<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Coupon extends Model
{
    use HasFactory;

    protected $fillable = [
        'vendor_id', 'code', 'type', 'value', 'min_order_amount', 'max_discount',
        'usage_limit', 'used_count', 'per_user_limit', 'starts_at', 'expires_at', 'is_active',
    ];

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

    public function vendor(): BelongsTo { return $this->belongsTo(Vendor::class); }
    public function usages(): HasMany { return $this->hasMany(CouponUsage::class); }

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

    public function calculateDiscount(float $orderTotal): float
    {
        if ($this->type === 'fixed') {
            $discount = $this->value;
        } else {
            $discount = ($orderTotal * $this->value) / 100;
        }

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

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