<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class CashbookEntry extends Model
{
    protected $fillable = [
        'cashbook_id',
        'date',
        'module',
        'account_id',
        'account_type',
        'reference_id',
        'reference_type',
        'description',
        'tr_code',
        'currency_id',
        'project_id',
        'amount',
        'dr_amount',
        'cr_amount'
    ];

    /**
     * Relationship to currency
     */
    public function currency(): BelongsTo
    {
        return $this->belongsTo(Currency::class);
    }

    /**
     * Relationship to project
     */
    public function project(): BelongsTo
    {
        return $this->belongsTo(Project::class);
    }

    /**
     * Relationship to cashbook
     */
    public function cashbook(): BelongsTo
    {
        return $this->belongsTo(Cashbook::class);
    }

    /**
     * Polymorphic relationship to account (GL, SubAccount, Customer, Supplier)
     */
    public function account(): MorphTo
    {
        return $this->morphTo();
    }

    /**
     * Polymorphic relationship to reference (invoice or supplier_invoice)
     */
    public function reference(): MorphTo
    {
        return $this->morphTo();
    }

    /**
     * Customer relationship for AR module
     */
    public function customer(): BelongsTo
    {
        return $this->belongsTo(CustomerAccount::class, 'account_id');
    }

    /**
     * Supplier relationship for AP module
     */
    public function supplier(): BelongsTo
    {
        return $this->belongsTo(SupplierAccount::class, 'account_id');
    }

    /**
     * MainAccount relationship for GL module (hierarchical accounts)
     */
    public function mainAccount(): BelongsTo
    {
        return $this->belongsTo(MainAccount::class, 'account_id');
    }

    /**
     * Relationship to AR invoice
     */
    public function invoice(): BelongsTo
    {
        return $this->belongsTo(DocumentHeader::class, 'reference_id')
                    ->where('type', 'invoice');
    }

    /**
     * Relationship to AP supplier invoice
     */
    public function supplierInvoice(): BelongsTo
    {
        return $this->belongsTo(SupplierDocumentHeader::class, 'reference_id')
                    ->where('type', 'supplier_invoice');
    }
}
