<?php

namespace App\Models\Accounting;

use App\Models\Scopes\BranchFilterScope;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Expense extends Model
{
    use HasFactory;
    use SoftDeletes;
    
    protected $guarded = [];

    public function accountingHead()
    {
        return $this->belongsTo(AccountingHead::class, 'accounting_head_id');
    }

    protected static function booted()
    {
        static::addGlobalScope(new BranchFilterScope);
    }

    protected static function boot()
    {
        parent::boot();

        self::creating(function($model){
            $model->uuid =  Str::uuid()->toString();
            $model->invoice_no = $model->generateInvoiceCode();
        });
    }

    public function generateInvoiceCode()
    {
        $yearPrefix = date('y');

        $lastIncome = self::where('invoice_no', 'LIKE', "$yearPrefix%")
                          ->orderBy('invoice_no', 'desc')
                          ->first();

        if ($lastIncome) {
            $lastNumber = (int) substr($lastIncome->invoice_no, 2);
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1000;
        }

        $newInvoiceCode = $yearPrefix . str_pad($newNumber, 4, '0', STR_PAD_LEFT);

        return $newInvoiceCode;
    }
}
