<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\User;
use App\Helpers\Helper;
use App\Models\UserBranch;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class CoController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:Co List', ['only' => ['index']]);
        $this->middleware('permission:Co Create', ['only' => ['store']]);
        $this->middleware('permission:Co Edit', ['only' => ['store']]);
        $this->middleware('permission:Co Delete', ['only' => ['destroy']]);
    }

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

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

    public function store(Request $request)
    {
        if($request->id=='')
        {
            $this->validate($request, [
                'name' => 'required',
                'gender' => 'required',
                'id_card' => 'nullable|max:20|unique:users,id_card,' . $request->id,
            ]);
        }
        try{
            DB::beginTransaction();
            $co = User::updateOrCreate(['id' => $this->getRequest($request)['id']],$this->getRequest($request));
            $co->syncRoles($request->role_id);
            if(empty($request->id))
            {
                $user_branch = new UserBranch();
                $user_branch->user_id = $co->id;
                $user_branch->branch_id = $co->branch_id;
                $user_branch->save();
            }
            DB::commit();
            $res = [
                'status' => 1,
                'message'=> $co->wasRecentlyCreated?'Create co success':'Update co success',
                'data'   => new UserResource($co),
            ];
        }catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Create co 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==2?(Helper::codeCOAuto(User::class, Helper::prefix(),6, 'code')):''),
            'name'               => $request->name,
            'branch_id'          => Auth::user()->branch_id,
            'currency_id'        => Auth::user()->currency_id,
            'nickname'           => $request->nickname,
            'gender'             => $request->gender,
            '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,
            'date_start_working' => $request->date_start_working,
            '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',
            'password'           => Hash::make($request->password),
        ];

        if(empty($request->password)){
            $data = Arr::except($data,array('password'));
        }
        return $data;
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        //
    }

    public function update(Request $request, $id)
    {
        DB::beginTransaction();
        try {

            $co = User::find($id);
            $co->status = $co->status==1?2:1;
            $co->update();
            $res = [
                'status' => 1,
                'message'=> $co->status==1?'Co is active now!':'Co is inactive now!',
                'data'   => $co,
            ];
            DB::commit();
        } catch(Exception $e){
            DB::rollBack();

            $co = User::find($id);
            $res = [
                'status'  => 0,
                'message' => $co->status==1?'Co is active not successfully':'Co is inactive not successfully',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }

    public function destroy($id)
    {
        //
    }
}