<?php
// app/Models/AccountBalance.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AccountBalance extends Model
{
    use HasFactory, \App\Traits\HotelScopeTrait;

    protected $table = 'account_balances';

    protected $fillable = [
        'hotel_id',
        'account_id',
        'fiscal_year',
        'period',
        'period_date',
        'balance',
        'debit_sum',
        'credit_sum'
    ];

    protected $casts = [
        'balance' => 'decimal:2',
        'debit_sum' => 'decimal:2',
        'credit_sum' => 'decimal:2',
        'fiscal_year' => 'integer',
        'period_date' => 'date',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    const PERIOD_MONTHLY = 'monthly';
    const PERIOD_QUARTERLY = 'quarterly';
    const PERIOD_YEARLY = 'yearly';
    const PERIOD_CUMULATIVE = 'cumulative';

    /**
     * Get the hotel that owns this balance
     */
    public function hotel(): BelongsTo
    {
        return $this->belongsTo(Hotel::class);
    }

    /**
     * Get the account for this balance
     */
    public function account(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'account_id');
    }

    /**
     * Scope to filter by hotel
     */
    public function scopeForHotel($query, $hotelId)
    {
        return $query->where('hotel_id', $hotelId);
    }

    /**
     * Scope to filter by account
     */
    public function scopeForAccount($query, $accountId)
    {
        return $query->where('account_id', $accountId);
    }

    /**
     * Scope to filter by fiscal year
     */
    public function scopeForYear($query, $year)
    {
        return $query->where('fiscal_year', $year);
    }

    /**
     * Scope to filter by period
     */
    public function scopeByPeriod($query, $period)
    {
        return $query->where('period', $period);
    }

    /**
     * Scope to filter by date range
     */
    public function scopeDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('period_date', [$startDate, $endDate]);
    }

    /**
     * Get the balance formatted with currency
     */
    public function getFormattedBalanceAttribute(): string
    {
        return 'UGX ' . number_format($this->balance, 2);
    }

    /**
     * Get the period name
     */
    public function getPeriodNameAttribute(): string
    {
        return ucfirst($this->period);
    }

    /**
     * Get the month name (if period is monthly)
     */
    public function getMonthNameAttribute(): ?string
    {
        if ($this->period === self::PERIOD_MONTHLY) {
            return $this->period_date->format('F Y');
        }
        
        return null;
    }
}