<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class FlashSale extends Model
{
    protected $fillable = [
        'title', 'product_id', 'sale_price',
        'sale_quantity', 'sold_quantity',
        'starts_at', 'ends_at', 'is_active',
    ];

    protected $casts = [
        'sale_price'    => 'integer',
        'is_active'     => 'boolean',
        'starts_at'     => 'datetime',
        'ends_at'       => 'datetime',
    ];

    protected $appends = ['is_running', 'remaining_seconds', 'remaining_quantity'];

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

    public function getIsRunningAttribute(): bool
    {
        $now = now();
        return $this->is_active
            && $now->gte($this->starts_at)
            && $now->lte($this->ends_at)
            && ($this->sale_quantity === null || $this->sold_quantity < $this->sale_quantity);
    }

    public function getRemainingSecondsAttribute(): int
    {
        if (!$this->is_running) return 0;
        return max(0, now()->diffInSeconds($this->ends_at, false));
    }

    public function getRemainingQuantityAttribute(): ?int
    {
        if ($this->sale_quantity === null) return null;
        return max(0, $this->sale_quantity - $this->sold_quantity);
    }
}
