<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Branch;
use App\Helpers\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Resources\BranchResource;

class BranchController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:Branch List', ['only' => ['index']]);
        $this->middleware('permission:Branch Create', ['only' => ['store']]);
        $this->middleware('permission:Branch Edit', ['only' => ['store']]);
        $this->middleware('permission:Branch Delete', ['only' => ['destroy']]);
    }
    public function index(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = Branch::orderBy('id','DESC')->paginate($per_page);
        return BranchResource::collection($data);
        
    }
   
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $branchID = decrypt_id($request->id);
        $branch = Branch::find($branchID);
        
        if($branch){
            $res = [
                'status' => 1,
                'message'=> 'Create branch success',
                'data'   => $branch,
            ];
        }else{
            $res = [
                'status'  => 0,
                'message' => 'Create branch not found',
                'data'    => [],
            ];
        }
        return response()->json($res,200);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name_en' => 'nullable|required',
            'name_km' => 'nullable|required',
        ]);
        try{
            DB::beginTransaction();
            $com = Branch::updateOrCreate(['id' => $this->getBranchRequest($request)['id']],$this->getBranchRequest($request));

            DB::commit();
            $res = [
                'status' => 1,
                'message'=> $com->wasRecentlyCreated?'Create Branch success':'Update Branch success',
                'data'   => $com,
            ];
        }catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Create Branch not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }

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

            $branch = Branch::find($id);
            $branch->delete();
            $res = [
                'status' => 1,
                'message'=> 'Deleted success',
                'data'   => $branch,
            ];
            DB::commit();
        }catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Deleted not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }
    
    public function getBranchRequest($request)
    {
        // dd($request->id);
        $company = Branch::find($request->id);
        $image = Helper::Base64Upload($request->image, 'uploads/bank_qr/',  $company->image??'');
        $image1 = Helper::Base64Upload($request->image1, 'uploads/bank_qr/',  $company->image1??'');
        $data = [
            'id'        => $request->id,
            'name_km' => $request->name_km,
            'name_en' => $request->name_en,
            'phone' => $request->phone,
            'address' => $request->address,
            'image' => $image,
            'image1' => $image1,
            'province_id' => $request->province_id,
            'district_id' => $request->district_id,
            'commune_id' => $request->commune_id,
            'village_id' => $request->village_id,
        ];
        return $data;
    }
    ///Adminbranch
     public function adminbrach(Request $request)
    {
        // dd($request->all());
        $branch = Branch::orderBy('id', 'DESC')->get();
        return view('admin-system.branch.branch', compact('branch'));
    }
    public function admincreate()
    {
        return view('admin-system.branch.create');
    }
    public function adminedit($id)
    {
        $branch = Branch::findOrFail($id);
        return view('admin-system.branch.edit', compact('branch'));
    }
    public function adminstore(Request $request)
    {
        $request->validate([
            'name_en'        => 'required|unique:branches,name_en',
            'name_km'        => 'required|unique:branches,name_km',
            'branch_prefix'  => 'required|string|max:4|unique:branches,branch_prefix',
            'client_prefix'  => 'required|string|max:4|unique:branches,client_prefix',
            'co_prefix'      => 'required|string|max:4|unique:branches,co_prefix',
            'user_prefix'    => 'required|string|max:4|unique:branches,user_prefix',
            'loan_prefix'    => 'required|string|max:7|unique:branches,loan_prefix',
            'invoice_prefix' => 'required|string|max:4|unique:branches,invoice_prefix',
        ],
        [
            'name_en.required' => 'English name is required.',
            'name_en.unique'   => 'This English name already exists.',
            'name_km.required' => 'Khmer name is required.',
            'name_km.unique'   => 'This Khmer name already exists.',
            'branch_prefix.required' => 'Branch prefix is required.',
            'branch_prefix.max'      => 'Branch prefix must not be more than 4 characters.',
            'branch_prefix.unique'   => 'Branch prefix already exists.',
            'client_prefix.required' => 'Client prefix is required.',
            'client_prefix.max'      => 'Client prefix must not be more than 4 characters.',
            'client_prefix.unique'   => 'Client prefix already exists.',
            'co_prefix.required' => 'CO prefix is required.',
            'co_prefix.max'      => 'CO prefix must not be more than 4 characters.',
            'co_prefix.unique'   => 'CO prefix already exists.',
            'user_prefix.required' => 'User prefix is required.',
            'user_prefix.max'      => 'User prefix must not be more than 4 characters.',
            'user_prefix.unique'   => 'User prefix already exists.',
            'loan_prefix.required' => 'Loan prefix is required.',
            'loan_prefix.max'      => 'Loan prefix must not be more than 7 characters.',
            'loan_prefix.unique'   => 'Loan prefix already exists.',
            'invoice_prefix.required' => 'Invoice prefix is required.',
            'invoice_prefix.max'      => 'Invoice prefix must not be more than 4 characters.',
            'invoice_prefix.unique'   => 'Invoice prefix already exists.',
        ]);

        Branch::create($request->only(
            'name_en',
            'name_km',
            'phone',
            'address',
            'branch_prefix',
            'client_prefix',
            'co_prefix',
            'user_prefix',
            'loan_prefix',
            'invoice_prefix'
        ));

        return redirect('adminbranch')->with('success', 'Branch created successfully.');
    }


    public function branchupdate(Request $request, $id)
    {
        $branch = Branch::findOrFail($id);

        $request->validate([
            'name_en'        => 'required',
            'name_km'        => 'required',
            'branch_prefix'  => 'required|string|max:4|unique:branches,branch_prefix,' . $id,
            'client_prefix'  => 'required|string|max:4|unique:branches,client_prefix,' . $id,
            'co_prefix'      => 'required|string|max:4|unique:branches,co_prefix,' . $id,
            'user_prefix'    => 'required|string|max:4|unique:branches,user_prefix,' . $id,
            'loan_prefix'    => 'required|string|max:7|unique:branches,loan_prefix,' . $id,
            'invoice_prefix' => 'required|string|max:4|unique:branches,invoice_prefix,' . $id,
        ],
        [
            'name_en.required' => 'English name is required.',
            'name_km.required' => 'Khmer name is required.',
            'branch_prefix.required' => 'Branch prefix is required.',
            'branch_prefix.max'      => 'Branch prefix must not exceed 4 characters.',
            'branch_prefix.unique'   => 'Branch prefix already exists.',
            'client_prefix.required' => 'Client prefix is required.',
            'client_prefix.max'      => 'Client prefix must not exceed 4 characters.',
            'client_prefix.unique'   => 'Client prefix already exists.',
            'co_prefix.required' => 'CO prefix is required.',
            'co_prefix.max'      => 'CO prefix must not exceed 4 characters.',
            'co_prefix.unique'   => 'CO prefix already exists.',
            'user_prefix.required' => 'User prefix is required.',
            'user_prefix.max'      => 'User prefix must not exceed 4 characters.',
            'user_prefix.unique'   => 'User prefix already exists.',
            'loan_prefix.required' => 'Loan prefix is required.',
            'loan_prefix.max'      => 'Loan prefix must not exceed 7 characters.',
            'loan_prefix.unique'   => 'Loan prefix already exists.',
            'invoice_prefix.required' => 'Invoice prefix is required.',
            'invoice_prefix.max'      => 'Invoice prefix must not exceed 4 characters.',
            'invoice_prefix.unique'   => 'Invoice prefix already exists.',
        ]);

        $branch->update($request->only(
            'name_en',
            'name_km',
            'phone',
            'address',
            'branch_prefix',
            'client_prefix',
            'co_prefix',
            'user_prefix',
            'loan_prefix',
            'invoice_prefix'
        ));

        return redirect('adminbranch')->with('success', 'Branch updated successfully.');
    }

    public function admindestroy($id)
    {
        Branch::findOrFail($id)->delete();

        return redirect('adminbranch')->with('success', 'Branch deleted successfully.');
    }
   public function activeAction($id)
    {
        DB::beginTransaction();
        try {
            $branch = Branch::find($id);

            if (!$branch) {
                return response()->json([
                    'status_id' => 0,
                    'message'   => 'Branch not found',
                ], 404);
            }
            $newStatus = $branch->status_id == 1 ? 2 : 1;
            $branch->update(['status_id' => $newStatus]);
            $branch->refresh();
            DB::commit();
            return redirect('adminbranch')->with('success', 'Branch activeaction successfully.');
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json([
                'status_id' => 0,
                'message' => 'Error: '.$e->getMessage()
            ], 500);
        }
    }

}
