<?php

namespace App\Models;

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

class CreditMemoItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'credit_memo_id',
        'product_id',
        'income_account_id',   // Captured from Product for Revenue reversal
        'expense_account_id',  // Captured from Product for COGS reversal
        'asset_account_id',    // Captured from Product for Inventory reversal
        'description',
        'qty',
        'unit_price',
        'subtotal',            // ADD THIS: Missing from your current model
        'tax_rate',
        'tax_amount',
        'total_amount'
    ];

    protected $casts = [
        'qty'          => 'decimal:2',
        'unit_price'   => 'decimal:2',
        'subtotal'     => 'decimal:2', // ADD THIS: For numeric precision
        'tax_rate'     => 'decimal:2',
        'tax_amount'   => 'decimal:2',
        'total_amount' => 'decimal:2',
    ];

    /**
     * Relationship: The header credit memo document.
     */
    public function creditMemo()
    {
        return $this->belongsTo(CreditMemo::class);
    }

    /**
     * Relationship: The product being returned or credited.
     */
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * Relationship: The income account used for revenue reversal.
     */
    public function incomeAccount()
    {
        return $this->belongsTo(Account::class, 'income_account_id');
    }
}