<?php

namespace App\Models\Accounting;

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

class Invoice extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $guarded = [];

    public function student()
    {
        return $this->belongsTo(StudentInfo::class, 'student_info_id');
    }

    public function invoiceItems()
    {
        return $this->hasMany(InvoiceItem::class, 'invoice_id');
    }

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

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($invoice) {
            // Generate a unique student ID number
            $invoice->invoice_no = static::generateInvoiceNo();
        });

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

    protected static function generateInvoiceNo()
    {
        $year = date('y');
        // Get the last generated invoice_no number without the global scope
        $lastInvoiceNo = static::withoutGlobalScope(BranchFilterScope::class)
            ->orderBy('id', 'desc')
            ->first();

        // If there are no existing invoice_no, start with 000001
        if (!$lastInvoiceNo) {
            return $year.'000001';
        }

        // Increment invoice_no 1 for every new invoice
        $invoiceNo = (int)$lastInvoiceNo->invoice_no + 1;

        return $invoiceNo;
    }
}
