<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Traits\Searchable;

/**
 * @property int $id
 * @property int $category_id
 * @property string $name
 * @property string|null $description
 * @property numeric $price
 * @property string|null $image_url
 * @property int $stock
 * @property bool $is_available
 * @property bool $is_special
 * @property bool $is_best_seller
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read \App\Models\Category $category
 * @property-read float $average_rating
 * @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\OrderItem> $orderItems
 * @property-read int|null $order_items_count
 * @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Review> $reviews
 * @property-read int|null $reviews_count
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu available()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu bestSeller()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu byCategory($categoryId)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu query()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu search($searchTerm, $searchableColumns = [])
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu special()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu whereCategoryId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu whereDescription($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu whereImageUrl($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu whereIsAvailable($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu whereIsBestSeller($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu whereIsSpecial($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu wherePrice($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu whereStock($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Menu whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class Menu extends Model
{
    use HasFactory, Searchable;

    protected $fillable = [
        'category_id',
        'name',
        'description',
        'price',
        'image_url',
        'stock',
        'is_available',
        'is_special',
        'is_best_seller',
    ];
    
    protected $appends = ['image'];

    protected $casts = [
        'price' => 'decimal:2',
        'stock' => 'integer',
        'is_available' => 'boolean',
        'is_special' => 'boolean',
        'is_best_seller' => 'boolean',
    ];

    // Relationships
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function orderItems()
    {
        return $this->hasMany(OrderItem::class);
    }

    public function reviews()
    {
        return $this->hasMany(Review::class);
    }

    // Scopes
    public function scopeAvailable($query)
    {
        return $query->where('is_available', true)->where('stock', '>', 0);
    }

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

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

    public function scopeByCategory($query, $categoryId)
    {
        return $query->where('category_id', $categoryId);
    }

    public function scopeUniqueByName($query)
    {
        return $query->distinct('name');
    }
    
    public function scopeGroupByName($query)
    {
        return $query->groupBy('name');
    }
    
    public function scopeNoDuplicates($query)
    {
        return $query->select('*')
            ->from(function($subQuery) {
                $subQuery->selectRaw('*, ROW_NUMBER() OVER (PARTITION BY name, category_id, price ORDER BY id) as row_num')
                    ->from('menus');
            }, 'numbered_menus')
            ->where('row_num', 1);
    }
 
        // Helper untuk mendapatkan menu unik
    public static function getUniqueMenus()
    {
        return self::where('is_available', true)
            ->select('id', 'name', 'description', 'price', 'image_url', 'category_id', 
                     'is_special', 'is_best_seller', 'stock')
            ->distinct('name')
            ->orderBy('name')
            ->with('category')
            ->get()
            ->unique(function($item) {
                // Unique berdasarkan kombinasi name + category_id
                return $item->name . '_' . $item->category_id;
            });
    }
    
// Helpers
    public function reduceStock($quantity): bool
    {
        if ($this->stock < $quantity) {
            return false;
        }
        
        $this->stock -= $quantity;
        if ($this->stock <= 0) {
            $this->is_available = false;
        }
        
        return $this->save();
    }

    public function addStock($quantity): bool
    {
        $this->stock += $quantity;
        if ($this->stock > 0 && !$this->is_available) {
            $this->is_available = true;
        }
        
        return $this->save();
    }

    public function getAverageRatingAttribute(): float
    {
        return $this->reviews()->avg('rating') ?: 0;
    }
    
public function getRatingCountAttribute()
{
    return $this->reviews()->count();
}
    
    /**
     * Get image with fallback to placeholder
     */
    public function getImageAttribute(): string
    {
        $imageUrl = $this->attributes['image_url'] ?? '';
        
        // If image_url is empty or is example.com placeholder
        if (empty($imageUrl) || str_contains($imageUrl, 'example.com')) {
            // Generate a unique placeholder based on menu name
            $seed = crc32($this->name ?? 'food');
            return "https://ui-avatars.com/api/?name=" . urlencode($this->name ?? 'Food') . 
                   "&size=400&background=" . dechex($seed % 16777215) . 
                   "&color=ffffff&font-size=0.4";
        }
        
        return $imageUrl;
    }
}