<?php

namespace App\Http\Controllers\Admin;

use App\Models\Role;
use App\Models\User;
use App\Models\Ward;
use App\Models\Prabhag;
use App\Models\Department;
use App\Models\PrabhagWard;
use Illuminate\Support\Arr;
use App\Models\WaterPrabhag;
use Illuminate\Http\Request;
use App\Models\DepartmentUser;
use App\Models\WaterPrabhagWards;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Admin\Controller;
use App\Http\Requests\Admin\StoreUserRequest;
use App\Http\Requests\Admin\UpdateUserRequest;
use App\Http\Requests\Admin\AssignUserRoleRequest;
use App\Http\Requests\Admin\ChangeUserPasswordRequest;

class UserController extends Controller
{
   public function __construct()
    {
        $this->middleware('permission:users.view')->only(['index', 'show']);
        $this->middleware('permission:users.create')->only(['create', 'store']);
        $this->middleware('permission:users.edit')->only(['edit', 'update', 'assignRole']);
        $this->middleware('permission:users.delete')->only(['destroy', 'retire']);
        $this->middleware('permission:users.toggle_status')->only(['toggle']);
        $this->middleware('permission:users.change_password')->only(['changePassword']);
    }
    public function index()
    {
       $users = User::where('id', '!=', Auth::id())
                ->whereDoesntHave('roles', function ($q) {
                    $q->where('name', 'User'); // Exclude users with "User" role
                })
                ->with(['departmentUser.department', 'roles']) // eager load departments and roles
                ->latest()
                ->get();
        // dd($users);
        $roles = Role::orderBy('id', 'DESC')->get();
        $departments = Department::orderBy('id', 'DESC')->get();
        $wards = Ward::orderBy('id', 'ASC')->get();
        $propertyprabhag = Prabhag::get();
        $propertyward = PrabhagWard::get();
        $waterPrabhag = WaterPrabhag::get();
        $waterPrabhagWard = WaterPrabhagWards::get();
        return view('admin.users')->with(['users' => $users, 'roles' => $roles, 'departments' => $departments, 'wards' => $wards, 'propertyprabhag' => $propertyprabhag, 'waterPrabhag' => $waterPrabhag]);
    }

    public function getWardsByPrabhag($id)
    {
        $ids = explode(',', $id);
        $wards = PrabhagWard::whereIn('prabhag_id', $ids)
            ->where('status', 1)
            ->select('id', 'ward_name', 'prabhag_id')
            ->with('prabhag')
            ->get()
            ->map(function ($ward) {

                return [
                    'id' => $ward->id,
                    'ward_name' => $ward->ward_name,
                    'prabhag_id' => $ward->prabhag_id,
                    'prabhag_name' => $ward->prabhag->name ?? '',
                ];
            });
        return response()->json($wards);
    }

    public function getWaterWardsByPrabhag($prabhangParam)
    {
        $ids = explode(',', $prabhangParam);
        $wards = WaterPrabhagWards::whereIn('prabhag_id', $ids)
            ->with('prabhag')
            ->get()
            ->map(function ($ward) {
                return [
                    'id' => $ward->id,
                    'ward_name' => $ward->ward_name,
                    'prabhag_id' => $ward->prabhag_id,
                    'prabhag_name' => $ward->prabhag->name ?? '',
                ];
            });
        return response()->json($wards);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create() {}
    /**
     * Store a newly created resource in storage. StoreUserRequest
     */
    public function store(StoreUserRequest $request)
{
    try {
        DB::beginTransaction();

        $input = $request->validated();

        // 1️⃣ Create user
        $user = User::create([
            'name'     => $input['name'],
            'email'    => $input['email'],
            'mobile'   => $input['mobile'],
            'password' => Hash::make($input['password']),
        ]);

        // 2️⃣ Assign role
        DB::table('model_has_roles')->insert([
            'role_id'    => $input['role'],
            'model_type' => 'App\Models\User',
            'model_id'   => $user->id,
        ]);

        // 3️⃣ Loop through all departments
        foreach ($input['departments'] as $index => $departmentId) {

            // Water Department
            if ($departmentId == 5) {
                $prabhags = $input['water_prabhag'][$index] ?? [];
                $wards = $input['prabhagward'][$index] ?? [];

                foreach ($wards as $wardId) {
                    $ward = \App\Models\WaterPrabhagWards::find($wardId);
                    if ($ward) {
                        DepartmentUser::insert([
                            'user_id'       => $user->id,
                            'department_id' => $departmentId,
                            'ward_name'     => $ward->id,
                            'prabhag'       => $ward->prabhag_id,
                            'created_at'    => now(),
                            'updated_at'    => now(),
                        ]);
                    }
                }
            }
            // Normal Prabhag Department
            elseif ($departmentId == 4) {
                $prabhags = $input['prabhag'][$index] ?? [];
                $wards = $input['prabhagward'][$index] ?? [];

                foreach ($wards as $wardId) {
                    $ward = \App\Models\PrabhagWard::find($wardId);
                    if ($ward) {
                        DepartmentUser::insert([
                            'user_id'       => $user->id,
                            'department_id' => $departmentId,
                            'ward_name'     => $ward->id,
                            'prabhag'       => $ward->prabhag_id,
                            'created_at'    => now(),
                            'updated_at'    => now(),
                        ]);
                    }
                }
            }
            // General Wards
            else {
                $wards = $input['wards'][$index] ?? [];
                foreach ($wards as $wardId) {
                    DepartmentUser::insert([
                        'user_id'       => $user->id,
                        'department_id' => $departmentId,
                        'ward_name'     => $wardId,
                        'prabhag'       => null,
                        'created_at'    => now(),
                        'updated_at'    => now(),
                    ]);
                }
            }
        }

        DB::commit();
        return response()->json(['success' => 'User created successfully!']);
    } catch (\Exception $e) {
        DB::rollBack();
        Log::error("Error while creating User: " . $e->getMessage());
        return $this->respondWithAjax($e, 'creating', 'User');
    }
}


    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     */
    // public function edit(User $user)
    // {
    //     try {
    //         $roles = Role::all();
    //         $user->loadMissing('roles');
    //         $departments = DepartmentUser::where('user_id', $user->id)->get();

    //         // if ($departments->isEmpty()) {
    //         //     return response()->json(['result' => 0, 'message' => 'No department data found.']);
    //         // }
    //         $roleHtml = '<span><select>';
    //         $roleHtml .= '<option value="">--Select Role--</option>';
    //         foreach ($roles as $role) {
    //             $is_select = ($user->roles->isNotEmpty() && $role->id == $user->roles->first()->id)
    //                 ? "selected"
    //                 : "";
    //             $roleHtml .= '<option value="' . $role->id . '" ' . $is_select . '>' . e($role->name) . '</option>';
    //         }
    //         $roleHtml .= '</select></span>';
    //         $wardIds = [];
    //         $prabhagIds = [];
    //         $waterPrabhagIds = [];
    //         $prabhagwardIds = [];
    //         $departmentId = null;
    //         foreach ($departments as $department) {
    //             $departmentId = $department->department_id;
    //             if ($department->department_id == 5) {
    //                 if (!empty($department->ward_name)) {
    //                     $wardIds[] = $department->ward_name;
    //                 }

    //                 if (!empty($department->prabhag)) {
    //                     $waterPrabhagIds[] = $department->prabhag;

    //                     $wardMatch =\App\Models\WaterPrabhagWards::where('prabhag_id', $department->prabhag)
    //                         ->where('id', $department->ward_name)
    //                         ->first();

    //                     if ($wardMatch) {
    //                         $prabhagwardIds[] = $wardMatch->id;
    //                     }
    //                 }
    //             }
    //             elseif ($department->department_id == 4) {
    //                 if (!empty($department->ward_name)) {
    //                     $wardIds[] = $department->ward_name;
    //                 }

    //                 if (!empty($department->prabhag)) {
    //                     $prabhagIds[] = $department->prabhag;

    //                     $wardMatch = \App\Models\PrabhagWard::where('prabhag_id', $department->prabhag)
    //                         ->where('id', $department->ward_name)
    //                         ->first();

    //                     if ($wardMatch) {
    //                         $prabhagwardIds[] = $wardMatch->id;
    //                     }
    //                 }
    //             }
    //             else {
    //                 if (!empty($department->ward_name)) {
    //                     $wardIds[] = $department->ward_name;
    //                 }
    //             }
    //         }
    //         return response()->json([
    //             'result'             => 1,
    //             'user'               => $user,
    //             'roleHtml'           => $roleHtml,
    //             'department_id'      => $departmentId,
    //             'ward_ids'           => $wardIds,
    //             'prabhag_ids'        => $prabhagIds,
    //             'water_prabhag_ids'  => $waterPrabhagIds,
    //             'prabhagward_ids'    => $prabhagwardIds,
    //         ]);
    //     } catch (\Exception $e) {
    //         Log::error("Error in edit User: " . $e->getMessage());
    //         return response()->json(['result' => 0, 'error' => $e->getMessage()]);
    //     }
    // }
public function edit(User $user)
{
    $roles = Role::orderBy('id', 'DESC')->get();
    $departments = Department::orderBy('id', 'DESC')->get();
    $wards = Ward::orderBy('id', 'ASC')->get();
    $propertyPrabhags = Prabhag::all();

    $waterPrabhags = WaterPrabhag::all();

    $departmentUserData = DepartmentUser::where('user_id', $user->id)->get();

    $userDepartments = [];

    foreach ($departmentUserData->groupBy('department_id') as $deptId => $deptUsers) {

        $prabhag_ids = [];
        $water_prabhag_ids = [];
        $ward_ids = [];
        $prabhagWard_ids = []; // preload prabhag wards

        if ($deptId == 5) { // Water Department
            $water_prabhag_ids = $deptUsers->pluck('prabhag')->unique()->filter()->toArray();
            $prabhagWard_ids = WaterPrabhagWards::whereIn('id', $deptUsers->pluck('ward_name'))->pluck('id')->toArray();
        } elseif ($deptId == 4) { // Property Department
            $prabhag_ids = $deptUsers->pluck('prabhag')->unique()->filter()->toArray();
            $prabhagWard_ids = PrabhagWard::whereIn('id', $deptUsers->pluck('ward_name'))->pluck('id')->toArray();
        } else { // Other departments
            $ward_ids = $deptUsers->pluck('ward_name')->toArray();
        }

        $userDepartments[] = [
            'department_id'      => $deptId,
            'prabhag_ids'        => $prabhag_ids,
            'water_prabhag_ids'  => $water_prabhag_ids,
            'ward_ids'           => $ward_ids,
            'prabhagWard_ids'    => $prabhagWard_ids,
        ];
     }


    return view('admin.user.edit_new', compact(
        'user',
        'roles',
        'departments',
        'wards',
        'propertyPrabhags',
        'waterPrabhags',
        'userDepartments'
    ));
}







    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateUserRequest $request, User $user)
{
    try {
        DB::beginTransaction();

        $input = $request->validated();

        // Update basic user info
        $user->update([
            'name'   => $input['name'],
            'email'  => $input['email'],
            'mobile' => $input['mobile'],
        ]);

        // Update role
        $user->roles()->detach();
        DB::table('model_has_roles')->insert([
            'role_id'    => $input['role'],
            'model_type' => 'App\Models\User',
            'model_id'   => $user->id,
        ]);

        // Clear old department assignments
        DepartmentUser::where('user_id', $user->id)->delete();

        $departments = $input['departments'] ?? [];

        foreach ($departments as $index => $departmentId) {
            if ($departmentId == 5) {
                // Water Department

                
                $prabhags = $input["water_prabhag"][$index] ?? [];
                $wards = $input["prabhagward"][$index] ?? [];
                foreach ($prabhags as $prabhagId) {
                    foreach ($wards as $wardId) {
                        $ward_temp = WaterPrabhagWards::find($wardId);
                        if ($ward_temp) {
                            DepartmentUser::insert([
                                'user_id'       => $user->id,
                                'department_id' => $departmentId,
                                'ward_name'     => $ward_temp->id,
                                'prabhag'       => $prabhagId,
                                'created_at'    => now(),
                                'updated_at'    => now(),
                            ]);
                        }
                    }
                }
            } elseif ($departmentId == 4) {
                // Normal Prabhag Department
                $prabhags = $input["prabhag"][$index] ?? [];
                $wards = $input["prabhagward"][$index] ?? [];

                foreach ($prabhags as $prabhagId) {
                    foreach ($wards as $wardId) {
                        $ward_temp = PrabhagWard::find($wardId);
                        if ($ward_temp) {
                            DepartmentUser::insert([
                                'user_id'       => $user->id,
                                'department_id' => $departmentId,
                                'ward_name'     => $ward_temp->id,
                                'prabhag'       => $prabhagId,
                                'created_at'    => now(),
                                'updated_at'    => now(),
                            ]);
                        }
                    }
                }
            } else {
                // Other departments (general wards)
                $wards = $input['wards'][$index]?? [];
                foreach ($wards as $wardId) {
                    DepartmentUser::insert([
                        'user_id'       => $user->id,
                        'department_id' => $departmentId,
                        'ward_name'     => $wardId,
                        'prabhag'       => null,
                        'created_at'    => now(),
                        'updated_at'    => now(),
                    ]);
                }
            }
        }

        DB::commit();
        return response()->json(['success' => 'User updated successfully!']);
    } catch (\Exception $e) {
        DB::rollBack();
        Log::error("Error while updating User: " . $e->getMessage());
        return response()->json(['error' => 'Something went wrong while updating user.'], 500);
    }
}






    /**
     * Remove the specified resource from storage.
     */


    public function toggle(Request $request, User $user)
    {
        $current_status = DB::table('users')->where('id', $user->id)->value('active_status');
        try {
            DB::beginTransaction();
            if ($current_status == '1') {
                User::where('id', $user->id)->update(['active_status' => '0']);
            } else {
                User::where('id', $user->id)->update(['active_status' => '1']);
            }
            DB::commit();
            return response()->json(['success' => 'User status updated successfully']);
        } catch (\Exception $e) {
            return $this->respondWithAjax($e, 'changing', 'User\'s status');
        }
    }

    public function retire(Request $request, User $user)
    {
        try {
            DB::beginTransaction();
            $user->delete();
            DB::commit();
            return response()->json(['success' => 'Employee retired successfully']);
        } catch (\Exception $e) {
            return $this->respondWithAjax($e, 'changing', 'Employee\'s retirement status');
        }
    }

    public function changePassword(ChangeUserPasswordRequest $request, User $user)
    {
        $input = $request->validated();
        try {
            DB::beginTransaction();
            $user->update(['password' => Hash::make($input['new_password'])]);
            DB::commit();
            return response()->json(['success' => 'Password updated successfully']);
        } catch (\Exception $e) {
            return $this->respondWithAjax($e, 'changing', 'User\'s password');
        }
    }


    public function getRole(User $user)
    {
        $user->load('roles');
        if ($user) {
            $roles = Role::orderBy('id', 'DESC')->get();
            $roleHtml = '<span>
                <option value="">--Select Role--</option>';
            foreach ($roles as $role):
                $is_select = $role->id == $user->roles[0]->id ? "selected" : "";
                $roleHtml .= '<option value="' . $role->id . '" ' . $is_select . '>' . $role->name . '</option>';
            endforeach;
            $roleHtml .= '</span>';

            $response = [
                'result' => 1,
                'user' => $user,
                'roleHtml' => $roleHtml,
            ];
        } else {
            $response = ['result' => 0];
        }
        return $response;
    }


    public function assignRole(User $user, AssignUserRoleRequest $request)
    {
        try {
            DB::beginTransaction();
            $user->roles()->detach();
            DB::table('model_has_roles')->insert(['role_id' => $request->edit_role, 'model_type' => 'App\Models\User', 'model_id' => $user->id]);
            DB::commit();
            return response()->json(['success' => 'Role updated successfully']);
        } catch (\Exception $e) {
            return $this->respondWithAjax($e, 'changing', 'User\'s role');
        }
    }



    public function destroy(User $user)
    {
        try {
            DB::beginTransaction();

            $user->delete();

            DB::commit();
            return response()->json(['success' => 'User deleted successfully!']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['error' => 'Error deleting user: ' . $e->getMessage()], 500);
        }
    }
}
