<?php

namespace App\Models;

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

class Expense extends Model
{
    protected $fillable = [
        'company_id',
        'supplier_id',
        'bank_account_id', // <--- ADD THIS LINE HERE
        'payment_date',
        'payment_method',
        'reference_no',
        'total_amount',
        'memo',
        'status',
        'reversed_at',
        'reversal_reason',
        'created_by'
    ];

    protected $casts = [
        'payment_date' => 'date',
        'reversed_at' => 'datetime',
        'total_amount' => 'decimal:2',
    ];

    /**
     * Get the bank or cash account that paid for this expense.
     */
    public function bankAccount(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'bank_account_id');
    }

    /**
     * Get the line items associated with this expense.
     */
    public function items(): HasMany
    {
        return $this->hasMany(ExpenseItem::class);
    }

    /**
     * Get the supplier associated with this expense.
     */
    public function supplier(): BelongsTo
    {
        return $this->belongsTo(Supplier::class);
    }

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

    public function isDraft(): bool
    {
        return $this->status === 'draft';
    }

    public function isReversed(): bool
    {
        return !is_null($this->reversed_at);
    }
}