<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Coupon extends Model {
    protected $fillable = ['code','type','value','min_order','max_discount','usage_limit','used_count','starts_at','expires_at','is_active'];
    protected $casts    = ['value'=>'decimal:2','min_order'=>'decimal:2','is_active'=>'boolean','starts_at'=>'datetime','expires_at'=>'datetime'];
    public function isValid(float $orderTotal): bool {
        if(!$this->is_active) return false;
        if($this->expires_at && $this->expires_at->isPast()) return false;
        if($this->starts_at && $this->starts_at->isFuture()) return false;
        if($this->usage_limit && $this->used_count >= $this->usage_limit) return false;
        if($this->min_order && $orderTotal < $this->min_order) return false;
        return true;
    }
    public function calculateDiscount(float $total): float {
        $discount = $this->type === 'percent' ? ($total * $this->value / 100) : $this->value;
        if($this->max_discount) $discount = min($discount, $this->max_discount);
        return round($discount, 2);
    }
}
