<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Coupon extends Model
{
    protected $fillable = [
        'code', 'title', 'type', 'value',
        'min_order_amount', 'max_discount',
        'usage_limit', 'used_count', 'per_user_limit',
        'is_active', 'starts_at', 'expires_at',
    ];

    protected $casts = [
        'value'            => 'integer',
        'min_order_amount' => 'integer',
        'max_discount'     => 'integer',
        'is_active'        => 'boolean',
        'starts_at'        => 'datetime',
        'expires_at'       => 'datetime',
    ];

    public function isValid(): bool
    {
        if (!$this->is_active) return false;
        $now = now();
        if ($this->starts_at && $now->lt($this->starts_at)) return false;
        if ($this->expires_at && $now->gt($this->expires_at)) return false;
        if ($this->usage_limit && $this->used_count >= $this->usage_limit) return false;
        return true;
    }

    public function calculateDiscount(float $orderTotal): float
    {
        if ($orderTotal < $this->min_order_amount) return 0;

        $discount = $this->type === 'percentage'
            ? $orderTotal * ($this->value / 100)
            : $this->value;

        if ($this->max_discount) {
            $discount = min($discount, $this->max_discount);
        }

        return min($discount, $orderTotal);
    }
}
