<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'slug',
        'description',
        'short_description',
        'sku',
        'category_id',
        'base_price',
        'discount_price',
        'discount_start',
        'discount_end',
        'tax_rate',
        'is_active',
        'is_featured',
        'sort_order',
        'meta',
        'video_path',
    ];

    protected function casts(): array
    {
        return [
            'base_price' => 'decimal:2',
            'discount_price' => 'decimal:2',
            'discount_start' => 'date',
            'discount_end' => 'date',
            'tax_rate' => 'decimal:2',
            'is_active' => 'boolean',
            'is_featured' => 'boolean',
            'meta' => 'array',
        ];
    }

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

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

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

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

    public function activeVariants(): HasMany
    {
        return $this->variants()->where('is_active', true);
    }

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

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

    public function productRatings(): HasMany
    {
        return $this->hasMany(ProductRating::class);
    }

    public function getAverageRatingAttribute(): ?float
    {
        if (array_key_exists('product_ratings_avg_rating', $this->attributes)) {
            $v = $this->attributes['product_ratings_avg_rating'];
            return $v !== null ? (float) $v : null;
        }
        $avg = $this->productRatings()->avg('rating');
        return $avg !== null ? (float) $avg : null;
    }

    public function getRatingsCountAttribute(): int
    {
        if (array_key_exists('product_ratings_count', $this->attributes)) {
            return (int) $this->attributes['product_ratings_count'];
        }
        return $this->productRatings()->count();
    }

    public function getMinPriceAttribute(): float
    {
        $minVariant = $this->activeVariants()->min('price');
        return $minVariant ?? $this->base_price;
    }

    public function getMaxPriceAttribute(): float
    {
        $maxVariant = $this->activeVariants()->max('price');
        return $maxVariant ?? $this->base_price;
    }

    public function getTotalStockAttribute(): int
    {
        return $this->activeVariants()->sum('stock_quantity');
    }

    public function getCurrentPriceAttribute(): float
    {
        $now = now();
        if ($this->discount_price 
            && $this->discount_start 
            && $this->discount_end
            && $now->between($this->discount_start, $this->discount_end)) {
            return $this->discount_price;
        }
        return $this->base_price;
    }

    public function hasActiveDiscount(): bool
    {
        $now = now();
        return $this->discount_price 
            && $this->discount_start 
            && $this->discount_end
            && $now->between($this->discount_start, $this->discount_end);
    }
}
