<?php

namespace App\Http\Controllers\System;

use App\Helpers\CustomDateFilter;
use Exception;
use App\Models\User;
use App\Helpers\Helper;
use Illuminate\Support\Arr;
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\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,
        );
    }
    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())
            ->where('type',$request->type)
            ->orderBy('id','DESC')
            ->paginate($page_size);

        return UserResource::collection($data);
    }

    public function create(Request $request){
        $user = User::find($request->id);
        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();
            $user = User::updateOrCreate(['id' => $this->getRequest($request)['id']],$this->getRequest($request));
            $user->syncRoles($request->role_id);
            if(empty($request->id))
            {
                $user_branch = new UserBranch();
                $user_branch->user_id = $user->id;
                $user_branch->branch_id = $user->branch_id;
                $user_branch->save();
            }
            $user_login = User::find(Auth::user()->id);
            if($request->id)
            {
                $subject = "កែប្រែអ្នកប្រើប្រាស់ $user->name ដោយ $user_login->name.";
            }
            else
            {
                $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';
            if ($user) {
                // $userDID= [];
                // if (count($request->user_details)>0) {
                //     foreach ($request->user_details as $key => $value) {
                //         if($value['selected']  == true){
                //             $userDetail = UserBranch::updateOrCreate([
                //                 'user_id' => $user->id,
                //                 'branch_id' => $value['id'],
                //             ]);
                //             $userDID []= $userDetail->id;
                //             $user->branch_id = $value['id'];
                //         }
                //     }
                // }
                // else{
                //     $userDetail = UserBranch::updateOrCreate([
                //         'user_id' => $user->id,
                //         'branch_id' => Auth::user()->branch_id,
                //     ]);
                // }
                // UserBranch::where('user_id',$user->id)->whereNotIn('id',$userDID)->delete();
                 UserBranch::updateOrCreate([
                    'user_id' => $user->id,
                    'branch_id' => Auth::user()->branch_id,
                ]);
                $user = User::find(Auth::user()->id);
            }
            $user->save();
            LogActivityHepler::addToLog($subject,$subject_type,$subject_id,$causer_type,$causer_id,$branch,$log_name);
            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 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 getRequest($request)
    {
        // if ($request->hasFile('attach_file')) {
        //     $file         = $request->file('attach_file');
        //     $path  = 'uploads/profiles/attach-files/';
        //     if ($request->id) {
        //         $oldFile = User::find($request->id)->attach_file;
        //     }
        //     $attach_file = Helper::uploadFile($file, $path, $oldFile ?? '');
        // }

        $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')):''),
            '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),
        ];
        if(empty($request->password)){
            $data = Arr::except($data,array('password'));
        }
        return $data;
    }

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

            }else{
                User::where('id',$id)->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 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);
    }
}