<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Employee;
use Illuminate\Http\Request;
use App\Models\CompanyInformation;
use App\Models\Departmant;
use App\Models\EmployeeDepartment;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Spatie\Permission\Models\Role;
use App\Models\User_details;

class UserApiController extends Controller
{
    public function getAllRoles()
    {
        // Assuming you have a Role model to fetch roles from the database
        $roles = Role::all();

        return response()->json([
            'status' => 'success',
            'data' => $roles
        ]);
    }

    public function createUser(Request $request)
    {
        // return response()->json($request->all());
        // Validate the incoming request data
        $company_info = CompanyInformation::latest()->first();

        $user = User::where('email', $request->email)->first();
        if ($user) {
            return response()->json([
                'status' => 'error',
                'message' => $company_info->name . ' already has an account with this email.'
            ], 400);
        }


        DB::beginTransaction();
        try {
            // Create the user
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => $request->password,
                'user_balance_check' => 'no',
                'user_accounting_status' => "yes",
                'mobile_number' => $request->mobile_number,
                'voucher_softwate_user_id' => $request->voucher_softwate_user_id,

            ]);

            // Create associated employee record
            $employee = new Employee();
            $employee->name = $user->name;
            $employee->user_id = $user->id;
            $employee->admin_user_id = $user->id;
            $employee->mobile_office = $user->mobile_number;
            $employee->status = 'active';
            $employee->save();
            clearCache('employees');

            DB::table('user_details')->insert([
                'user_id' => $user->id,
                'company' => $company_info->name ?? '',
                'message' => $request->message ?? '',
                'token_admin' => 'no',
                'user_status' => $request->user_status ?? 'active',
                'created_at' => Carbon::now(),

            ]);


            // update departments
            $thisSoftwareDeaprtments = Departmant::whereIn('voucer_software_id', $request->departments)->get();
            EmployeeDepartment::where('employee_id', $employee->id)->delete();
            foreach ($thisSoftwareDeaprtments as $department) {
                EmployeeDepartment::create([
                    'employee_id'   => $employee->id,
                    'department_id' => $department->id,
                ]);
            }


            if (isset($request->assign_role)) {
                // Assign role to the user
                $user->assignRole($request->assign_role);
            }

            DB::commit();

            $data = [
                'user' => $user,
                $company_info
            ];

            return response()->json([
                'status' => 'success',
                'message' => 'User created successfully',
                'data' => $data
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();

            return response()->json([
                'status' => 'error',
                'message' => $company_info->name . ' user creation failed.',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function userRoleAssign(Request $request)
    {
        $user = User::where('email', $request->email)->first();
        if (!$user) {
            return response()->json([
                'status' => 'error',
                'message' => 'User not found with this email.'
            ], 404);
        }

        if (isset($request->assign_role)) {
            $user->assignRole($request->assign_role); // Sync roles to ensure only the provided role is assigned
            return response()->json([
                'status' => 'success',
                'message' => 'Role assigned successfully to the user.',
                'data' => [
                    'user' => $user,
                    'assigned_role' => $request->assign_role
                ]
            ]);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'No role provided for assignment.'
            ], 400);
        }
    }

    public function createOnlyUser($name, $status, $employee_id, $email, $password, $mobile_number, $voucher_softwate_user_id, $message = "")
    {
        $company_info = CompanyInformation::latest()->first();

        $user = User::create([
            'name' => $employee_id . '-' . $name,
            'email' => $email,
            'password' => $password,
            'user_balance_check' => 'no',
            'user_accounting_status' => "yes",
            'mobile_number' => $mobile_number,
            'voucher_softwate_user_id' => $voucher_softwate_user_id,
            'isActive' => $status,

        ]);

        // Create associated employee record
        $employee = new Employee();
        $employee->name = $user->name;
        $employee->user_id = $user->id;
        $employee->admin_user_id = $user->id;
        $employee->mobile_office = $user->mobile_number;
        $employee->status = 'active';
        $employee->save();
        clearCache('employees');

        DB::table('user_details')->insert([
            'user_id' => $user->id,
            'company' => $company_info->name ?? '',
            'message' => $message ?? '',
            'token_admin' => 'no',
            'user_status' => 'active',
            'created_at' => Carbon::now(),

        ]);




        return $user;
    }

    public function updateAllUserIdAndMobil(Request $request)
    {
        $request->validate([
            'email'  => 'required|email',
            'id'     => 'required',
            'mobile' => 'required|string',
            'name' => 'required|string',
        ]);

        $user = User::where('email', $request->email)->first();

        if (!$user) {
            return response()->json([
                'status'  => 'error',
                'message' => 'No user found',
            ], 404);
        }
        DB::beginTransaction();
        try {

            $user->voucher_softwate_user_id = $request->id;
            $user->mobile_number       = $request->mobile;
            $user->name                = $request->name;
            $user->save();

            $employee = Employee::where('admin_user_id', $user->id)->first();


            if ($employee) {
                $employee->mobile_office = $request->mobile;
                $employee->name          = $request->name;
                $employee->save();
            } else {
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Employee not found',
                ], 510);
            }

            DB::commit();

            return response()->json([
                'status'  => 'success',
                'message' => 'User updated successfully',
            ], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status'  => 'error',
                'message' => 'Update failed, please try again ' . $e->getMessage(),
            ], 500);
        }
    }

    public function userUpdateVoucherSoftwareId(Request $request)
    {
        // Fix array fields sent as JSON strings
        if (is_string($request->department_ids)) {
            $request->merge(['department_ids' => json_decode($request->department_ids, true)]);
        }
        if (is_string($request->role_ids)) {
            $request->merge(['role_ids' => json_decode($request->role_ids, true)]);
        }

        $request->validate([
            'voucher_software_id' => 'required|integer',
            'password_has'        => 'required|string',
            'department_ids'      => 'nullable|array',
            'role_ids'            => 'nullable|array',
            'name'                => 'required|string',
            'mobile_number'       => 'required|string',
            'email'               => 'required|email',
            'employee_id'         => 'required|string',
            'status'         => 'required|string',
        ]);

        DB::beginTransaction();
        try {
            $user = User::where('voucher_softwate_user_id', $request->voucher_software_id)->first();
            if($request->status == 'active'){
                $status_set = 'yes';
            }else{
                $status_set = 'no';
            }
            if (!$user) {
               
                $user = $this->createOnlyUser($request->name,$status_set, $request->employee_id , $request->email, $request->password_has, $request->mobile_number, $request->voucher_software_id);
                if (!$user) {
                    return response()->json([
                        'status'  => 'error',
                        'message' => 'User not created',
                    ], 500);
                }
            }

            $employee = Employee::where('admin_user_id', $user->id)->first();
            if (!$employee) {
                DB::rollBack();
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Employee not found',
                ], 404);
            }
           
            $user->password      = $request->password_has;
            $user->name          = $request->employee_id . '-' . $request->name;
            $user->mobile_number = $request->mobile_number;
            $user->isActive        = $status_set;
            $user->save();

            $user_detils = User_details::where('user_id',$user->id)->first();
            
            $user_detils->user_status = $request->status;
            $user_detils->save();
            

           
           
            $employee->name          = $request->employee_id . '-' . $request->name;
            $employee->mobile_office = $request->mobile_number;
            
            if($status_set != 'yes'){
                $employee->status = 'pending';

            }else{
                $employee->status = 'active';
            }
            $employee->save();

            // ✅ Sync departments only if provided
            EmployeeDepartment::where('employee_id', $employee->id)->delete();
            if (!empty($request->department_ids)) {
                $departments = Departmant::whereIn('voucer_software_id', $request->department_ids)->get();
                $newDepartments = $departments->map(fn($dept) => [
                    'employee_id'   => $employee->id,
                    'department_id' => $dept->id,
                ])->toArray();
                EmployeeDepartment::insert($newDepartments);
            }

            // ✅ Sync roles only if provided
            if (!empty($request->role_ids)) {
                $existingRoleIds = $user->roles->pluck('id')->toArray();
                $newRoleIds = array_diff($request->role_ids, $existingRoleIds);
                foreach ($newRoleIds as $role_id) {
                    $user->assignRole($role_id);
                }
            }

            // Log out the user if currently logged in
            if (Auth::check() && Auth::id() === $user->id) {
                Auth::guard('web')->logout();
                Session::flush();
            }

            DB::commit();
            return response()->json([
                'status'  => 'success',
                'message' => 'User updated successfully',
            ], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status'  => 'error',
                'message' => 'User update failed',
                'error'   => $e->getMessage(),
            ], 500);
        }
    }
}
