<?php

namespace App\Http\Controllers\Admin;

use App\Exports\ExportCollateral;
use App\Helpers\Helper;
use App\Models\Collateral;
use App\Http\Controllers\Controller;
use App\Http\Resources\CollateralDetailResource;
use App\Http\Resources\CollateralResource;
use App\Models\CollateralDetail;
use App\Models\Loan;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class CollateralController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:Collateral List', ['only' => ['index']]);
        $this->middleware('permission:Collateral Create', ['only' => ['store']]);
        $this->middleware('permission:Collateral Edit', ['only' => ['store']]);
        $this->middleware('permission:Collateral Delete', ['only' => ['destroy']]);
    }
    public function index(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = Collateral::search($request->search_text)
        ->orderBy('id','DESC')
        ->paginate($per_page);
        return CollateralResource::collection($data);
    }

    public function create(Request $request)
    {
        $collateral = Collateral::find($request->id);

        if($collateral){
            $res = [
                'status' => 1,
                'message'=> 'Create collateral success',
                'data'   => new CollateralResource($collateral),
            ];
        }else{
            $res = [
                'status'  => 0,
                'message' => 'Create collateral not found',
                'data'    => [],
            ];
        }
        return response()->json($res,200);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'cat_id' => 'nullable|required',
            'title' => 'nullable|required',
        ]);
        try{
            DB::beginTransaction();
            $collateral = Collateral::updateOrCreate(['id' => $this->getCollecteralRequest($request)['id']],$this->getCollecteralRequest($request));

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

    public function getCollecteralRequest($request)
    {
        $data = [
            'id'      => $request->id,
            'cat_id'  =>  $request->cat_id,
            'title'   => $request->title,
            'purpose' => $request->purpose,
        ];
        return $data;
    }

    public function update(Request $request,$id)
    {
        DB::beginTransaction();
        try {
            $cat = CollateralDetail::find($id);
            $cat->status = $request->check;
            $cat->update();
            $res = [
                'status' => 1,
                'message'=> $request->check==1?'បានដកដោយជោគជ័យ':'បានដាក់ដោយជោគជ័យ',
                'data'   => $cat,
            ];
            DB::commit();
        }catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Deleted not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }

    public function destroy($id)
    {
        DB::beginTransaction();
        try {
            $cat = Collateral::find($id);
            if($cat->collateralDetails->count()>0){
                $res = [
                    'status'  => 0,
                    'message' => 'មិនអាចលុបបានទេ ពីព្រោះលោកអ្នកបានធ្វើប្រត្តិបត្តិការរួចហើយ',
                    'data'    => '',
                ];
            } else{
                $cat->delete();
                $res = [
                    'status' => 1,
                    'message'=> 'Deleted success',
                    'data'   => $cat,
                ];
            }
            DB::commit();
        }catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Deleted not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }

    // Collateral List
    public function getCollateralDetail(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = CollateralDetail::whereHas('loan', function ($query) use ($request) {
            if(!$request->search_text ==''){
                $query->where('loan_code', 'LIKE', '%'.$request->search_text.'%');
            }
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[]){
                $query->whereIn('co_id',$request->co_id);
            }
            if(!$request->collateral_id ==''){
                $query->where('collateral_id',$request->collateral_id);
            }
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
        })
        ->orderBy('id','DESC')
        ->paginate($per_page);
        return CollateralDetailResource::collection($data);
    }

    public function getCollateralDetailCreate(Request $request)
    {
        $collateral = CollateralDetail::where('loan_id',$request->id)->first();

        if($collateral){
            $res = [
                'status' => 1,
                'message'=> 'Create collateral success',
                'data'   => new CollateralDetailResource($collateral),
            ];
        }else{
            $res = [
                'status'  => 0,
                'message' => 'Create collateral not found',
                'data'    => [],
            ];
        }
        return response()->json($res,200);
    }

    public function storeCollateralDetailCreate(Request $request)
    {
        // $this->validate($request, [
        //     'collateral_id' => 'required',
        // ]);
        try{
            DB::beginTransaction();
            $collateral = CollateralDetail::updateOrCreate(
                [
                    'id' => $this->getCollecteralDetailRequest($request)['id']
                ],
                $this->getCollecteralDetailRequest($request)
            );

            DB::commit();
            $res = [
                'status' => 1,
                'message'=> $collateral->wasRecentlyCreated?'Create Collecteral success':'Update Collecteral success',
                'data'   => new CollateralDetailResource($collateral),
            ];
        }catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Create Collecteral not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }
    public function getCollecteralDetailRequest($request)
    {
        $loan = Loan::find($request->loan_id);
        $data = [
            'id'           => $request->id,
            'collateral_id'=> $request->collateral_id,
            'loan_id'      => $request->loan_id,
            'client_id'    => $loan->client_id,
            'model_type'   => $request->model_type,
            'color'        => $request->color,
            'number_plate' => $request->number_plate,
            'body_number'  => $request->body_number,
            'engine_number'=> $request->engine_number,
            'cylinder_size'=> $request->cylinder_size,
            'date_made'    => $request->date_made,
            'year'         => $request->year,
            'price_market' => $request->price_market,
            'price_urgent' => $request->price_urgent,
            'degree'       => $request->degree,
            'number'       => $request->number,
            'head_land'    => $request->head_land,
            'size'         => $request->size,
            'issued_by'    => $request->issued_by,
            'location'     => $request->location,
            'status_type'  => $request->status_type,
            'north'        => $request->north,
            'south'        => $request->south,
            'east'         => $request->east,
            'west'         => $request->west,
        ];
        return $data;
    }

    public function getCollateralReport(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = CollateralDetail::whereHas('loan', function ($query) use ($request) {
            // $query->whereIn('co_id',Helper::group());
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[]){
                $query->whereIn('co_id',$request->co_id);
            }
            if(!$request->collateral_id ==[]){
                $query->whereIn('collateral_id',$request->collateral_id);
            }
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
        })
        ->orderBy('collateral_id','DESC');
        if($request->per_page=="ALL" || $request->pagin == 'true') {
            return CollateralDetailResource::collection($data->get());
        } else {
            return CollateralDetailResource::collection($data->paginate($per_page));
        }
    }

}
