<?php

namespace App\Models;

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

class CreditMemo extends Model
{
    use HasFactory;

    protected $fillable = [
        'company_id',
        'customer_id',
        'original_invoice_id', // Link to the source document
        'credit_note_reason_id', // Add this
        'credit_memo_no',      // Matches your SQL: credit_memo_no
        'transaction_date',
        'subtotal',            // Added for financial tracking
        'tax_total',           // Added for VAT reversal tracking
        'total_amount',        // Total amount of the credit
        'reason',
        'status',              // draft, posted, or void
        'created_by'
    ];

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

    /**
     * Relationship: The customer receiving the credit.
     */
    public function customer() 
    { 
        return $this->belongsTo(Customer::class); 
    }

    /**
     * Relationship: The original invoice being adjusted.
     */
    public function invoice() 
    { 
        return $this->belongsTo(Invoice::class, 'original_invoice_id'); 
    }

    /**
     * Relationship: The line items for this credit memo.
     */
    public function items() 
    { 
        return $this->hasMany(CreditMemoItem::class); 
    }
    
    public function reasonCode(){
        return $this->belongsTo(CreditNoteReason::class, 'credit_note_reason_id');
    }

    /**
     * Relationship: The user who created the document.
     */
    public function creator() 
    { 
        return $this->belongsTo(User::class, 'created_by'); 
    }
}