<?php

namespace App\Models;

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

class LiveSale extends Model
{
    protected $fillable = [
        'date',
        'title',
        'sub_title',
        'is_active',
    ];

    protected $casts = [
        'date' => 'date',
        'is_active' => 'boolean',
    ];

    /**
     * Get the product entries for this live sale.
     */
    public function liveSaleProducts(): HasMany
    {
        return $this->hasMany(LiveSaleProduct::class);
    }

    /**
     * Get the products attached to this live sale (with pivot pricing).
     */
    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class, 'live_sale_products')
            ->withPivot(['custom_price', 'price_min', 'price_max'])
            ->withTimestamps();
    }

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

    /**
     * Get the active live sale for the current date (with eager loaded products).
     */
    public static function getActiveForToday()
    {
        return static::active()
            ->where('date', now()->toDateString())
            ->with(['liveSaleProducts.product.category'])
            ->first();
    }
}
