<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'category_id', 'name', 'slug', 'description', 'short_description',
        'price', 'sale_price', 'sku', 'stock', 'images',
        'sizes', 'colors', 'brand', 'badge',
        'is_active', 'is_featured', 'is_flash_deal',
        'flash_deal_ends_at', 'weight', 'meta_title', 'meta_description',
    ];

    protected $casts = [
        'images'          => 'array',
        'sizes'           => 'array',
        'colors'          => 'array',
        'price'           => 'decimal:2',
        'sale_price'      => 'decimal:2',
        'is_active'       => 'boolean',
        'is_featured'     => 'boolean',
        'is_flash_deal'   => 'boolean',
        'flash_deal_ends_at' => 'datetime',
    ];

    // ── Relationships ──────────────────────────────────────────────────

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

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

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

    public function cartItems()
    {
        return $this->hasMany(CartItem::class);
    }

    public function wishlists()
    {
        return $this->hasMany(Wishlist::class);
    }

    // ── Scopes ─────────────────────────────────────────────────────────

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

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

    public function scopeFlashDeals($query)
    {
        return $query->where('is_flash_deal', true)
                     ->where('flash_deal_ends_at', '>', now());
    }

    public function scopeInStock($query)
    {
        return $query->where('stock', '>', 0);
    }

    // ── Accessors ──────────────────────────────────────────────────────

    /**
     * Effective (selling) price is always `price`.
     * `sale_price` = original/MRP before discount.
     * Convention: price=850 (sell), sale_price=1200 (original) → 29% OFF
     */
    public function getEffectivePriceAttribute(): float
    {
        return (float) $this->price;
    }

    public function getDiscountPercentAttribute(): int
    {
        if (!$this->sale_price || $this->sale_price <= $this->price) return 0;
        return (int) round((($this->sale_price - $this->price) / $this->sale_price) * 100);
    }

    public function getAverageRatingAttribute(): float
    {
        return round($this->reviews()->avg('rating') ?? 0, 1);
    }

    public function getIsInStockAttribute(): bool
    {
        return $this->stock > 0;
    }
}
