<?php

namespace App\Http\Controllers\Admin;

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\Http\Resources\LoanCollateralResource;
use App\Models\CollateralDetail;
use App\Models\Loan;
use App\Models\LoanCollateral;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

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)
    {
        $collateralID = decrypt_id($request->id);
        $collateral = Collateral::find($collateralID);
        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 {
            $collateralID = decrypt_id($id);
            $coll = Collateral::find($collateralID);

            if ($coll->collateralDetails->count() > 0) {
                foreach ($coll->collateralDetails as $detail) {
                    $loanCollateral = LoanCollateral::where('collateral_detail_id', $detail->id)->first();
                    if ($loanCollateral) {
                        $loan_id = Loan::where('id', $loanCollateral->loan_id)->pluck('id')->first();
                        if ($loan_id !== null) {
                            $res = [
                                'status'  => 0,
                                'message' => 'មិនអាចលុបបានទេ ពីព្រោះធានានេះត្រូវបានភ្ជាប់ជាមួយនឹងកម្ចី។',
                                'data'    => '',
                            ];
                            DB::rollBack();
                            return response()->json($res, 200);
                        }
                    }
                }
            }

            CollateralDetail::where('collateral_id', $coll->id)->delete();
            $coll->delete();
            DB::commit();
            $res = [
                'status'  => 1,
                'message' => 'Deleted success',
                'data'    => $coll,
            ];
        } 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 = Collateral::where(function($query) use ($request)
        {
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
        })
        ->whereHas('client',function($query){
            $query->where('branch_id',Helper::byBranch());
        })
        ->orderBy('id','desc'); 
        if($request->per_page=="ALL" || $request->pagin == 'true'){
            return CollateralResource::collection($data->get());
        } else {
            return CollateralResource::collection($data->paginate($per_page));
        }
    }

    public function getCollateralDetailCreate(Request $request)
    {

        $collateralID = decrypt_id($request->id);
        $collateral = Collateral::find($collateralID);
        $one = CollateralDetail::where('collateral_id',$collateralID)->where('status_type',1)->first();
        $two = CollateralDetail::where('collateral_id',$collateralID)->where('status_type',2)->first();
        $three = CollateralDetail::where('collateral_id',$collateralID)->where('status_type',3)->first();
        $four = CollateralDetail::where('collateral_id',$collateralID)->where('status_type',4)->first();
        $five = CollateralDetail::where('collateral_id',$collateralID)->where('status_type',5)->first();
        $six = CollateralDetail::where('collateral_id',$collateralID)->where('status_type',6)->first();
        $data_one = $one?new CollateralDetailResource($one):null;
        $data_two = $two?new CollateralDetailResource($two):null;
        $data_three = $three?new CollateralDetailResource($three):null;
        $data_four = $four?new CollateralDetailResource($four):null;
        $data_five = $five?new CollateralDetailResource($five):null;
        $data_six = $six?new CollateralDetailResource($six):null;

        if($one||$two||$three||$four||$five||$six){
            $res = [
                'status' => 1,
                'message'=> 'Create collateral success',
                'home'          => $data_one,
                'home1'         => $data_two,
                'vehicle'       => $data_three,
                'vehicleTwo'    => $data_four,
                'jewelrys'      => $data_five,
                'collateral'    => $collateral,
                'jewelryTwo'    => $data_six,
            ];
        }
        else{
            $res = [
                'status'  => 0,
                'message' => 'Create collateral not found',
                'home'          => [],
                'home1'         => [],
                'vehicle'       => [],
                'vehicleTwo'    => [],
                'jewelrys'      => [],
                'collateral'    => [],
                'jewelryTwo'    => [],
            ];
        }
        return response()->json($res,200);
    }

    public function storeCollateralDetailCreate(Request $request)
    {
        $this->validate($request, [
            'client_id' => 'required',
            'title' => 'required',
        ]);
        try{
            DB::beginTransaction();
            $data = [
                'client_id' => $request->client_id, 
                'title'     => $request->title,
            ];
            $collateral = Collateral::updateOrCreate(['id' => $request->id], $data);

            $one  = $request->home;
            $two  = $request->home1;
            $three= $request->vehicle;
            $four = $request->vehicleTwo;
            $five = $request->jewelrys;
            $six  = $request->jewelryTwo;

            $oneID   = $one['id'] ? decrypt_id($one['id']) : null;
            $twoID   = $two['id'] ? decrypt_id($two['id']) : null;
            $threeID = $three['id'] ? decrypt_id($three['id']) : null;
            $fourID  = $four['id'] ? decrypt_id($four['id']) : null;
            $fiveID  = $five['id'] ? decrypt_id($five['id']) : null;
            $sixID   = $six['id'] ? decrypt_id($six['id']) : null;

            if(!empty($one['model_type']))
            {
                $image = Helper::Base64Upload($one['image'], 'uploads/mortgages/',  $one['image']->image??'');
                $photo = Helper::Base64Upload($one['photo'], 'uploads/mortgages/',  $one['photo']->photo??'');

                CollateralDetail::updateOrCreate(
                    [
                        'id' => $oneID,
                        'status_type'      => 1,
                    ],[

                        'model_type' => $one['model_type'],
                        'collateral_id' => $collateral->id,
                        'client_id' => $collateral->client_id,
                        'pawn_type' => $one['pawn_type'],
                        'color' => $one['color'],
                        'number' => $one['number'],
                        'number_plate' => $one['number_plate'],
                        'body_number' => $one['body_number'],
                        'engine_number' => $one['engine_number'],
                        'cylinder_size' => $one['cylinder_size'],
                        'date_made' => $one['date_made'],
                        'year' => $one['year'],
                        'price_market' => $one['price_market'],
                        'price_urgent' => $one['price_urgent'],
                        'other_price' => $one['other_price'],
                        'authority_price' => $one['authority_price'],
                        'degree' => $one['degree'],
                        'head_land' => $one['head_land'],
                        'size' => $one['size'],
                        'issued_by' => $one['issued_by'],
                        'collateral_owner' => $one['collateral_owner'],
                        'location' => $one['location'], 
                        'status_type' => $one['status_type'],
                        'north' => $one['north'],
                        'south' => $one['south'],
                        'east' => $one['east'],
                        'west' => $one['west'],
                        'link_map' => $one['link_map'],
                        'photo' => $photo??'',
                        'image' => $image??'',
                    ]);
            }
            if(!empty($two['model_type']))
            {
                $image = Helper::Base64Upload($two['image'], 'uploads/mortgages/',  $two['image']->image??'');
                $photo = Helper::Base64Upload($two['photo'], 'uploads/mortgages/',  $two['photo']->photo??'');
                CollateralDetail::updateOrCreate(
                    [
                        'id'        =>$twoID,
                        'status_type'      => 2,
                    ],[
                        'model_type' => $two['model_type'],
                        'collateral_id' => $collateral->id,
                        'client_id' => $collateral->client_id,
                        'pawn_type' => $two['pawn_type'],
                        'color' => $two['color'],
                        'number' => $two['number'],
                        'number_plate' => $two['number_plate'],
                        'body_number' => $two['body_number'],
                        'engine_number' => $two['engine_number'],
                        'cylinder_size' => $two['cylinder_size'],
                        'date_made' => $two['date_made'],
                        'year' => $two['year'],
                        'price_market' => $two['price_market'],
                        'price_urgent' => $two['price_urgent'],
                        'other_price' => $two['other_price'],
                        'authority_price' => $two['authority_price'],
                        'latabat' => $two['latabat'],
                        'degree' => $two['degree'],
                        'head_land' => $two['head_land'],
                        'size' => $two['size'],
                        'issued_by' => $two['issued_by'],
                        'collateral_owner' => $two['collateral_owner'],
                        'location' => $two['location'],
                        'status_type' => $two['status_type'],
                        'north' => $two['north'],
                        'south' => $two['south'],
                        'east' => $two['east'],
                        'west' => $two['west'],
                        'link_map' => $two['link_map'],
                        'photo' => $photo??'',
                        'image' => $image??'',
                    ]);
            }
            if(!empty($three['model_type']))
            {
                $image='';
                if($three['image']){
                    $image = Helper::Base64Upload($three['image'], 'uploads/mortgages/',  $three['image']->image??'');
                    // $photo = Helper::Base64Upload($three['photo'], 'uploads/mortgages/',  $three['photo']->photo??'');
                }

                CollateralDetail::updateOrCreate(
                    [
                        'id'        =>$threeID,
                        'status_type'      => 3,
                    ],[
                        'model_type' => $three['model_type'],
                        'collateral_id' => $collateral->id,
                        'client_id' => $collateral->client_id,
                        'pawn_type' => $three['pawn_type'],
                        'color' => $three['color'],
                        'number' => $three['number'],
                        'number_plate' => $three['number_plate'],
                        'body_number' => $three['body_number'],
                        'engine_number' => $three['engine_number'],
                        'cylinder_size' => $three['cylinder_size'],
                        'date_made' => $three['date_made'],
                        'year' => $three['year'],
                        'price_market' => $three['price_market'],
                        'price_urgent' => $three['price_urgent'],
                        'other_price' => $three['other_price'],
                        'authority_price' => $three['authority_price'],
                        'latabat' => $three['latabat'],
                        'degree' => $three['degree'],
                        'head_land' => $three['head_land'],
                        'size' => $three['size'],
                        'issued_by' => $three['issued_by'],
                        'collateral_owner' => $three['collateral_owner'],
                        'location' => $three['location'],
                        'status_type' => $three['status_type'],
                        'north' => $three['north'],
                        'south' => $three['south'],
                        'east' => $three['east'],
                        'west' => $three['west'],
                        'strength' => $three['strength'],
                        'photo' => '',
                        'image' => $image??'',
                    ]);
            }
            if(!empty($four['model_type']))
            {
                $image='';
                if($three['image']){
                    $image = Helper::Base64Upload($four['image'], 'uploads/mortgages/',  $four['image']->image??'');
                    // $photo = Helper::Base64Upload($four['photo'], 'uploads/mortgages/',  $four['photo']->photo??'');
                }

                CollateralDetail::updateOrCreate(
                    [
                        'id'        =>$fourID,
                        'status_type'      => 4,
                    ],[
                        'model_type' => $four['model_type'],
                        'collateral_id' => $collateral->id,
                        'client_id' => $collateral->client_id,
                        'pawn_type' => $four['pawn_type'],
                        'color' => $four['color'],
                        'number' => $four['number'],
                        'number_plate' => $four['number_plate'],
                        'body_number' => $four['body_number'],
                        'engine_number' => $four['engine_number'],
                        'cylinder_size' => $four['cylinder_size'],
                        'date_made' => $four['date_made'],
                        'year' => $four['year'],
                        'price_market' => $four['price_market'],
                        'price_urgent' => $four['price_urgent'],
                        'other_price' => $four['other_price'],
                        'authority_price' => $four['authority_price'],
                        'latabat' => $four['latabat'],
                        'degree' => $four['degree'],
                        'head_land' => $four['head_land'],
                        'size' => $four['size'],
                        'issued_by' => $four['issued_by'],
                        'collateral_owner' => $four['collateral_owner'],
                        'location' => $four['location'],
                        'status_type' => $four['status_type'],
                        'north' => $four['north'],
                        'south' => $four['south'],
                        'east' => $four['east'],
                        'west' => $four['west'],
                        'strength' => $four['strength'],
                        'photo' => '',
                        'image' => $image??'',
                    ]);
            }
            if(!empty($five['model_type']))
            {
                $image='';
                if($five['image']){
                    $image = Helper::Base64Upload($five['image'], 'uploads/mortgages/',  $five['image']->image??'');
                    // $photo = Helper::Base64Upload($five['photo'], 'uploads/mortgages/',  $five['photo']->photo??'');
                }

                CollateralDetail::updateOrCreate(
                    [
                        'id'        => $fiveID,
                        'status_type'      => 5,
                    ],[
                        'model_type' => $five['model_type'],
                        'collateral_id' => $collateral->id,
                        'client_id' => $collateral->client_id,
                        'pawn_type' => $five['pawn_type'],
                        'color' => $five['color'],
                        'number' => $five['number'],
                        'number_plate' => $five['number_plate'],
                        'body_number' => $five['body_number'],
                        'engine_number' => $five['engine_number'],
                        'cylinder_size' => $five['cylinder_size'],
                        'date_made' => $five['date_made'],
                        'year' => $five['year'],
                        'price_market' => $five['price_market'],
                        'price_urgent' => $five['price_urgent'],
                        'other_price' => $five['other_price'],
                        'authority_price' => $five['authority_price'],
                        'latabat' => $five['latabat'],
                        'degree' => $five['degree'],
                        'head_land' => $five['head_land'],
                        'size' => $five['size'],
                        'issued_by' => $five['issued_by'],
                        // 'collateral_owner' => $five['collateral_owner'],
                        'location' => $five['location'],
                        'status_type' => $five['status_type'],
                        'north' => $five['north'],
                        'south' => $five['south'],
                        'east' => $five['east'],
                        'west' => $five['west'],
                        'weight' => $five['weight'],
                        'photo' => '',
                        'image' => $image??'',
                    ]);
            }
            if(!empty($six['model_type']))
            {
                // $image='';
                // if($six['image']){
                //     $image = Helper::Base64Upload($six['image'], 'uploads/mortgages/',  $six['image']->image??'');
                //     $photo = Helper::Base64Upload($six['photo'], 'uploads/mortgages/',  $six['photo']->photo??'');
                // }

                CollateralDetail::updateOrCreate(
                    [
                        'id'        => $sixID,
                        'status_type'      => 6,
                    ],[
                        'model_type' => $six['model_type'],
                        'collateral_id' => $collateral->id,
                        'client_id' => $collateral->client_id,
                        'pawn_type' => $six['pawn_type'],
                        'color' => $six['color'],
                        'number' => $six['number'],
                        'number_plate' => $six['number_plate'],
                        'body_number' => $six['body_number'],
                        'engine_number' => $six['engine_number'],
                        'cylinder_size' => $six['cylinder_size'],
                        'date_made' => $six['date_made'],
                        'year' => $six['year'],
                        'price_market' => $six['price_market'],
                        'price_urgent' => $six['price_urgent'],
                        'other_price' => $six['other_price'],
                        'authority_price' => $six['authority_price'],
                        'latabat' => $six['latabat'],
                        'degree' => $six['degree'],
                        'head_land' => $six['head_land'],
                        'size' => $six['size'],
                        'issued_by' => $six['issued_by'],
                        'location' => $six['location'],
                        'status_type' => $six['status_type'],
                        'north' => $six['north'],
                        'south' => $six['south'],
                        'east' => $six['east'],
                        'west' => $six['west'],
                        'weight' => $six['weight'],
                        'photo' => '',
                        // 'image' => $image??'',
                    ]);
            }
            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 getCollateralReport(Request $request)
    {

        $per_page = $request->per_page == null?25: $request->per_page;
        $data = LoanCollateral::where(function($query) use($request){
            if(!$request->client_id ==[]) {
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->collateral_detail_id ==[]) {
                $query->whereIn('collateral_detail_id',$request->collateral_detail_id);
            }
        })
        ->whereHas('loan', function ($query) use($request) {
            if(!$request->co_id ==[]){
                $query->whereIn('co_id',$request->co_id);
            }
            $query->where('loan_code', 'LIKE', '%'.$request->search_text.'%');
        })
        ->orderBy('id','desc');
        if($request->per_page=="ALL" || $request->pagin == 'true'){
            return LoanCollateralResource::collection($data->get());
        } else {
            return LoanCollateralResource::collection($data->paginate($per_page));
        }
    }
    public function funSubLoanCollateral($collateral_detail_id)
    {
        DB::beginTransaction();
        try {
            $collateralDe = CollateralDetail::where('id',$collateral_detail_id)->first();
            $loanCollateral = LoanCollateral::where('collateral_detail_id',$collateral_detail_id)->first();
            $loan_status_id = Loan::where('id',$loanCollateral->loan_id)->pluck('loan_status_id')->first();
            if($collateralDe){
                 if($loan_status_id !=3){
                    return response()->json([
                        'status'  => 0,
                        'message' => 'មិនអាចលុបបានទេ!',
                        'data'    => '',
                    ], 404);
                }else{
                    $collateralDe->update(['status' => 2]);
                    DB::commit();
                    return response()->json([
                        'status'  => 1,
                        'message' => 'បានដកដោយជោគជ័យ',
                        'data'    => $collateralDe,
                    ], 200);

                }
            }
           
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status'  => 0,
                'message' => 'មិនជោគជ័យទេ!',
                'data'    => $e->getMessage(),
            ], 500);
        }
    }
}
