<?php

namespace App\Observers;

use App\Models\Loan;
use App\Models\LoanHistory;
use App\Models\TreasuryExit;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class LoanObserver
{
    /**
     * Handle the Loan "created" event.
     */
    public function created(Loan $loan): void
    {
        // Update borrower's loan statistics
        $borrower = $loan->borrower;

        $borrower->increment('count_loans');
    }

    /**
     * Handle the Loan "updated" event.
     */
    public function updated(Loan $loan): void
    {
        $transaction = 2;

        // Check if the loan was just validated
        if ($loan->is_valid && $loan->isDirty('is_valid')) {
            // Update borrower's loan statistics
            $borrower = $loan->borrower;

            $borrower->increment('number_loans');
            $borrower->increment('total_loans', $loan->amount);
            $borrower->in_progress = true;
            $borrower->save();

            // Add a new treasury exit
            $treasuryExit = new TreasuryExit();

            $treasuryExit->category_id = 1;
            $treasuryExit->date = $loan->date;
            $treasuryExit->amount = $loan->amount;
            $treasuryExit->title = $loan->code;
            $treasuryExit->description = "Prêt accordé à '{$borrower->name()}'";
            $treasuryExit->attachment = $loan->attachment;
            $treasuryExit->is_valid = true;
            $treasuryExit->validation_date = Carbon::now()->format('Y-m-d H:i:s');

            $treasuryExit->save();

            $transaction = 3;
        }
    }

    /**
     * Handle the Loan "created" event.
     */
    public function deleted(Loan $loan): void
    {
        // Update borrower's loan statistics
        $borrower = $loan->borrower;

        $borrower->decrement('count_loans');
    }

    /**
     * Handle the Loan "created" event.
     */
    public function restored(Loan $loan): void
    {
        // Update borrower's loan statistics
        $borrower = $loan->borrower;

        $borrower->increment('count_loans');
    }
}
