<?php

namespace App\Models;

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

class FinanTrn extends Model
{
    use HasFactory;

    protected $table = 'finan_trns';
    protected $primaryKey = 'Ft_Id';
    public $timestamps = false;

    protected $fillable = [
        'Org_Id',
        'Vou_Ty',
        'Vou_Id',
        'Vou_Dt',
        'Lg_Id',
        'Vou_Sr',
        'Vou_Ln',
        'V_Mode',
        'Vou_Rf',
        'SL_Id',
        'SL_Amt',
        'Cr_Amt',
        'Dr_Amt',
        'Ref_Id',
        'Emp_id',
        'chq_no',
        'chq_dt',
        'clr_dt',
        'rmk1',
        'rmk2',
        'rmk3',
        'rmk4',
        'rmk5',
        'sms_stus',
        'email_stus'
    ];

    protected $casts = [
        'Vou_Dt' => 'datetime',
        'chq_dt' => 'datetime',
        'clr_dt' => 'datetime',
        'Cr_Amt' => 'decimal:2',
        'Dr_Amt' => 'decimal:2',
        'SL_Amt' => 'decimal:4',
    ];

    public function getVouDtAttribute($value)
    {
        return $value
            ? Carbon::parse($value)->timezone('Asia/Kolkata')->format('d/m/Y')
            : null;
    }

    // Relationships

    public function organisation()
    {
        return $this->belongsTo(OrgMaster::class, 'Org_Id', 'Org_Id');
    }

    public function ledger()
    {
        return $this->belongsTo(LedgerMaster::class, 'Lg_Id', 'Lg_Id');
    }

    public function refLedger()
    {
        return $this->belongsTo(LedgerMaster::class, 'Ref_Id', 'Lg_Id');
    }

    // Fix: Use correct table name 'subledg_master'
    public function subLedger()
    {
        return $this->belongsTo(SubLedgerMaster::class, 'SL_Id', 'SL_Id');
    }

    // Relationship with invoice_charge_master
    public function invoiceCharge()
    {
        return $this->belongsTo(InvoiceChargeMaster::class, 'Lg_Id', 'Lg_Id');
    }
}
