<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    protected $fillable = [
        'invoice_number','client_id','created_by','division','type',
        'issue_date','due_date','billing_month','billing_year',
        'subtotal','tax_percent','tax_amount','total','amount_paid',
        'status','notes','paid_at','is_recurring'
    ];
    protected $casts = [
        'issue_date'=>'date','due_date'=>'date','paid_at'=>'datetime',
        'is_recurring'=>'boolean','subtotal'=>'decimal:2',
        'tax_amount'=>'decimal:2','total'=>'decimal:2','amount_paid'=>'decimal:2'
    ];

    public function client()    { return $this->belongsTo(Client::class); }
    public function items()     { return $this->hasMany(InvoiceItem::class); }
    public function payments()  { return $this->hasMany(Payment::class); }
    public function createdBy() { return $this->belongsTo(User::class, 'created_by'); }

    public static function generateNumber(string $division): string
    {
        $year   = date('Y');
        $month  = date('m');
        $prefix = ['JPN'=>'INV','FixLab'=>'FLB','Havva'=>'HVV'][$division] ?? 'INV';
        $seq    = str_pad(
            self::where('division',$division)->whereYear('created_at',$year)->whereMonth('created_at',$month)->count() + 1,
            4, '0', STR_PAD_LEFT
        );
        return "{$prefix}-{$year}{$month}-{$seq}";
    }

    public function recalculate(): void
    {
        $subtotal = $this->items()->sum('total');
        $taxAmt   = $subtotal * ($this->tax_percent / 100);
        $this->update(['subtotal'=>$subtotal,'tax_amount'=>$taxAmt,'total'=>$subtotal + $taxAmt]);
    }
}
