<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Product extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'brand',
        'description',
        'price',
        'stock',
        'image',
        'category_id',
        'sku',
        'is_active',
        'meta_title',
        'meta_description',
        'meta_keywords',
    ];

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

    protected $appends = [
        'image_url',
        'discounted_price',
        'is_on_sale',
        'best_deal_info'
    ];

    /**
     * Get the category that owns the product.
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    /**
     * Get the deals associated with the product.
     */
    public function deals(): BelongsToMany
    {
        return $this->belongsToMany(Deal::class, 'deal_product')
                    ->withTimestamps();
    }

    /**
     * Get active deals for this product.
     */
    public function activeDeals()
    {
        return $this->deals()
            ->where('is_active', true)
            ->where('start_date', '<=', now())
            ->where('end_date', '>=', now())
            ->orderBy('sort_order', 'asc');
    }

    /**
     * Get the URL to the product image.
     */
    public function getImageUrlAttribute(): ?string
    {
        return $this->image ? asset($this->image) : null;
    }

    /**
     * Get the best deal for this product.
     */
    public function getBestDealInfoAttribute()
    {
        $bestPrice = $this->price;
        $bestDeal = null;

        foreach ($this->activeDeals()->get() as $deal) {
            $discountedPrice = $deal->calculateDiscount($this->price);
            if ($discountedPrice < $bestPrice) {
                $bestPrice = $discountedPrice;
                $bestDeal = $deal;
            }
        }

        return [
            'deal' => $bestDeal,
            'price' => $bestPrice,
            'saving' => $this->price - $bestPrice,
            'has_deal' => !is_null($bestDeal)
        ];
    }

    /**
     * Get discounted price.
     */
    public function getDiscountedPriceAttribute()
    {
        return $this->best_deal_info['price'];
    }

    /**
     * Check if product is on sale.
     */
    public function getIsOnSaleAttribute()
    {
        return $this->best_deal_info['has_deal'];
    }

    /**
     * Scope a query to only include active products.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope a query to only include in-stock products.
     */
    public function scopeInStock($query)
    {
        return $query->where('stock', '>', 0);
    }

    /**
     * Scope a query to only include products with active deals.
     */
    public function scopeWithDeals($query)
    {
        return $query->whereHas('deals', function ($q) {
            $q->where('is_active', true)
              ->where('start_date', '<=', now())
              ->where('end_date', '>=', now());
        });
    }
}