<?php

namespace App\Http\Controllers\System;

use App\Helpers\CustomDateFilter;
use Exception;
use App\Models\User;
use App\Helpers\Helper;
use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Resources\LogResource;
use App\Http\Resources\UserResource;
use App\Models\Currency;
use App\Models\LogActivity;
use App\Helpers\LogActivity as LogActivityHepler;
use App\Models\Branch;
use App\Models\UserBranch;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Permission;

class UserController extends Controller
{

    public function getUser(){

        $user =  Auth::user();
        $branches = UserBranch::select('branches.*')
        ->where('user_branches.user_id',$user->id)
        ->leftjoin('branches','branches.id','user_branches.branch_id')
        ->groupBy('user_branches.branch_id')
        ->get();

        $length     = $branches->count();
        $currency   = $user->currency_id;
        $currencies = Currency::get();

        return array(
            'user'        => $user,
            'branch'      => $branches,
            'length'      => $length,
            'currency'    => $currency,
            'currencies'  => $currencies,
            'branch_name' => $user->branchs->name_km??'',
        );
    }

    public function index(Request $request)
    {
        $page_size = $request->page_size == null?25: $request->page_size;
        $data = User::search($request->search_text)
            ->whereIn('branch_id',Helper::byBranch())
            ->orderBy('id','DESC')
            ->paginate($page_size);
        return UserResource::collection($data);
    }

    public function create(Request $request){
        $userID = decrypt_id($request->id);
        $user = User::find($userID);
        if($user){
            $res = [
                'status' => 1,
                'message'=> 'Get user success',
                'data'   => new UserResource($user),
            ];
        }else{
            $user_details = new User;
            $res = [
                'status'  => 0,
                'message' => 'Get user not found',
                'data'    => [],
                'user_details' => $user_details->userBranchSelect(),
            ];
        }
        return response()->json($res,200);
    }

    public function store(UserRequest $request)
    {

        try {
            DB::beginTransaction();
            $userID = !empty($request->id) ? decrypt_id($request->id) : null;

            if (!empty($userID)) {
                $userOldPassword = User::find($userID);
            }

            $password = $request->password ? Hash::make($request->password): ($userOldPassword->password ?? '');
            $selectBranchID = collect($request->user_details)->firstWhere('selected', true)['id'] ?? Auth::user()->branch_id;

            if ($request->is_representative && $request->representative_brand_id) {
                $existingRep = User::where('representative_brand_id', $request->representative_brand_id)
                    ->where('is_representative', true)
                    ->where('id', '!=', $userID)  // FIXED
                    ->first();


                if ($existingRep) {
                    return response()->json([
                        'status' => 0,
                        'message' => 'This brand already has a representative.',
                    ]);
                }

                $existingUserRep = User::where('id', $userID ?? 0)
                    ->where('is_representative', true)
                    ->where('representative_brand_id', '!=', $request->representative_brand_id)
                    ->first();

                if ($existingUserRep) {
                    return response()->json([
                        'status' => 0,
                        'message' => 'This user is already a representative for another brand and cannot be assigned to a new one.',
                    ]);
                }
            }
            $user = User::updateOrCreate(
                ['id' => $userID],
                [
                    'code'              => $request->code ?? Helper::codeUserAuto(User::class,4,'code'),
                    'name'              => $request->name,
                    'nickname'          => $request->nickname,
                    // 'branch_id'         => $userID ? $request->branch_id : $selectBranchID,
                    'branch_id'         => $selectBranchID,
                    'currency_id'       => Auth::user()->currency_id,
                    'gender'            => $request->gender,
                    'dob'               => $request->dob,
                    'email'             => $request->email,
                    'contact_number'    => $request->contact_number,
                    'type'              => $request->type,
                    'address'           => $request->address,
                    'type_document'     => $request->type_document,
                    'id_card'           => $request->id_card,
                    'date_of_birth'     => $request->date_of_birth,
                    'place_of_birth'    => $request->place_of_birth,
                    'create_card_date'  => $request->create_card_date,
                    'expired_card_date' => $request->expired_card_date,
                    'institution'       => $request->institution,
                    'position'          => $request->position,
                    'work_place'        => $request->work_place,
                    'province_id'       => $request->province_id,
                    'district_id'       => $request->district_id,
                    'commune_id'        => $request->commune_id,
                    'village_id'        => $request->village_id,
                    'status'            => $request->status ?? 1,
                    'is_representative' => $request->is_representative ?? false,
                    'representative_brand_id' => $request->representative_brand_id ?? null,
                    'photo'             => $photo ?? 'uploads/profiles/default.png',
                    'password'          => $password,
                ]
            );
            $user->syncRoles($request->role_id);

            $isRepresentative = false;
            $representativeBranchId = null;

            // =========== 1.Use for more branch =========== //
            // $userDID = [];
            // if (!empty($request->user_details) && count($request->user_details) > 0) {
            //     foreach ($request->user_details as $key => $value) {
            //         if (!empty($value['selected']) && $value['selected'] == true) {
            //             $userDetail = UserBranch::updateOrCreate(
            //                 [
            //                     'user_id'   => $user->id,
            //                     'branch_id' => $value['id'],
            //                 ]
            //             );
            //             $userDID[] = $userDetail->id;

            //             if (!empty($value['is_representative']) && $value['is_representative'] == true) {
            //                 $isRepresentative = true;
            //                 $representativeBranchId = $value['id'];
            //             }
            //         }
            //     }
            // } else {
            //     $userDetail = UserBranch::updateOrCreate([
            //         'user_id'   => $user->id,
            //         'branch_id' => Auth::user()->branch_id,
            //     ]);
            // }
            // UserBranch::where('user_id', $user->id)->where('branch_id',$user->branch_id)->whereNotIn('id', $userDID)->delete();
            // =========== End Use for more branch =========== //

            // =========== Use for single branch =========== //
            UserBranch::updateOrCreate([
                'user_id'   => $user->id,
                'branch_id' => Auth::user()->branch_id,
            ]);
            // =========== End Use for single branch =========== //

            $user->is_representative = $isRepresentative;
            $user->representative_branch_id = $representativeBranchId;
            $user->save();

            $user_login = User::find(Auth::user()->id);
            $subject    = $request->id ? "កែប្រែអ្នកប្រើប្រាស់ $user->name ដោយ $user_login->name.": "បង្កើតអ្នកប្រើប្រាស់ $user->name ដោយ $user_login->name.";
            LogActivityHepler::addToLog($subject, get_class($user), $user->id, get_class($user), Auth::user()->id,Auth::user()->branch_id, 'User Model');
            DB::commit();

            $res = [
                'status' => 1,
                'message'=> $user->wasRecentlyCreated ? 'Create user success' : 'Update user success',
                'data'   => new UserResource($user),
            ];
        } catch(Exception $e) {
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Create user not success',
                'data'    => $e->getMessage(),
            ];
        }

        return response()->json($res, 200);
    }


    // public function getRequest($request)
    // {
    //     $oldFile = User::find($request->id);
    //     $photo = Helper::Base64Upload($request->photo, 'uploads/profiles/', $oldFile->photo ?? '');

    //     $data = [
    //         'id'            => $request->id,
    //         // 'code'          => $request['code']??($request->type==1?(Helper::codeUserAuto(User::class, Helper::prefix(),6, 'code')):''),
    //         'code'      => $request->code??Helper::codeUserAuto(User::class,4,'code'),
    //         'name'          => $request->name,
    //         'nickname'      => $request->nickname,
    //         'branch_id'      => Auth::user()->branch_id,
    //         'currency_id'      => Auth::user()->currency_id,
    //         'gender'        => $request->gender,
    //         'dob'           => $request->dob,
    //         'email'         => $request->email,
    //         'contact_number'=> $request->contact_number,
    //         'type'          => $request->type,
    //         'address'       => $request->address,
    //         'type_document' => $request->type_document,
    //         'id_card' => $request->id_card,
    //         'date_of_birth' => $request->date_of_birth,
    //         'place_of_birth' => $request->place_of_birth,
    //         'create_card_date' => $request->create_card_date,
    //         'expired_card_date' => $request->expired_card_date,
    //         'institution' => $request->institution,
    //         'position' => $request->position,
    //         'work_place' => $request->work_place,
    //         'province_id' => $request->province_id,
    //         'district_id' => $request->district_id,
    //         'commune_id' => $request->commune_id,
    //         'village_id' => $request->village_id,
    //         'status'     => $request->status??1,
    //         'photo'         => $photo??'uploads/profiles/default.png',
    //         // 'attach_file'   => $attach_file ?? $request->attach_file,
    //         'password'      => Hash::make($request->password),
    //         'is_representative'    => $oldFile->is_representative ?? false,
    //         'representative_branch_id' => $oldFile->representative_branch_id ?? null,
    //     ];
    //     if(empty($request->password)){
    //         $data = Arr::except($data,array('password'));
    //     }
    //     return $data;
    // }

    public function updateProfile(Request $request,$id){

        $this->validate($request, [
            'name' => 'required',
            'password' => 'required',
            'new_password' => 'required|same:confirm_password',
            'email' => 'required|unique:users,email,'.$id,
        ]);
        try{
            DB::beginTransaction();
            $user = User::find($id);
            $user->name  = $request->name;
            $user->email = $request->email;
            if (Hash::check($request->password, $user->password)) {
                $user->password = Hash::make($request->get('new_password'));
                if ($request->new_password != $request->confirm_password) {
                    $res = [
                        'status'  => 0,
                        'message' => 'New password and confirm password not match',
                        'data'    => [],
                    ];
                }
                if($user->save()){
                    $res = [
                        'status'  => 1,
                        'message' => 'Password updated successfully!',
                        'data'    => new UserResource($user),
                    ];
                }
            }
            else{
                $res = [
                    'status'  => 0,
                    'message' => 'The old password not match with password!',
                    'data'    => [],
                ];
            }
            $user_login = User::find(Auth::user()->id);
            $subject = "កែប្រែប្រវត្តិរូបរបស់ខ្លួនឯង $user->name ដោយ $user_login->name.";
            $subject_type = get_class($user);
            $subject_id = $user->id;
            $causer_type = get_class($user);
            $causer_id = Auth::user()->id;
            $branch = Auth::user()->branch_id;
            $log_name = 'User Model';
            LogActivityHepler::addToLog($subject,$subject_type,$subject_id,$causer_type,$causer_id,$branch,$log_name);
        }catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Update My Profile not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }



    public function activeAction($id)
    {
        DB::beginTransaction();
        try {
            $accID = decrypt_id ($id);
            $users = User::find($accID);
            // dd($accID);
            DB::commit();
            if( $users -> status ==1)
            {
                User::where('id',$accID)->update(['status' => 2]);
                $res = [
                    'status'  => 1,
                    'message' => "User's Active",
                    'data'    => $users,
                ];

            }else{
                User::where('id',$accID)->update(['status' => 1]);
                $res = [
                    'status'  => 2,
                    'message' => "User's Inactive",
                    'data'    => $users,
                ];
            }
        } catch (Exception $e) {
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res, 200);
    }
    public function switchBranch($id)
    {
        $user = User::find(Auth::user()->id);
        $user->branch_id = $id;
        $user->update();
        return $id;
    }
    public function switchCurrency($id)
    {
        $user = User::find(Auth::user()->id);
        $user->currency_id = $id;
        $user->update();
        return $id;
    }

    public function getUserBranch(){
        // return  Auth::user()->branch_id;
        return array(
            'branch_id' =>  Auth::user()->branch_id??'',
            'user_type' =>  Auth::user()->type??'',
        );
    }
    public function getBranchName(){
        return Branch::get()->map(function($value){
            return [
                'name' => $value->branch_code,
            ];
        });
    }

    public function getUserPermission()
    {
        $permissions = [];
        foreach (Permission::all() as $permission) {
            if (Auth::user()->can($permission->name)) {
                $permissions[] = $permission->name;
            }
        }
        return $permissions;
    }
    public function getLogactivity(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = LogActivity::where(function($query) use ($request){
            $query->whereIn('branch_id',Helper::byBranch());
            if(!$request->date == []) {
                if($request->date['0'] != 'null' || $request->date['1'] != 'null')
                {
                    $query->whereBetween(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"), $request->date ?? CustomDateFilter::allDay());
                }
            }
            if(!$request->user_id ==[]){
                $query->whereIn('causer_id',$request->user_id);
            }
        })
        ->orderby('id','desc')
        ->paginate($per_page);
        return LogResource::collection($data);
    }
}
