<?php

namespace App\Models;

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

class CartItem extends Model
{
    use HasFactory;

    protected $fillable = ['cart_id', 'product_id', 'variant_id', 'qty', 'is_flash_sale'];

    protected $casts = [
        'is_flash_sale' => 'boolean',
    ];

    protected $appends = ['price'];

    public function getPriceAttribute()
    {
        if ($this->is_flash_sale) {
            $now = now();
            $flashSaleProduct = $this->product->flashSaleProducts()
                ->where(function($q) {
                    if ($this->variant_id) {
                        $q->where('variant_id', $this->variant_id);
                    } else {
                        $q->whereNull('variant_id');
                    }
                })
                ->whereHas('flashSale', function ($query) use ($now) {
                    $query->where('is_active', true)
                        ->where('start_time', '<=', $now)
                        ->where('end_time', '>=', $now);
                })
                ->first();

            if ($flashSaleProduct) {
                return (float) $flashSaleProduct->flash_sale_price;
            }
        }

        if ($this->variant_id && $this->variant) {
            $variantPrice = $this->variant->price ?? $this->product->price;
            if ($this->product->discount_percent > 0) {
                return (float) ($variantPrice - ($variantPrice * $this->product->discount_percent / 100));
            }
            return (float) $variantPrice;
        }

        return (float) $this->product->final_price;
    }

    public function cart()
    {
        return $this->belongsTo(Cart::class);
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function variant()
    {
        return $this->belongsTo(ProductVariant::class, 'variant_id');
    }
}
