<?php

namespace App\Models;

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

class Coupon extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'type',
        'value',
        'max_discount_amount',
        'min_order_amount',
        'usage_limit',
        'usage_count',
        'is_active',
        'expires_at',
    ];

    protected $casts = [
        'value' => 'float',
        'max_discount_amount' => 'float',
        'min_order_amount' => 'float',
        'usage_limit' => 'integer',
        'usage_count' => 'integer',
        'is_active' => 'boolean',
        'expires_at' => 'datetime',
    ];

    public function isExpired(): bool
    {
        return $this->expires_at && $this->expires_at->isPast();
    }

    public function isUsageLimitReached(): bool
    {
        return $this->usage_limit && $this->usage_count >= $this->usage_limit;
    }

    public function isValid(float $subtotal = 0): array
    {
        if (!$this->is_active) {
            return ['valid' => false, 'message' => 'This coupon code is currently disabled.'];
        }

        if ($this->isExpired()) {
            return ['valid' => false, 'message' => 'This coupon code has expired.'];
        }

        if ($this->isUsageLimitReached()) {
            return ['valid' => false, 'message' => 'This coupon has reached its maximum global usage limit.'];
        }

        if ($this->min_order_amount && $subtotal < $this->min_order_amount) {
            $diff = $this->min_order_amount - $subtotal;
            return [
                'valid' => false,
                'message' => "Order minimum of ₹" . number_format($this->min_order_amount) . " required. Add ₹" . number_format($diff) . " more to unlock!"
            ];
        }

        return ['valid' => true, 'message' => 'Coupon code is valid!'];
    }

    public function calculateDiscount(float $subtotal): float
    {
        if ($this->type === 'fixed') {
            return min($this->value, $subtotal);
        }

        // Percentage discount
        $discount = ($subtotal * $this->value) / 100;
        if ($this->max_discount_amount && $this->max_discount_amount > 0) {
            $discount = min($discount, $this->max_discount_amount);
        }

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