<?php

namespace App\Models;

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

class Expense extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'expense_head_id',
        'account_head_id',
        'expense_date',
        'amount',
        'payment_method',
        'reference_number',
        'invoice_number',
        'invoice_date',
        'vendor_name',
        'description',
        'attachment',
        'status',
        'approved_by',
        'approval_date',
    ];

    protected $casts = [
        'expense_date' => 'date',
        'invoice_date' => 'date',
        'approval_date' => 'datetime',
        'amount' => 'decimal:2',
    ];

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

    public function expenseHead()
    {
        return $this->belongsTo(ExpenseHead::class, 'expense_head_id');
    }

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

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

    // Scopes
    public function scopeForExpenseHead($query, $expenseHeadId)
    {
        return $query->where('expense_head_id', $expenseHeadId);
    }

    public function scopeApproved($query)
    {
        return $query->where('status', 'approved');
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

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

    public function scopeByPaymentMethod($query, $method)
    {
        return $query->where('payment_method', $method);
    }
}
