<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;

class FoodMenuItem extends Model
{
    protected $fillable = [
        'food_cart_id',
        'title',
        'slug',
        'description',
        'price',
        'image',
        'search_tags',
        'is_available',
        'created_by',
    ];

    protected $casts = [
        'search_tags' => 'array',
        'price' => 'decimal:2',
        'is_available' => 'boolean',
    ];

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

        static::creating(function (self $item) {
            if (! $item->slug) {
                $item->slug = static::generateUniqueSlug((string) $item->title);
            }
        });

        static::updating(function (self $item) {
            if ($item->isDirty('title') && ! $item->isDirty('slug')) {
                $item->slug = static::generateUniqueSlug((string) $item->title, (int) $item->id);
            }
        });
    }

    protected static function generateUniqueSlug(string $title, ?int $ignoreId = null): string
    {
        $base = Str::slug($title);
        if ($base === '') {
            $base = 'menu-item';
        }

        $slug = $base;
        $counter = 1;

        while (static::query()
            ->when($ignoreId, fn(Builder $query) => $query->where('id', '!=', $ignoreId))
            ->where('slug', $slug)
            ->exists()
        ) {
            $slug = $base . '-' . $counter;
            $counter++;
        }

        return $slug;
    }

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

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function scopeAvailable(Builder $query): Builder
    {
        return $query->where('is_available', true);
    }
}
