<?php

namespace App\Models;

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

class LedgerEntry extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'account_head_id',
        'ledger_transaction_id',
        'entry_date',
        'entry_type',
        'debit_amount',
        'credit_amount',
        'balance',
        'narration',
        'reference_number',
        'created_by',
    ];

    protected $casts = [
        'entry_date' => 'date',
        'debit_amount' => 'decimal:2',
        'credit_amount' => 'decimal:2',
        'balance' => 'decimal:2',
    ];

    // Relationships
    public function school()
    {
        return $this->belongsTo(School::class);
    }

    public function accountHead()
    {
        return $this->belongsTo(AccountHead::class, 'account_head_id');
    }

    public function ledgerTransaction()
    {
        return $this->belongsTo(LedgerTransaction::class, 'ledger_transaction_id');
    }

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    // Scopes
    public function scopeForAccountHead($query, $accountHeadId)
    {
        return $query->where('account_head_id', $accountHeadId);
    }

    public function scopeDebit($query)
    {
        return $query->where('entry_type', 'debit');
    }

    public function scopeCredit($query)
    {
        return $query->where('entry_type', 'credit');
    }

    public function scopeForDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('entry_date', [$startDate, $endDate]);
    }
}
