<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class ExpenseCategory extends Model
{
    use HasFactory;

    // =========================================================================
    // Model Configuration
    // =========================================================================

    protected $fillable = [
        'uuid',
        'association_id',
        'parent_id',
        'name',
        'slug',
        'description',
        'is_active',
        'display_order',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'display_order' => 'integer',
    ];

    // =========================================================================
    // Boot
    // =========================================================================

    protected static function boot()
    {
        parent::boot();

        static::creating(function (ExpenseCategory $category) {
            if (!$category->uuid) {
                $category->uuid = (string) Str::uuid();
            }
            if (!$category->slug && $category->name) {
                $category->slug = Str::slug($category->name);
            }
        });
    }

    // =========================================================================
    // Relationships
    // =========================================================================

    public function association()
    {
        return $this->belongsTo(Association::class);
    }

    public function parent()
    {
        return $this->belongsTo(ExpenseCategory::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(ExpenseCategory::class, 'parent_id')->orderBy('display_order');
    }

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

    // =========================================================================
    // Accessors
    // =========================================================================

    /**
     * Returns "Parent > Child" format for display.
     */
    public function getFullNameAttribute(): string
    {
        if ($this->parent) {
            return $this->parent->name . ' > ' . $this->name;
        }
        return $this->name;
    }

    // =========================================================================
    // Scopes
    // =========================================================================

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

    public function scopeRoots($query)
    {
        return $query->whereNull('parent_id');
    }

    public function scopeForAssociation($query, int $associationId)
    {
        return $query->where('association_id', $associationId);
    }

    /**
     * Get a flat list suitable for select dropdowns: "Parent > Child".
     */
    public static function getGroupedOptions(int $associationId): array
    {
        $categories = static::where('association_id', $associationId)
            ->where('is_active', true)
            ->whereNull('parent_id')
            ->with(['children' => function ($q) {
                $q->where('is_active', true)->orderBy('display_order');
            }])
            ->orderBy('display_order')
            ->get();

        $options = [];

        foreach ($categories as $parent) {
            $options[$parent->id] = $parent->name;
            foreach ($parent->children as $child) {
                $options[$child->id] = $parent->name . ' > ' . $child->name;
            }
        }

        return $options;
    }
}
