<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;
use App\Models\DepartmentUser;
use App\Models\Department;
use App\Models\Prabhag;
use App\Models\PrabhagWard;
use App\Models\WaterPrabhag;
use App\Models\WaterPrabhagWards;
use App\Models\Ward;
use Spatie\Permission\Models\Role;

class StoreUserRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $rules = [
            'role' => 'required',
            'name' => 'required',
            'email' => 'required|email|unique:users,email',
            'mobile' => 'required|digits:10|unique:users,mobile',
            'password' => 'required|min:8',
            'confirm_password' => 'required|same:password',
            'departments' => 'required|array',
            'departments.*' => 'required|integer',
        ];

        // Dynamic validation for each department submitted
        $departments = $this->input('departments', []);
        foreach ($departments as $index => $deptId) {
            if ($deptId == 5) { // Water Department
                $rules["water_prabhag.$index"] = 'required|array';
                $rules["water_prabhag.$index.*"] = 'required|integer';
                $rules["prabhagward.$index"] = 'required|array';
                $rules["prabhagward.$index.*"] = 'required|integer';
            } elseif ($deptId == 4) { // Normal Prabhag
                $rules["prabhag.$index"] = 'required|array';
                $rules["prabhag.$index.*"] = 'required|integer';
                $rules["prabhagward.$index"] = 'required|array';
                $rules["prabhagward.$index.*"] = 'required|integer';
            } else { // General Departments
                $rules["wards.$index"] = 'required|array';
                $rules["wards.$index.*"] = 'required|integer';
            }
        }

        return $rules;
    }

   public function messages(): array
{
    return [
        'role.required' => 'Please select a user role.',
        'name.required' => 'Please enter the user name.',
        'email.required' => 'Please enter a valid email address.',
        'email.unique' => 'This email is already taken.',
        'mobile.required' => 'Please enter mobile number.',
        'mobile.digits' => 'Mobile number must be 10 digits.',
        'mobile.unique' => 'This mobile number is already taken.',
        'password.required' => 'Please enter a password.',
        'password.min' => 'Password must be at least 8 characters.',
        'confirm_password.required' => 'Please confirm your password.',
        'confirm_password.same' => 'Confirm password must match the password.',
        'departments.required' => 'Please select at least one department.',
        'departments.*.required' => 'Please select a  department.',

        // ✅ Water Department
        'water_prabhag.*.required' => 'Please select at least one water prabhag for each department.',
        'water_prabhag.*.*.required' => 'Please select a  water prabhag.',
        'prabhagward.*.required' => 'Please select at least one ward for each water prabhag.',
        'prabhagward.*.*.required' => 'Please select a  ward for the selected water prabhag.',

        // ✅ Normal Prabhag
        'prabhag.*.required' => 'Please select at least one prabhag for each department.',
        'prabhag.*.*.required' => 'Please select a  prabhag.',
        'prabhagward.*.required' => 'Please select at least one ward for each prabhag.',
        'prabhagward.*.*.required' => 'Please select a  ward for the selected prabhag.',

        // ✅ General Departments
        'wards.*.required' => 'Please select at least one ward for each department.',
        'wards.*.*.required' => 'Please select a  ward.',
    ];
}


    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $roleId = $this->input('role');
            $roleName = Role::find($roleId)->name ?? 'Unknown Role';
            $departments = $this->input('departments', []);

            $duplicateItems = [];

            foreach ($departments as $index => $departmentId) {
                $departmentName = Department::find($departmentId)->name ?? 'Unknown Department';

                if ($departmentId == 5) { // Water Department
                    $prabhags = (array) ($this->input("water_prabhag.$index") ?? []);
                    $wards = (array) ($this->input("prabhagward.$index") ?? []);

                    foreach ($prabhags as $prabhagId) {
                        $waterPrabhagName = WaterPrabhag::find($prabhagId)->name ?? $prabhagId;
                        foreach ($wards as $wardId) {
                            $wardName = WaterPrabhagWards::find($wardId)->ward_name ?? $wardId;
                            $exists = DepartmentUser::where('department_id', $departmentId)
                                ->where('prabhag', $prabhagId)
                                ->where('ward_name', $wardId)
                                ->whereHas('user.roles', fn($q) => $q->where('roles.id', $roleId))
                                ->exists();
                            if ($exists) {
                                $duplicateItems[] = "({$departmentName}, {$waterPrabhagName} - Ward: {$wardName})";
                            }
                        }
                    }
                } elseif ($departmentId == 4) { // Normal Prabhag
                    $prabhags = (array) ($this->input("prabhag.$index") ?? []);
                    $wards = (array) ($this->input("prabhagward.$index") ?? []);

                    foreach ($prabhags as $prabhagId) {
                        $prabhagName = Prabhag::find($prabhagId)->name ?? $prabhagId;
                        foreach ($wards as $wardId) {
                            $wardName = PrabhagWard::find($wardId)->ward_name ?? $wardId;
                            $exists = DepartmentUser::where('department_id', $departmentId)
                                ->where('prabhag', $prabhagId)
                                ->where('ward_name', $wardId)
                                ->whereHas('user.roles', fn($q) => $q->where('roles.id', $roleId))
                                ->exists();
                            if ($exists) {
                                $duplicateItems[] = "({$departmentName}, Prabhag: {$prabhagName} - Ward: {$wardName})";
                            }
                        }
                    }
                } else { // General Departments
                    $wards = (array) ($this->input("wards.$index") ?? []);
                    foreach ($wards as $wardId) {
                        $wardName = Ward::find($wardId)->name ?? $wardId;
                        $exists = DepartmentUser::where('department_id', $departmentId)
                            ->where('ward_name', $wardId)
                            ->whereHas('user.roles', fn($q) => $q->where('roles.id', $roleId))
                            ->exists();
                        if ($exists) {
                            $duplicateItems[] = "({$departmentName} - Ward: {$wardName})";
                        }
                    }
                }
            }

            if (!empty($duplicateItems)) {
                $validator->errors()->add('duplicate_ward', "User with role '{$roleName}' is already assigned to: " . implode(', ', $duplicateItems));
            }
        });
    }
}
