<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'category_id',
        'sub_category_id',
        'name',
        'seo_title',
        'seo_description',
        'seo_keywords',
        'slug',
        'description',
        'price',
        'discount_price',
        'stock',
        'unit',
        'image',
        'images',
        'is_active',
        'is_featured',
        'is_special_offer',
        'is_premium',
        'is_flash_sale',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'is_featured' => 'boolean',
        'is_special_offer' => 'boolean',
        'is_premium' => 'boolean',
        'is_flash_sale' => 'boolean',
        'images' => 'array',
        'price' => 'float',
        'discount_price' => 'float',
    ];

    protected $appends = ['image_url'];

    public function getImageUrlAttribute()
    {
        if (empty($this->image)) {
            return null;
        }

        if (\Illuminate\Support\Str::startsWith($this->image, ['http://', 'https://'])) {
            return $this->image;
        }

        return route('public.media', ['path' => $this->image]);
    }

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

    public function subCategory()
    {
        return $this->belongsTo(SubCategory::class);
    }

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