<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    use HasFactory;

    protected $fillable = [
        'company_id',
        'customer_id',
        'invoice_no',
        'invoice_date',
        'due_date',
        'subtotal',           // Added
        'tax_total',          // Added
        'total_amount',
        'total_paid',
        'outstanding_balance',
        'status', 
        'memo',
        'created_by'
    ];

    protected $casts = [
        'invoice_date' => 'date',
        'due_date' => 'date',
        'subtotal' => 'decimal:2',
        'tax_total' => 'decimal:2',
        'total_amount' => 'decimal:2',
    ];

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function items()
    {
        return $this->hasMany(InvoiceItem::class);
    }

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

    public function user()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function isOverdue()
    {
        return $this->status !== 'paid' && $this->due_date->isPast();
    }
    
    
    /**
 * Relationship: An invoice can have many credit memos.
 */
public function creditMemos()
{
    return $this->hasMany(CreditMemo::class, 'original_invoice_id');
}


public function getAgingBucket()
{
    if ($this->status === 'paid' || $this->outstanding_balance <= 0) {
        return 'current';
    }

    $daysOverdue = now()->diffInDays($this->due_date, false);

    if ($daysOverdue >= 0) {
        return 'current'; // Not yet due
    }

    $absDays = abs($daysOverdue);

    if ($absDays <= 30) return '1-30';
    if ($absDays <= 60) return '31-60';
    if ($absDays <= 90) return '61-90';
    return '90+';
}

}