<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Product extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'restaurant_id',
        'category_id',
        'name',
        'slug',
        'description',
        'image',
        'price',
        'discount',
        'preparation_time',
        'is_available',
        'is_active'
    ];

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

    protected $appends = ['image_url'];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($product) {
            if (empty($product->slug)) {
                $slug = Str::slug($product->name);
                $count = static::where('slug', 'like', $slug . '%')->count();
                $product->slug = $count ? "{$slug}-{$count}" : $slug;
            }
        });
    }

    public function getImageUrlAttribute()
    {
        if ($this->image) {
            return asset('storage/' . $this->image);
        }
        return asset('images/default-product.png');
    }

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

    public function categories()
    {
        return $this->belongsToMany(Category::class, 'product_categories');
    }

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

    public function variations()
    {
        return $this->hasMany(ProductVariation::class);
    }

    public function addons()
    {
        return $this->hasMany(ProductAddon::class);
    }
}
