<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Cache;

class Menu extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'location',
        'description',
        'is_active',
        'sort_order',
    ];

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

    // Location constants
    const LOCATION_TOP = 'top';
    const LOCATION_FOOTER = 'footer';

    public static function getLocations(): array
    {
        return [
            self::LOCATION_TOP => 'Üst Menü',
            self::LOCATION_FOOTER => 'Footer Menü',
        ];
    }

    public function items(): HasMany
    {
        return $this->hasMany(MenuItem::class)->whereNull('parent_id')->orderBy('sort_order');
    }

    public function allItems(): HasMany
    {
        return $this->hasMany(MenuItem::class)->orderBy('sort_order');
    }

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

    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order');
    }

    /**
     * Get menu by location (cached)
     */
    public static function getByLocation(string $location): ?self
    {
        return Cache::remember("menu_{$location}", 3600, function () use ($location) {
            return self::where('location', $location)
                ->where('is_active', true)
                ->with(['items.children'])
                ->first();
        });
    }

    /**
     * Clear menu cache
     */
    public static function clearCache(): void
    {
        Cache::forget('menu_top');
        Cache::forget('menu_footer');
        Cache::flush();
    }
}
