<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\Helper;
use App\Models\Accounting\Journal;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Accounting\ChartOfAccount;
use App\Models\Accounting\Depreciation;
use App\Models\Accounting\DepreciationDetail;
use App\Models\Accounting\DepreciationPayment;
use App\Models\AccReceivables;
use App\Models\Loan;
use App\Models\LoanLossProvision;
use Carbon\Carbon;

class AutoUpdateScheduleController extends Controller
{
    
    public static function Depreciation()
    {

        DB::beginTransaction();
        try {
            
            if(date('Y-m-d') === date('Y-m-t') && date('Y-m-d H:i') === date('Y-m-t') . ' 23:30'){

                $startDate = date('Y-m-01'); // First day of the month
                $endDate   = date('Y-m-t'); // Last day of the month
    
                $data = DepreciationDetail::whereBetween('payment_date', [$startDate, $endDate])->where('status',1)->get();
                
                foreach($data as $value) {
                    $depDetails = DepreciationDetail::find($value->id);
                    $depDetails->paid_date = date('Y-m-d');
                    $depDetails->paid     += $depDetails->unpaid;
                    $depDetails->unpaid    = 0;
                    $depDetails->status    = 2;
                    $depDetails->update();
    
                    $depreciation = Depreciation::find($depDetails->dep_id);
                    $depreciation->increment('total_paid',$depDetails->paid);
                    $depreciation->decrement('balance',$depDetails->paid);
                    $depreciation->update();
    
                    $depPayment = DepreciationPayment::create([
                        'dep_detail_id' => $depDetails->id,
                        'paid_date'     => date('Y-m-d'),
                        'paid'          => $depDetails->paid,
                        'loan_balance'  => $depreciation->balance,
                        'created_by'    => $depreciation->created_by,
                        'branch_id'     => $depreciation->branch_id,
                        'currency_id'   => $depreciation->currency_id,
                    ]);
                    $parent_id = Helper::findParentId();
                    $journal   = self::insertJournal($depreciation->chart_expense, $parent_id, date('Y-m-d'), $depPayment->id, get_class($depPayment),$depDetails->paid,0,$depreciation);
                    $parentID  = $journal->parent_id;
                    self::insertJournal($depreciation->chart_asset, $parentID, date('Y-m-d'), $depPayment->id, get_class($depPayment),0,$depDetails->paid,$depreciation);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            return response()->json(["message" => "Something wrong! please check it again"], 200);
        }
    }

    public function insertJournal($chartID,$parentID,$journalDate,$paymentTable,$paymentTableType,$debit,$credit,$depreciation)
    {   
        return Journal::create([
            'chart_of_acc_id'   => $chartID,
            'parent_id'         => $parentID,
            'journal_date'      => $journalDate,
            'payment_model_id'  => $paymentTable,
            'payment_model_type'=> $paymentTableType,
            'debit'             => $debit,
            'credit'            => $credit,
            'branch_id'         => $depreciation->branch_id,
            'currency_id'       => $depreciation->currency_id,
            'created_by'        => $depreciation->created_by??1,
            'desc'              => 'Auto created by system.',
            'status'            => 1,
        ]);
    }

    public static function LoanLossProvision()
    {
        DB::beginTransaction();
        try {
            if(date('Y-m-d') === date('Y-m-t') && date('Y-m-d H:i') === date('Y-m-t') . ' 23:30'){

                $today = date('Y-m-d');
                $data = AccReceivables::whereIn('payment_status_id',[2,3])
                    ->where(DB::raw("DATE_FORMAT(payment_date, '%Y-%m-%d')"),'<',$today)
                    ->whereHas('loan',function($query){
                        $query->where('loan_status_id',2);
                    })
                    ->orderby('id','asc')
                    ->groupby('loan_id')
                    ->get();

                foreach($data as $value) {

                    $acc_receivable = AccReceivables::find($value['id']);
                    $payment_date   = Carbon::parse(date('Y-m-d', strtotime($acc_receivable->payment_date)));
                    $diff_date      = Carbon::parse(date('Y-m-d', strtotime($today)));
                    $interval       = $payment_date->diff($diff_date);
                    $count_late     = intval($interval->format("%R%a"));

                    if($count_late>=7){

                        $provision_percentage_rate = 0;
                        $type_loan_loss_provision  = '';
                        if($count_late>=7 && $count_late<=30){
                            $provision_percentage_rate = 0.01; // 1%
                            $type_loan_loss_provision = 2;
                        }
                        else if($count_late>30 && $count_late<=60){
                            $provision_percentage_rate = 0.05; // 5%
                            $type_loan_loss_provision = 3;
                        }
                        else if($count_late>60){
                            $provision_percentage_rate = 0.1; // 10%
                            $type_loan_loss_provision = 4;
                        }

                        $loan = Loan::find($acc_receivable->loan_id);
                        $amount_loss_provision = $loan->balance_principal*$provision_percentage_rate;
                        $total_amount_late = AccReceivables::where('loan_id',$value['loan_id'])->whereIn('payment_status_id',[2,3])->where('payment_date','<',date('Y-m-d'))->sum('unreceived');

                        LoanLossProvision::create([
                            'branch_id'                => $loan->branch_id,
                            'currency_id'              => $loan->currency_id,
                            'client_id'                => $loan->client_id,
                            'co_id'                    => $loan->co_id,
                            'loan_id'                  => $loan->id,
                            'installment_date'         => date('Y-m-d', strtotime($loan->installment_date)),
                            'loan_out'                 => $loan->loan_out,
                            'loan_balance'             => $loan->balance_principal,
                            'date_late'                => date('Y-m-d', strtotime($acc_receivable->payment_date)),
                            'loss_provision_date'      => $today ,
                            'count_day_date'           => $count_late,
                            'amount_late'              => $total_amount_late,
                            'amount_loss_provision'    => $amount_loss_provision,
                            'type_loan_loss_provision' => $type_loan_loss_provision,
                        ]);
                        $acc_specific_provision   = ChartOfAccount::find(220);  // Specific Provisions for Loan Losses  Expense (Expense)
                        $asset_specific_provision = ChartOfAccount::find(51);  // Specific Loan Loss Provisions (Asset)

                        $parent_id = Helper::findParentId();
                        $journal   = self::insertJournal($acc_specific_provision->id, $parent_id, date('Y-m-d'), $acc_specific_provision->id, get_class($acc_specific_provision),$amount_loss_provision,0,$loan);
                        $parentID  = $journal->parent_id;
                        self::insertJournal($asset_specific_provision->id, $parentID, date('Y-m-d'), $asset_specific_provision->id, get_class($asset_specific_provision),0,$amount_loss_provision,$loan);
                    }       
                }
            }
            DB::commit();
        } 
        catch (\Exception $e) {
            return response()->json(["message" => "Something wrong! please check it again"], 200);
        }
    }
}