<?php

namespace App\Models;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use App\Models\Accounting\ChartOfAccount;
use Illuminate\Database\Eloquent\SoftDeletes;

class Loan extends Model
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'id',
        'client_id',
        'co_id',
        'branch_id',
        'currency_id',
        'completed_date',
        'installment_date',
        'start_date',
        'expired_date',
        'reschedule_amount',
        'balance_maintenance',
        'insurance',
        'total_insurance',
        'level_loan',
        'chart_of_acc_id',
        'loan_code',
        'loan_out',
        'interest',
        'total_interest',
        'risk',
        'total_risk',
        'service',
        'total_service',
        'service_collection',
        'total_collection',
        'loan_receive',
        'amount_client_receive',
        'balance_principal',
        'balance_interest',
        'balance_risk',
        'loan_balance',
        'paid_principal',
        'paid_interest',
        'paid_risk',
        'loan_in',
        'total_penalty',
        'paid_maintenance',
        'desc',
        'term_type',
        'term_condi',
        'period',
        'condition_pay',
        'loan_status_id',
        'closing_date',
        'approved_by',
        'closing_by',
        'type_loan',
        'maintenance',
        'total_maintenance',
        'saving',
        'total_saving',
        'total_waiv',
        'client_type',
        'created_by',
    ];

    public function currency()
    {
        return $this->belongsTo(Loan::class, 'currency_id');
    }
    public function loan_status()
    {
        return $this->belongsTo(LoanStatus::class, 'loan_status_id');
    }
    public function co()
    {
        return $this->belongsTo(User::class, 'co_id');
    }

    public function disburstVia()
    {
        return $this->belongsTo(ChartOfAccount::class, 'chart_of_acc_id');
    }

    public function client()
    {
        return $this->belongsTo(Client::class, 'client_id');
    }
    public function getsumprincipalAttribute()
    {
        return $this->where('co_id',$this->co_id)->sum('loan_out');
    }
    public function getsuminterestAttribute()
    {
        return $this->where('co_id',$this->co_id)->sum('total_interest');
    }
    public function getsumriskAttribute()
    {
        return $this->where('co_id',$this->co_id)->sum('total_risk');
    }
    public function getcountdaylateAttribute()
    {
        $late = AccReceivables::where('co_id',$this->co_id)->where('payment_date','<',date('Y-m-d'))->whereIn('payment_status_id',[2,3])->groupBy('client_id')->get()->count();
        $amount = AccReceivables::where('co_id',$this->co_id)->where('payment_date','<',date('Y-m-d'))->whereIn('payment_status_id',[2,3])->sum('principal');
        return array(
            'late' => $late,
            'amount' => $amount,
        );
    }

    public function accReceivables()
    {
        return $this->hasMany(AccReceivables::class,'loan_id','id');
    }

    public function funAccReceivables(){
        $data = AccReceivables::where('loan_id',$this->id)
        ->where('client_id',$this->client_id)
        ->whereIn('payment_status_id',[2,3])
        ->where(function($qeury){
            if(request()->date!=''){
                $qeury->where(DB::raw("DATE_FORMAT(payment_date, '%Y-%m-%d')"),'<=',request()->date);
            } else{
                $qeury->where(DB::raw("DATE_FORMAT(payment_date, '%Y-%m-%d')"),'<=',date('Y-m-d'));
            }
        });
        return $data;
    }

    public function getfirstIDAttribute()
    {
        return $this->funAccReceivables()->min('id');
    }

    public function getcurrentPaymentAttribute()
    {
      return $this->funAccReceivables()->where('id',$this->first_id)->sum('unreceived');
    }

    public function getlatePaymentAttribute()
    {
      return $this->funAccReceivables()->sum('unreceived');
    }
    // public function collateralDetails()
    // {
    //     return $this->hasMany(CollateralDetail::class,'loan_id');
    // }

    public function gettotallateAttribute()
    {
        $acc = AccReceivables::find($this->first_id);
        $now = Carbon::now();
        $end = Carbon::parse($acc->payment_date);
        $total_late = $now->diff($end)->days;
        return $total_late;
    }

    public function getdateLateAttribute()
    {
        return AccReceivables::find($this->first_id);
    }

    public function getActualPaymentDateAttribute()
    {
        return $this->funAccReceivables()->max('payment_date');
    }
    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

}
