<?php

namespace App\Models;

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

class Product extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'name', 'slug', 'description', 'long_description', 'specifications', 'sku',
        'price', 'discount_price', 'stock',
        'is_active', 'is_featured', 'category_id', 'created_by',
        'price_updated_at', 'meta_title', 'meta_description', 'tags',
    ];

    protected $casts = [
        'price'            => 'integer',
        'discount_price'   => 'integer',
        'is_active'        => 'boolean',
        'is_featured'      => 'boolean',
        'price_updated_at' => 'datetime',
        'tags'             => 'array',
        'specifications'   => 'array',
    ];

    protected $appends = ['final_price'];

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

    public function images()
    {
        return $this->hasMany(ProductImage::class)->orderBy('sort_order');
    }

    public function primaryImage()
    {
        return $this->hasOne(ProductImage::class)->where('is_primary', true);
    }

    public function priceHistories()
    {
        return $this->hasMany(PriceHistory::class)->latest();
    }

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

    public function getFinalPriceAttribute(): float
    {
        return $this->discount_price ?? $this->price;
    }

    public function activeFlashSale()
    {
        return $this->hasOne(FlashSale::class)
            ->where('is_active', true)
            ->where('starts_at', '<=', now())
            ->where('ends_at', '>=', now());
    }

    public function flashSales()
    {
        return $this->hasMany(FlashSale::class);
    }

    public function variants()
    {
        return $this->hasMany(ProductVariant::class);
    }
}
