<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Coupon extends Model
{
    protected $fillable = ['code', 'stripe_coupon_id', 'name', 'type', 'value', 'currency', 'max_uses', 'times_used', 'applicable_plans', 'expires_at', 'is_active'];

    protected function casts(): array
    {
        return [
            'value' => 'decimal:2',
            'applicable_plans' => 'array',
            'expires_at' => 'datetime',
            'is_active' => 'boolean',
            'max_uses' => 'integer',
            'times_used' => 'integer',
        ];
    }

    public function isValid(): bool
    {
        if (!$this->is_active) return false;
        if ($this->expires_at && $this->expires_at->isPast()) return false;
        if ($this->max_uses !== null && $this->times_used >= $this->max_uses) return false;
        return true;
    }

    public function isApplicableToPlan(int $planId): bool
    {
        if (empty($this->applicable_plans)) return true; // null = all plans
        return in_array($planId, $this->applicable_plans);
    }

    /**
     * Normalized "kind" of this coupon — 'percent' or 'fixed' — regardless
     * of which historical schema convention created the row.
     *
     * The table accumulated two styles over time:
     *   - Legacy MailTrixy:  type='percent' | 'fixed',  amount in `value`
     *   - Stripe-style sync: type='percent_off' | 'amount_off',  amount in
     *                        dedicated `percent_off` / `amount_off` columns
     *
     * Mixing them broke calculateDiscount(): a Stripe-style row with
     * type='amount_off' fell through the legacy `=== 'percent'` check
     * AND had value=NULL, so min(null, $price) returned null → 500.
     */
    public function discountKind(): string
    {
        return in_array($this->type, ['percent', 'percent_off'], true) ? 'percent' : 'fixed';
    }

    /**
     * Single source of truth for "how much off". Reads `value` first (the
     * legacy column the admin UI writes to), and falls back to the
     * Stripe-style `percent_off` / `amount_off` columns when value is
     * null. Always returns a float — never null — so callers can math
     * with it directly.
     */
    public function resolvedValue(): float
    {
        // Legacy `value` column wins when set (admin UI populates this).
        if ($this->value !== null && $this->value !== '') {
            return (float) $this->value;
        }
        // Fall back to whichever Stripe-style column matches the type.
        $col = $this->discountKind() === 'percent' ? $this->percent_off : $this->amount_off;
        return (float) ($col ?? 0);
    }

    public function calculateDiscount(float $price): float
    {
        $value = $this->resolvedValue();
        if ($this->discountKind() === 'percent') {
            return round($price * ($value / 100), 2);
        }
        // Fixed amount — capped at the price so the discount never makes
        // the total negative.
        return (float) min($value, $price);
    }

    public function getDiscountedPrice(float $price): float
    {
        return max(0.0, $price - $this->calculateDiscount($price));
    }

    public function incrementUsage(): void
    {
        $this->increment('times_used');
    }
}
