<?php

namespace App\Models;

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

class ExpenseCategory extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'color',
        'is_active',
        'monthly_budget'
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'monthly_budget' => 'decimal:2'
    ];

    /**
     * Get the expenses for the category.
     */
    public function expenses(): HasMany
    {
        return $this->hasMany(Expense::class);
    }

    /**
     * Scope a query to only include active categories.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Get the category's total expenses amount for current month.
     */
    public function getCurrentMonthExpensesAttribute()
    {
        return $this->expenses()
                   ->whereMonth('date', now()->month)
                   ->whereYear('date', now()->year)
                   ->where('status', 'approved')
                   ->sum('amount');
    }

    /**
     * Get the category's budget utilization percentage.
     */
    public function getBudgetUtilizationAttribute()
    {
        if ($this->monthly_budget == 0) {
            return 0;
        }

        return ($this->current_month_expenses / $this->monthly_budget) * 100;
    }

    /**
     * Get the category's color or a default color.
     */
    public function getDisplayColorAttribute()
    {
        return $this->color ?: $this->getDefaultColor($this->name);
    }

    /**
     * Get default color based on category name.
     */
    private function getDefaultColor($categoryName)
    {
        $colors = [
            'Food & Beverage' => '#1a936f',
            'Maintenance' => '#88d498',
            'Supplies' => '#c6dabf',
            'Utilities' => '#114b5f',
            'Other' => '#f3e9d2'
        ];

        return $colors[$categoryName] ?? '#6c757d';
    }
}