<?php


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    protected $fillable = [
        'legal_case_id',
        'user_id',          // <--- Make sure this is here!
        'invoice_number',
        'due_date',
        'status',
        'total_amount',
        'approved_by',
        'approved_at',
        'rejection_reason'
    ];

    // protected $fillable = ['legal_case_id', 'invoice_number', 'due_date', 'total_amount', 'status'];

    protected $casts = ['due_date' => 'date'];

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

    public function legalCase()
    {
        return $this->belongsTo(LegalCase::class);
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }
    public function credit_notes()
    {
        return $this->hasMany(CreditNote::class);
    }

    // Helper to calculate what is left to pay
    public function getBalanceAttribute()
    {
        $paid = $this->payments->sum('amount');
        $credited = $this->credit_notes->sum('amount');
        return $this->total_amount - ($paid + $credited);
    }

    // Ensure this relationship exists
    public function case()
    {
        return $this->belongsTo(LegalCase::class, 'legal_case_id');
    }

    // Optional: A helper to get the client easily in code (but not for eager loading)
    public function getClientAttribute()
    {
        return $this->case ? $this->case->client : null;
    }
}
