<?php

namespace App\Models;

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

class LiveSaleProduct extends Model
{
    protected $fillable = [
        'live_sale_id',
        'product_id',
        'custom_price',
        'price_min',
        'price_max',
    ];

    protected $casts = [
        'custom_price' => 'decimal:2',
        'price_min' => 'decimal:2',
        'price_max' => 'decimal:2',
    ];

    /**
     * Get the parent live sale.
     */
    public function liveSale(): BelongsTo
    {
        return $this->belongsTo(LiveSale::class);
    }

    /**
     * Get the related product.
     */
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * Determine if this entry uses a price range instead of a single price.
     */
    public function getIsRangeAttribute(): bool
    {
        return is_null($this->custom_price) && !is_null($this->price_min);
    }

    /**
     * The actual price used when adding the product to the cart.
     * Single custom price wins; otherwise the range minimum (best deal).
     */
    public function getEffectivePriceAttribute(): float
    {
        if (!is_null($this->custom_price)) {
            return (float) $this->custom_price;
        }

        if (!is_null($this->price_min)) {
            return (float) $this->price_min;
        }

        return (float) ($this->product->price ?? 0);
    }

    /**
     * Human readable price for display (single or range format).
     */
    public function getDisplayPriceAttribute(): string
    {
        if (!is_null($this->custom_price)) {
            return '৳' . number_format((float) $this->custom_price, 0);
        }

        if (!is_null($this->price_min) && !is_null($this->price_max)) {
            return '৳' . number_format((float) $this->price_min, 0)
                . ' - ৳' . number_format((float) $this->price_max, 0);
        }

        return '৳' . number_format((float) ($this->product->price ?? 0), 0);
    }
}
