<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Loan;
use App\Models\User;
use App\Models\Client;
use App\Helpers\Helper;
use App\Models\Currency;
use App\Helpers\LogActivity;
use Illuminate\Http\Request;
use App\Models\AccReceivables;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Resources\LoanResource;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\ClientResource;
use App\Http\Resources\CollateralDetailResource;
use App\Http\Resources\GuarantorResource;
use App\Http\Resources\ShowPaymentResource;
use App\Http\Resources\UserResource;
use App\Models\AccReceivableDetails;
use App\Models\BackPayment;
use App\Models\CollateralDetail;
use App\Models\Guarantor;
use App\Models\LoanCollateral;
use App\Models\Reschedule;
use Carbon\Carbon;

class LoanController extends Controller
{

    function __construct()
    {
        $this->middleware('permission:Loan List|List Approve',   ['only' => ['index']]);
        $this->middleware('permission:Loan Approve',['only' => ['update']]);
        $this->middleware('permission:Loan Delete', ['only' => ['destroy']]);
        $this->middleware('permission:Loan Create', ['only' => ['store','create','storeReschedule']]);
        $this->middleware('permission:Loan Edit',   ['only' => ['edit','create','storeReschedule']]);
    }

    public function index(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = Loan::where(function($query) use ($request){
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
            // $query->whereIn('co_id',Helper::group());
            if(!$request->date==[]){
                $query->whereBetween(DB::raw("DATE_FORMAT(installment_date, '%Y-%m-%d')"), $request->date);
            }
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[]){
                $query->whereIn('co_id',$request->co_id);
            }
            if($request->check_list_loan==1){
                $query->where('loan_status_id',1);
            } else{
                $query->where('client_type',$request->client_type);
                $query->whereNotIn('loan_status_id',[1,4]);
                if(!$request->loan_status_id ==[]){
                    $query->whereIn('loan_status_id',$request->loan_status_id);
                }
                if(!$request->loan_code ==''){
                    $query->where('loan_code', 'LIKE', '%'.$request->loan_code.'%');
                }
            }
        })
        ->orderBy('id','desc');

        if($request->per_page=="ALL" || $request->pagin == 'true'){
            return LoanResource::collection($data->get());
        } else {
            return LoanResource::collection($data->paginate($per_page));
        }
    }

    public function create(Request $request)
    {
        $currency_id = Auth::user()->currency_id;
        $loan = Loan::find($request->id);

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

    public function store(Request $request)
    {
        $this->validate($request, [
            'client_id'       => 'required',
            'co_id'           => 'required',
            'installment_date'=> 'required',
            'start_date'      => 'required',
            'chart_of_acc_id' => 'required',
            'condition_pay'   => 'required',
            'term_type'       => 'required',
            'period'          => 'required',
            'term_condi'      => 'required',
            'loan_out'        => 'required|numeric|gte:'.'1',
        ]);

        try{
            DB::beginTransaction();
            $loan = Loan::updateOrCreate(['id' => $this->getLoan($request)['id']],$this->getLoan($request));

            $user = User::find(Auth::user()->id);
            $client = Client::find($loan->client_id);
            $subject_type = get_class($loan);
            $subject_id   = $loan->id;
            $causer_type  = get_class($user);
            $causer_id    = Auth::user()->id;
            $branch       = Auth::user()->branch_id;
            $log_name     = 'Loan Model';

            if($request->id!='')
            {
                AccReceivables::where('loan_id',$request->id)->delete();
                $subject = "កែប្រែកម្ចីអតិថិជន $client->name ទំហំទឹកប្រាក់ $request->loan_out ដោយ $user->name.";
            } else {
                $subject = "បង្កើតកម្ចីថ្មីអតិថិជន $client->name ទំហំទឹកប្រាក់ $request->loan_out ដោយ $user->name.";
            }
            LogActivity::addToLog($subject,$subject_type,$subject_id,$causer_type,$causer_id,$branch,$log_name);

            foreach($request->rows as $key => $value){
                if($key==0){
                    $type_open_close = 2;
                } else{
                    $type_open_close = 1;
                }
                $arr = array(
                    'loan_id'              => $loan->id,
                    'client_id'            => $request->client_id,
                    'co_id'                => $request->co_id,
                    'branch_id'            => Auth::user()->branch_id,
                    'currency_id'          => Helper::byCurrency(),
                    'num'                  => $key + 1,
                    'payment_date'         => date('Y-m-d', strtotime($value['payment_date'])),
                    'received_date'        => null,
                    'interest_per_month'   => $value['interestPerMonth'],
                    'risk_per_month'       => $value['riskPerMonth'],
                    'maintenance_per_month'=> $value['maintenancePerMonth'] ?? 0,
                    'principal'            => $value['principal'],
                    'loan_balance'         => $value['loan_balance'],
                    'payment_per_month'    => $value['payment_per_month'],
                    'unreceived'           => $value['payment_per_month'],
                    'created_at'           => new \DateTime(),
                    'payment_status_id'    => $loan->loan_status_id==1?4:3, // Pending
                    'open_close'           => $type_open_close,
                );
                AccReceivables::insert($arr);
            }

            // insert collateral to *LoanCollateral*
            $detailID = [];
            foreach($request->AddRemoveRows as $key => $ColDetail) {
                if (!isset($ColDetail['collateral_id']) || $ColDetail['collateral_id'] == null) {
                    continue;
                }
                $detail_collate = [];
                $detail_collate[] = $ColDetail['collateral_id'];

                if($detail_collate[0]!=null) {
                    $collateralDetail = LoanCollateral::updateOrCreate(
                        ['id' => $ColDetail['id']],
                        [
                            'loan_id'      => $loan->id,
                            'currency_id'  => Auth::user()->currency_id,
                            'branch_id'    => Auth::user()->branch_id,
                            'client_id'    => $loan->client_id,
                            'collateral_id'=> $ColDetail['collateral_id'],
                            'date_made'    => $ColDetail['date_made'],
                            'status'=> $ColDetail['status'],
                        ]
                    );
                    $detailID[] = $collateralDetail->id;
                }
                // //update status collateral detial
                // CollateralDetail::where('id',$ColDetail['collateral_id'])->update([
                //     'status' => 2
                // ]);
            }
            // if remove collateral in loan
            LoanCollateral::whereNotIn('id',$detailID)->where('loan_id',$loan->id)->update([
                'deleted_at' => Carbon::now()
            ]);

            DB::commit();
            $res = [
                'status' => 1,
                'message'=> $loan->wasRecentlyCreated?"បង្កើតកម្ចីថ្មីអតិថិជនឈ្មោះ $client->name ដោយជោគជ័យ":"កែប្រែកម្ចីនៃអតិថិជនឈ្មោះ $client->name ដោយជោគជ័យ",
                'data'   => new LoanResource($loan),
            ];
        }catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Loan create not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }

    public function getLoan($request)
    {
        if($request->id) {
            $level_loan = $request->level_loan;
        }
        else {
            $count = Loan::where('client_id',$request->client_id)->max('level_loan');
            if($count) {
                $level_loan = $count+1;
            } else {
                $level_loan = 1;
            }
        }
        $total_interest    = 0;
        $total_risk        = 0;
        $total_maintenance = 0;
        foreach($request->rows as $value) {
            $total_interest    += ($value['interestPerMonth']);
            $total_risk        += ($value['riskPerMonth']);
            $total_maintenance += ($value['maintenancePerMonth']);
        }
        $row_period   = $request->rows;
        $last_row     = end($row_period);
        $new_object   = json_decode(json_encode($last_row));
        $expired_date = date('Y-m-d',strtotime($new_object->payment_date));
        // Value total
        $total_service    = $request->service>0&&$request->total_service==0?($request->loan_out*$request->service)/100:$request->total_service;
        $total_insurance  = $request->insurance>0&&$request->total_insurance==0?($request->loan_out*$request->insurance)/100:$request->total_insurance;
        $total_collection = $request->service_collection>0&&$request->total_collection==0?($request->loan_out*$request->service_collection)/100:$request->total_collection;

        $data = [
            'id'                   => $request->id,
            'client_id'            => $request->client_id,
            'loan_code'            => $request->loan_code??Helper::codeLoanAuto(Loan::class, Helper::prefix(),5, 'loan_code'),
            'co_id'                => $request->co_id,
            'chart_of_acc_id'      => $request->chart_of_acc_id,
            'branch_id'            => Auth::user()->branch_id,
            'currency_id'          => Helper::byCurrency(),
            'installment_date'     => date('Y-m-d', strtotime($request->installment_date)),
            'start_date'           => date('Y-m-d', strtotime($request->start_date)),
            'expired_date'         => $expired_date,
            'loan_out'             => $request->loan_out,
            'risk'                 => $request->risk!=null?$request->risk:0,
            'total_risk'           => $total_risk??0,
            'interest'             => $request->interest!=null?$request->interest:0,
            'total_interest'       => $total_interest??0,
            'maintenance'          => $request->maintenance!=null?$request->maintenance:0,
            'total_maintenance'    => $total_maintenance??0,
            // 'reschedule_amount'    => $request->principal_down??0,
            'service'              => $request->service??0,
            // 'total_service'        => $total_service??0,
            'total_service'        => $request->total_service??0,
            'service_collection'   => $request->service_collection??0,
            'total_collection'     => $total_collection??0,
            'insurance'            => $request->insurance??0,
            'total_insurance'      => $total_insurance??0,

            'saving'               => $request->saving??0,
            'total_saving'         => $request->total_saving??0,
            'period'               => $request->period,
            'level_loan'           => $level_loan,
            'condition_pay'        => $request->condition_pay,
            'loan_receive'         => $request->balance_principal + $total_interest + $total_risk + $total_maintenance,
            'loan_balance'         => $request->balance_principal + $total_interest + $total_risk + $total_maintenance,
            'amount_client_receive'=> $request->total_to_client>0?$request->total_to_client:$request->loan_out-$total_service-$total_collection-$total_insurance??0,
            // 'balance_principal'    => $request->loan_out,
            'balance_principal'    => $request->balance_principal??0,
            'balance_interest'     => $total_interest,
            'balance_risk'         => $total_risk,
            'balance_maintenance'  => $total_maintenance,
            'term_type'            => $request->term_type,
            'term_condi'           => $request->term_condi,
            'desc'                 => $request->desc,
            'type_loan'            => $request->type_loan,
            'loan_status_id'       => $request->id?$request->loan_status_id:1,
            'client_type'          => 1,
            'created_by'           => Auth::user()->id,
        ];
        return $data;
    }

    public function storeReschedule(Request $request)
    {
        // dd($request->all());
        if($request->principal_down>0 || $request->principal_add>0) {
            $this->validate($request, [
                'payment_method' => 'required',
            ]);
        }
        try{
            DB::beginTransaction();

            $arr_acc_details = AccReceivableDetails::where('loan_id',$request->id)->whereNull('closing_date')->get();
            if($arr_acc_details->count()>0) {
                $res = [
                    'status' => 0,
                    'message'=>'លោកអ្នកមិនអាចរៀបចំតារាងឡើងវិញបានទេ ព្រោះការទូទាត់ប្រាក់មិនទាន់បានបិទបញ្ជី!',
                ];
            }
            else {

                $id = $request['id'];
                $not_complete = AccReceivables::where('loan_id',$request->id)->where('payment_status_id',2)->first();
                if($not_complete) {
                    $acc_detail = AccReceivableDetails::where('acc_id', $not_complete->id)->get();
                    $paid_principal   =  $acc_detail->sum('paid_principal');
                    $paid_interest    =  $acc_detail->sum('paid_interest');
                    $paid_risk        =  $acc_detail->sum('paid_risk');
                    $paid_maintenance =  $acc_detail->sum('paid_maintenance');

                    $updat_acc = AccReceivables::find($not_complete->id);
                    $updat_acc->payment_status_id     = 1;
                    $updat_acc->principal             = $paid_principal;
                    $updat_acc->interest_per_month    = $paid_interest ;
                    $updat_acc->risk_per_month        = $paid_risk ;
                    $updat_acc->maintenance_per_month = $paid_maintenance;
                    $updat_acc->payment_per_month     = $acc_detail->sum('received');
                    $updat_acc->received              = $acc_detail->sum('received');
                    $updat_acc->loan_balance          = ($not_complete->loan_balance+$not_complete->principal)-$paid_principal;
                    $updat_acc->unreceived            = 0;
                    $updat_acc->save();
                }

                if($request->principal_add>0) {
                    $lastnum = AccReceivables::where('loan_id',$request->id)->whereIn('payment_status_id',[1,2])->orderBy('id','desc')->first();
                    $request['id'] = null;
                    $request['loan_code'] = null;
                    $loan = Loan::updateOrCreate(['id' => $this->getLoan($request)['id']],$this->getLoan($request));

                    $findLoan = Loan::find($id);
                    $balance_principal = $findLoan->balance_principal;
                    $total_received= $balance_principal + $request->penalty_interest + $request->penalty_risk;

                    $backDataAcc = AccReceivables::where('loan_id',$id)->where('payment_status_id',3)->get();
                    foreach($backDataAcc as $val) {

                        $back = new BackPayment();
                        $back->acc_id                = $val->id;
                        $back->loan_id               = $val->loan_id;
                        $back->currency_id           = $val->currency_id;
                        $back->client_id             = $val->client_id;
                        $back->co_id                 = $val->co_id;
                        $back->branch_id             = $val->branch_id;
                        $back->payment_date          = $val->payment_date;
                        $back->num                   = $val->num;
                        $back->interest_per_month    = $val->interest_per_month;
                        $back->risk_per_month        = $val->risk_per_month;
                        $back->maintenance_per_month = $val->maintenance_per_month;
                        $back->principal             = $val->principal;
                        $back->loan_balance          = $val->loan_balance;
                        $back->payment_per_month     = $val->payment_per_month;
                        $back->unreceived            = $val->unreceived;
                        $back->payment_status_id     = $val->payment_status_id;
                        $back->open_close            = $val->open_close;
                        $back->created_at            = $val->created_at;
                        $back->updated_at            = $val->updated_at;
                        $back->save();
                    }

                    AccReceivables::where('loan_id',$id)->where('payment_status_id',3)->delete();

                    $new_acc = new AccReceivables();
                    $new_acc->loan_id            = $id;
                    $new_acc->client_id          = $request->client_id;
                    $new_acc->co_id              = $request->co_id;
                    $new_acc->branch_id          = Auth::user()->branch_id;
                    $new_acc->currency_id        = Helper::byCurrency();
                    $new_acc->num                = $lastnum==null?1:$lastnum->num+1;
                    $new_acc->payment_date       = date('Y-m-d');
                    $new_acc->received_date      = date('Y-m-d');
                    $new_acc->principal          = $balance_principal;
                    $new_acc->interest_per_month = $request->penalty_interest;
                    $new_acc->risk_per_month     = $request->penalty_risk;
                    $new_acc->payment_per_month  = $total_received;
                    $new_acc->received           = $total_received;
                    $new_acc->open_close         = 2;
                    $new_acc->loan_balance       = 0;
                    $new_acc->unreceived         = 0;
                    $new_acc->created_at         = new \DateTime();
                    $new_acc->payment_status_id  = 8;
                    $new_acc->save();

                    $detail = new AccReceivableDetails();
                    $detail->loan_id           = $id;
                    $detail->client_id         = $request->client_id;
                    $detail->co_id             = $request->co_id;
                    $detail->branch_id         = Auth::user()->branch_id;
                    $detail->currency_id       = Helper::byCurrency();
                    $detail->acc_id            = $new_acc->id;
                    $detail->received_date     = date('Y-m-d');
                    $detail->paid_interest     = $request->penalty_interest;
                    $detail->paid_risk         = $request->penalty_risk;
                    $detail->paid_principal    = $balance_principal;
                    $detail->received          = $total_received;
                    $detail->chart_of_acc_id   = $request->payment_method;
                    $detail->unreceived        = 0;
                    $detail->condition_payment = 8;
                    $detail->invoice_number    = Helper::invoiceNumberAuto(AccReceivableDetails::class, 6, 'invoice_number');
                    $detail->created_by        = Auth::user()->id;

                    $detail->save();

                    foreach($request->rows as $key => $value) {
                        if($key==0){
                            $type_open_close = 2;
                        } else{
                            $type_open_close = 1;
                        }
                        $arr = array(
                            'loan_id'           => $loan->id,
                            'client_id'         => $request->client_id,
                            'co_id'             => $request->co_id,
                            'branch_id'         => Auth::user()->branch_id,
                            'currency_id'       => Helper::byCurrency(),
                            'num'               => $key + 1,
                            'payment_date'      => date('Y-m-d', strtotime($value['payment_date'])),
                            'received_date'     => null,
                            'interest_per_month'=> $value['interestPerMonth'],
                            'risk_per_month'    => $value['riskPerMonth'],
                            'principal'         => $value['principal'],
                            'loan_balance'      => $value['loan_balance'],
                            'payment_per_month' => $value['payment_per_month'],
                            'unreceived'        => $value['payment_per_month'],
                            'created_at'        => new \DateTime(),
                            'payment_status_id' => $loan->loan_status_id==1?4:3, // Pending
                            'open_close'        => $type_open_close,
                        );
                        AccReceivables::insert($arr);
                    }

                    $reschedule = New Reschedule();
                    $reschedule->loan_id            = $id;
                    $reschedule->client_id          = $request->client_id;
                    $reschedule->co_id              = $request->co_id;
                    $reschedule->reschedule_service = $request->re_service??0;
                    $reschedule->reschedule_total   = $request->total_re??0;
                    $reschedule->service            = $request->service;
                    $reschedule->service_total      = $request->total_service;
                    $reschedule->date               = date('Y-m-d');
                    $reschedule->branch_id          = Auth::user()->branch_id;
                    $reschedule->currency_id        = Auth::user()->currency_id;
                    $reschedule->status             = 3;
                    $reschedule->amount             = $request->principal_add;
                    $reschedule->save();

                    $updateLoan = Loan::find($id);
                    $updateLoan->balance_principal   = 0;
                    $updateLoan->balance_interest    = 0;
                    $updateLoan->balance_risk        = 0;
                    $updateLoan->balance_maintenance = 0;
                    $updateLoan->loan_balance        = 0;
                    $updateLoan->loan_status_id      = 3;
                    $updateLoan->completed_date      = date('Y-m-d');
                    $updateLoan->increment('loan_in',$total_received);
                    $updateLoan->increment('paid_interest',$request->penalty_interest);
                    $updateLoan->increment('paid_risk',$request->penalty_risk);
                    $updateLoan->increment('paid_principal', $balance_principal);
                    $updateLoan->update();
                }
                else {
                    $loan = Loan::updateOrCreate(['id' => $this->getLoan($request)['id']],$this->getLoan($request));
                    $firstAcc = AccReceivables::where('loan_id',$request->id)->orderBy('id','desc')->first();

                    if($request->principal_down>0) {
                        $new_acc = new AccReceivables();
                        $new_acc->loan_id           = $request->id;
                        $new_acc->client_id         = $request->client_id;
                        $new_acc->co_id             = $request->co_id;
                        $new_acc->branch_id         = Auth::user()->branch_id;
                        $new_acc->currency_id       = Helper::byCurrency();
                        $new_acc->num               = $firstAcc==null?1:$firstAcc->num+1;
                        $new_acc->payment_date      = date('Y-m-d');
                        $new_acc->received_date     = date('Y-m-d');
                        $new_acc->principal         = $request->principal_down;
                        $new_acc->interest_per_month= $request->penalty_interest;
                        $new_acc->risk_per_month    = $request->penalty_risk;
                        $new_acc->payment_per_month = $request->principal_down + $request->penalty_interest + $request->penalty_risk;
                        $new_acc->received          = $request->principal_down + $request->penalty_interest + $request->penalty_risk;
                        $new_acc->loan_balance      = $request->amount_principal;
                        $new_acc->open_close        = 2;
                        $new_acc->unreceived        = 0;
                        $new_acc->created_at        = new \DateTime();
                        $new_acc->payment_status_id = 9;
                        $new_acc->save();

                        $detail = new AccReceivableDetails();
                        $detail->loan_id           = $request->id;
                        $detail->client_id         = $request->client_id;
                        $detail->co_id             = $request->co_id;
                        $detail->branch_id         = Auth::user()->branch_id;
                        $detail->currency_id       = Helper::byCurrency();
                        $detail->acc_id            = $new_acc->id;
                        $detail->paid_principal    = $request->principal_down;
                        $detail->paid_interest     = $request->penalty_interest;
                        $detail->paid_risk         = $request->penalty_risk;
                        $detail->received          = $request->principal_down + $request->penalty_interest + $request->penalty_risk;
                        $detail->received_date     = date('Y-m-d');
                        $detail->chart_of_acc_id   = $request->payment_method;
                        $detail->unreceived        = 0;
                        $detail->condition_payment = 9;
                        $detail->invoice_number    = Helper::invoiceNumberAuto(AccReceivableDetails::class, 6, 'invoice_number');
                        $detail->created_by        = Auth::user()->id;
                        $detail->save();

                        $reschedule = New Reschedule();
                        $reschedule->loan_id            = $request->id;
                        $reschedule->client_id          = $request->client_id;
                        $reschedule->co_id              = $request->co_id;
                        $reschedule->reschedule_service = $request->re_service??0;
                        $reschedule->reschedule_total   = $request->total_re??0;
                        $reschedule->penalty_interest   = $request->penalty_interest;;
                        $reschedule->date               = date('Y-m-d');
                        $reschedule->branch_id          = Auth::user()->branch_id;
                        $reschedule->currency_id        = Auth::user()->currency_id;
                        $reschedule->status             = 1;
                        $reschedule->amount             = $request->principal_down;
                        $reschedule->save();

                        $loan_principal = Loan::find($request->id);
                        $loan_principal->reschedule_amount += $request->principal_down;
                        $loan_principal->loan_in           += $request->principal_down + $request->penalty_interest + $request->penalty_risk;
                        $loan_principal->paid_principal    += $request->principal_down;
                        $loan_principal->paid_interest     += $request->penalty_interest;
                        $loan_principal->paid_risk         += $request->penalty_risk;
                        $loan_principal->update();
                    }
                    AccReceivables::where('loan_id',$request->id)->where('payment_status_id',3)->delete();
                    foreach($request->rows as $key => $value){
                        if($key==0) {
                            $type_open_close = 2;
                        } else{
                            $type_open_close = 1;
                        }
                        $arr = array(
                            'loan_id'           => $loan->id,
                            'client_id'         => $request->client_id,
                            'co_id'             => $request->co_id,
                            'branch_id'         => Auth::user()->branch_id,
                            'currency_id'       => Helper::byCurrency(),
                            'num'               => $key + 1,
                            'payment_date'      => date('Y-m-d', strtotime($value['payment_date'])),
                            'received_date'     => null,
                            'interest_per_month'=> $value['interestPerMonth'],
                            'risk_per_month'    => $value['riskPerMonth'],
                            'principal'         => $value['principal'],
                            'loan_balance'      => $value['loan_balance'],
                            'payment_per_month' => $value['payment_per_month'],
                            'unreceived'        => $value['payment_per_month'],
                            'created_at'        => new \DateTime(),
                            'payment_status_id' => $loan->loan_status_id==1?4:3, // Pending
                            'open_close'        => $type_open_close,
                        );
                        AccReceivables::insert($arr);
                    }
                }

                $user   = User::find(Auth::user()->id);
                $client = Client::find($loan->client_id);
                if($request->principal_add>0){
                    $subject = "អតិថិជន $client->name កាច់លុយកម្ចីចំនួនទំហំទឹកប្រាក់ $request->loan_out ដោយ $user->name.";
                } else{
                    $subject = "រៀបចំតារាងកម្ចីអតិថិជន $client->name ទំហំទឹកប្រាក់ $request->loan_out ដោយ $user->name.";
                }
                $subject_type = get_class($loan);
                $subject_id   = $loan->id;
                $causer_type  = get_class($user);
                $causer_id    = Auth::user()->id;
                $branch       = Auth::user()->branch_id;
                $log_name     = 'Loan Model';
                LogActivity::addToLog($subject,$subject_type,$subject_id,$causer_type,$causer_id,$branch,$log_name);

                $res = [
                    'status' => 1,
                    'message'=> $loan->wasRecentlyCreated?'កម្ចីថ្មីបង្កើតដោយជោគជ័យ':'រៀបតារាងឡើងវិញដោយជោគជ័យ',
                    'data'   => new LoanResource($loan),
                ];
            }
            DB::commit();
        } catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Loan Client not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }

    public function update($id)
    {
        $loan = Loan::find($id);
        $loan->loan_status_id = 2;
        $loan->approved_by    = Auth::user()->id;
        $loan->update();

        AccReceivables::where('loan_id',$id)->update(['payment_status_id'=>3]);
        $user   = User::find(Auth::user()->id);
        $client = Client::find($loan->client_id);

        $subject      = "អនុញ្ញាតចេញកម្ចីអោយអតិថិជន $client->name ទំហំទឹកប្រាក់ $loan->loan_out ដោយ $user->name.";
        $subject_type = get_class($loan);
        $subject_id   = $loan->id;
        $causer_type  = get_class($user);
        $causer_id    = Auth::user()->id;
        $branch       = Auth::user()->branch_id;
        $log_name     = 'Loan Model';
        LogActivity::addToLog($subject,$subject_type,$subject_id,$causer_type,$causer_id,$branch,$log_name);
        $res = [
            'status' => 1,
            'message'=> 'Approved Client success',
            'data'   => new LoanResource($loan),
        ];
        return response()->json($res,200);
    }

    public function destroy($id)
    {

        DB::beginTransaction();
        try {
            $loan = Loan::find($id);
            $loan->delete();

            AccReceivables::where('loan_id',$id)->delete();
            LoanCollateral::where('loan_id',$id)->delete();
            $user   = User::find(Auth::user()->id);
            $client = Client::find($loan->client_id);

            $subject     = "លុបកម្ចីរបស់អតិថិជន $client->name ទំហំទឹកប្រាក់ $loan->loan_out ដោយ $user->name.";
            $subject_type= get_class($loan);
            $subject_id  = $loan->id;
            $causer_type = get_class($user);
            $causer_id   = Auth::user()->id;
            $branch      = Auth::user()->branch_id;
            $log_name    = 'Loan Model';
            LogActivity::addToLog($subject,$subject_type,$subject_id,$causer_type,$causer_id,$branch,$log_name);
            $res = [
                'status' => 1,
                'message'=> 'Deleted success',
                'data'   => $loan,
            ];
            DB::commit();
        }catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Deleted not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }

    public function ShowPayment($id)
    {

        $data     = AccReceivables::where('loan_id',$id)->where('payment_status_id', '<>',7)->orderBy('payment_date','asc')->get();
        $loan     = Loan::find($id);
        $client   = Client::find($loan->client_id);
        $co       = User::find($loan->co_id);
        $currency = Currency::find($loan->currency_id);
        $count    = $data->count();
        $count    = ceil($count/2);
        $garuantor1 = Guarantor::where('client_id',$client->id)->where('type',1)->first();
        $garuantor2 = Guarantor::where('client_id',$client->id)->where('type',2)->first();
        $garuantor3 = Guarantor::where('client_id',$client->id)->where('type',3)->first();

        // $real_estate_one = CollateralDetail::where('loan_id',$id)->where('status_type',1)->first();
        // $real_estate_two = CollateralDetail::where('loan_id',$id)->where('status_type',2)->first();
        // $motor = CollateralDetail::where('loan_id',$id)->where('status_type',3)->first();
        // $car = CollateralDetail::where('loan_id',$id)->where('status_type',4)->first();
        // $countSchedule = Loan::where('client_id', $loan->client_id)->count();

        return [
            'countPay'      => $count,
            'currency'      => $currency,
            'garuantor1'    => $garuantor1 ? new GuarantorResource($garuantor1) : '',
            'garuantor2'    => $garuantor2 ? new GuarantorResource($garuantor2) : '',
            'garuantor3'    => $garuantor3 ? new GuarantorResource($garuantor3) : '',
            'co'            => new UserResource($co),
            'loan'          => new LoanResource($loan),
            'client'        => new ClientResource($client),
            // 'real_estate_one' => $real_estate_one ? new CollateralDetailResource($real_estate_one) : null,
            // 'real_estate_two' => $real_estate_two ? new CollateralDetailResource($real_estate_two) : null,
            // 'motor'         => $motor ? new CollateralDetailResource($motor) : null,
            // 'car'           => $car ? new CollateralDetailResource($car) : null,
            'data'          => ShowPaymentResource::collection($data),
            // 'countSchedule' => $countSchedule,
        ];
    }

    public function HistoryPayment($id)
    {
        $loan     = Loan::find($id);
        $client   = Client::find($loan->client_id);
        $data = AccReceivables::where('loan_id', $id)
            ->where('payment_status_id', '<>', 7)
            ->orderBy('id', 'asc')
            ->get();

        return [
            'data'   => ShowPaymentResource::collection($data),
            'client' => new ClientResource($client),
        ];
    }

    public function GetPayment($id)
    {
        $data = AccReceivables::where('loan_id',$id)->orderBy('payment_date','asc')->get();
        $loan = Loan::find($id);
        $client = Client::find($loan->client_id);

        return [
            'data' =>ShowPaymentResource::collection($data),
            'client' =>new ClientResource($client),
        ];
    }

    public function getLoanPayment(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = Loan::whereHas('client', function ($query) use ($request) {
            if(!$request->loan_code ==''){
                $query->where('loans.loan_code', 'LIKE', '%'.$request->loan_code.'%');
            }
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[])
            {
                $query->whereIn('co_id',$request->co_id);
            }
        })
        ->where(function($query){
            // $query->whereIn('co_id',Helper::group());
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
            $query->whereIn('loan_status_id',[2,5]);
        })
        ->orderBy('id','DESC')
        ->paginate($per_page);
        return LoanResource::collection($data);
    }

    public function getContractDay($id)
    {
        $loan    = Loan::find($id);
        $currency= Currency::find($loan->currency_id);
        $client  = Client::find($loan->client_id);
        $profile = Guarantor::where('client_id',$loan->client_id)->where('type',1)->first();
        $one     = Guarantor::where('client_id',$loan->client_id)->where('type',2)->first();
        $two     = Guarantor::where('client_id',$loan->client_id)->where('type',3)->first();
        $collateral_detail = CollateralDetail::where('loan_id',$id)->where('status_type',1)->get();

        return [
            'currency'   => $currency,
            'loan'       => new LoanResource($loan),
            'client'     => new ClientResource($client),
            'profile'    => $profile?(new GuarantorResource($profile)):null,
            'one'        => $one?(new GuarantorResource($one)):null,
            'two'        => $two?(new GuarantorResource($two)):null,
            'collateral_detail' => $collateral_detail?(CollateralDetailResource::collection($collateral_detail)):null,
        ];
    }

    public function MoveCo(Request $request)
    {
        $this->validate($request, [
            'from_co_id' => 'required',
            'to_co_id'   => 'required',
        ]);
        DB::beginTransaction();
        try {

            if($request->loan_id=='' && $request->type_move == false) {
                Loan::where('co_id',$request->from_co_id)->update([
                    'co_id' => $request->to_co_id
                ]);
                AccReceivables::where('co_id',$request->from_co_id)->update([
                    'co_id' => $request->to_co_id
                ]);
                AccReceivableDetails::where('co_id',$request->from_co_id)->update([
                    'co_id' => $request->to_co_id
                ]);
            } else{
                Loan::where('co_id',$request->from_co_id)->where('id',$request->loan_id)->update([
                    'co_id' => $request->to_co_id
                ]);
                AccReceivables::where('co_id',$request->from_co_id)->where('loan_id',$request->loan_id)->update([
                    'co_id' => $request->to_co_id
                ]);
                AccReceivableDetails::where('co_id',$request->from_co_id)->where('loan_id',$request->loan_id)->update([
                    'co_id' => $request->to_co_id
                ]);
            }
            $user = User::find(Auth::user()->id);
            $from = User::find($request->from_co_id);
            $to   = User::find($request->to_co_id);
            $subject      = "ប្ដូរពីមន្រ្តីឥណទាន  $from->name ទៅមន្រ្តីឥណទាន $to->name ដោយ $user->name.";
            $subject_type = get_class($from);
            $subject_id   = $from->id;
            $causer_type  = get_class($user);
            $causer_id    = Auth::user()->id;
            $branch       = Auth::user()->branch_id;
            $log_name     = 'Loan Model';
            LogActivity::addToLog($subject,$subject_type,$subject_id,$causer_type,$causer_id,$branch,$log_name);
            $res = [
                'status'  => 1,
                'message' => 'Move success',
                'data'    => $user,
            ];
            DB::commit();
        } catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Move not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }

    public function moveToWriteOff($id)
    {
        $loan = Loan::find($id);
        $loan->client_type = 2;
        $loan->update();

        $user = User::find(Auth::user()->id);
        $client = Client::find($loan->client_id);
        $subject     ="អតិថិជន $client->name បានផា្លស់ប្ដូរទៅអតិថិជនខូច ដោយ $user->name.";
        $subject_type= get_class($loan);
        $subject_id  = $loan->id;
        $causer_type = get_class($user);
        $causer_id   = Auth::user()->id;
        $branch      = Auth::user()->branch_id;
        $log_name    = 'Loan Model';
        LogActivity::addToLog($subject,$subject_type,$subject_id,$causer_type,$causer_id,$branch,$log_name);
        $res = [
            'status' => 1,
            'message'=> 'Client Move to Write Off success',
            'data'   => new LoanResource($loan),
        ];
        return response()->json($res,200);
    }
}
