<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class AccReceivables extends Model
{
  use SoftDeletes;
  protected $table = 'acc_receivables';
  protected $fillable = [
    'id',
    'loan_id',
    'client_id',
    'co_id', 
    'branch_id', 
    'currency_id',
    'num',
    'principal',
    'interest_per_month',
    'risk_per_month', 
    'maintenance_per_month', 
    'payment_per_month', 
    'payment_date',
    'received_date',
    'loan_balance',
    'penalty', 
    'received', 
    'unreceived',
    'open_close',
    'waiv_penalty',
    'payment_status_id',
  ];

  public function currency()
  {
    return $this->belongsTo(Currency::class, 'currency_id');
  }

  public function loan()
  {
    return $this->belongsTo(Loan::class, 'loan_id');
  }

  public function payment_status()
  {
    return $this->belongsTo(PaymentStatus::class, 'payment_status_id');
  }

  public function co()
  {
    return $this->belongsTo(User::class, 'co_id');
  }

  public function client()
  {
    return $this->belongsTo(Client::class, 'client_id');
  }

  public function countlate()
  {
    return AccReceivables::where('loan_id',$this->loan_id)->whereIn('payment_status_id',[2,3])->count();
  }

  public function accReceivableDetails()
  {
    return $this->hasMany(AccReceivableDetails::class,'acc_id','id');
  }

  public function funAccReceivables()
  {
    $data = AccReceivables::where(function($qeury){
      if(request()->type_collection == 1){
        $qeury->where(DB::raw("DATE_FORMAT(payment_date, '%Y-%m-%d')"),date('Y-m-d')); // Daily Collection
      } 
      else if(request()->type_collect_late==1){
        $qeury->where(DB::raw("DATE_FORMAT(payment_date, '%Y-%m-%d')"),'<=',date('Y-m-d')); // Collect Late with today
      }
      else{
        $qeury->where(DB::raw("DATE_FORMAT(payment_date, '%Y-%m-%d')"),'<',date('Y-m-d')); // Late Collection
      }
    })
    ->where('loan_id',$this->loan_id)
    ->whereIn('payment_status_id',[2,3]);
    return $data;
  }

  public function joinAccWithAccDetails()
  {
    $data = AccReceivables::leftjoin('acc_receivable_details','acc_receivable_details.acc_id','acc_receivables.id')
    ->where(function($qeury){
        if(request()->type_collection == 1){
          $qeury->where(DB::raw("DATE_FORMAT(acc_receivables.payment_date, '%Y-%m-%d')"),date('Y-m-d')); // Daily Collection
        } 
        else if(request()->type_collect_late==1){
          $qeury->where(DB::raw("DATE_FORMAT(payment_date, '%Y-%m-%d')"),'<=',date('Y-m-d')); // Collect Late with today
        }
        else{
          $qeury->where(DB::raw("DATE_FORMAT(acc_receivables.payment_date, '%Y-%m-%d')"),'<',date('Y-m-d')); // Late Collection
        }
    })
    ->whereNull('acc_receivable_details.deleted_at')
    ->where('acc_receivables.loan_id',$this->loan_id)
    ->whereIn('acc_receivables.payment_status_id',[2,3]);
    return $data;
  }

  public function getprincipallateAttribute()
  {
    $AccReceivables = $this->funAccReceivables()->sum('principal');
    $Detail = $this->joinAccWithAccDetails()->sum('acc_receivable_details.paid_principal');
    return $AccReceivables - $Detail;
  }

  public function getinterestlateAttribute()
  {
    $AccReceivables = $this->funAccReceivables()->sum('interest_per_month');
    $Detail = $this->joinAccWithAccDetails()->sum('acc_receivable_details.paid_interest');
    return $AccReceivables - $Detail;
  }

  public function getrisklateAttribute()
  {
    $AccReceivables = $this->funAccReceivables()->sum('risk_per_month');
    $Detail = $this->joinAccWithAccDetails()->sum('acc_receivable_details.paid_risk');
    return $AccReceivables-$Detail;
  }
  
  public function getmaintenancelateAttribute()
  {
    $AccReceivables = $this->funAccReceivables()->sum('maintenance_per_month');
    $Detail = $this->joinAccWithAccDetails()->sum('acc_receivable_details.paid_maintenance');
    return $AccReceivables-$Detail;
  }

  public function getreceivedlateAttribute()
  {
    return $this->funAccReceivables()->sum('received');
  }

  public function getunreceivedlateAttribute()
  {
    return $this->funAccReceivables()->sum('unreceived');
  }

  public function getdatelateAttribute()
  {
    return $this->funAccReceivables()->where('client_id',$this->client_id)->min('payment_date');
  }

  public function getLastDateLateAttribute()
  {
    return $this->funAccReceivables()->where('client_id',$this->client_id)->where('payment_date','<',date('Y-m-d'))->max('payment_date');
  }

  public function getActualPaymentDateAttribute()
  {
    return $this->funAccReceivables()->where('client_id',$this->client_id)->max('payment_date');
  }

  public function getLastReceivedDateAttribute()
  {
    return $this->funAccReceivables()->where('client_id',$this->client_id)->max('received_date');
  }

  public function getfirstIdDatelateAttribute()
  {
    return $this->funAccReceivables()->where('client_id',$this->client_id)->min('id');
  }

  public function gettotallateAttribute()
  {
    $now = Carbon::now();
    $acc = AccReceivables::find($this->first_id_date_late);

    $total_late = 0;
    $total_penalty = 0;

    if($acc!=null) {
      
      $payment_date = Carbon::parse(date('Y-m-d', strtotime($acc->payment_date)));
      $today        = date('Y-m-d');
      $diff_date    = Carbon::parse(date('Y-m-d', strtotime($today)));
      $interval     = $payment_date->diff($diff_date);
      $total_late   = intval($interval->format("%R%a"));
      
      if($total_late>0) {
        if($this->currency_id==1) {
          $total_penalty = round($total_late*1500,-2,PHP_ROUND_HALF_ODD);
        }
        else{
          $total_penalty = round($total_late*0.375,-2,PHP_ROUND_HALF_ODD);
        }
      }
      else{
        $total_penalty = 0;
      }
      $total_penalty = $this->currency_id == 1?round($total_penalty,-2,PHP_ROUND_HALF_ODD):round($total_penalty,2);
      
      return array(
        'total_late'   => $acc->payment_date>$now?0:$total_late,
        'total_penalty'=> $total_penalty??0,
        'start_date'   => $acc->payment_date>$now?'':$acc->payment_date,
      );
    } 
    else{
      return '';
    }
  }
}