<?php

namespace App\Models;

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

class ExpenseCategory extends Model
{
    use HasFactory;

    protected $fillable = [
        'restaurant_id',
        'name',
        'description',
        'budget_limit',
        'is_active',
    ];

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

    public function restaurant(): BelongsTo
    {
        return $this->belongsTo(Restaurant::class);
    }

    public function expenses(): HasMany
    {
        return $this->hasMany(Expense::class, 'category_id');
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeForRestaurant($query, $restaurantId)
    {
        return $query->where('restaurant_id', $restaurantId);
    }

    public function getTotalSpentAttribute()
    {
        return $this->expenses()
            ->whereIn('status', ['approved', 'paid'])
            ->sum('amount');
    }

    public function getRemainingBudgetAttribute()
    {
        if (!$this->budget_limit) {
            return null;
        }
        
        return $this->budget_limit - $this->total_spent;
    }

    public function getBudgetUtilizationAttribute()
    {
        if (!$this->budget_limit || $this->budget_limit == 0) {
            return 0;
        }
        
        return ($this->total_spent / $this->budget_limit) * 100;
    }

    public function isOverBudget(): bool
    {
        if (!$this->budget_limit) {
            return false;
        }
        
        return $this->total_spent > $this->budget_limit;
    }
}