<?php
/**
 * Tom's Java Jive - Coupon Validation API
 */

header('Content-Type: application/json');

require_once __DIR__ . '/../includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['error' => 'Method not allowed'], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
$code = strtoupper(trim($input['code'] ?? ''));
$subtotal = floatval($input['subtotal'] ?? 0);

if (empty($code)) {
    jsonResponse(['error' => 'Coupon code required'], 400);
}

$coupon = db()->fetch(
    "SELECT * FROM coupons WHERE code = :code AND is_active = 1",
    ['code' => $code]
);

if (!$coupon) {
    jsonResponse(['error' => 'Invalid coupon code']);
}

// Check if expired
if ($coupon['expires_at'] && strtotime($coupon['expires_at']) < time()) {
    jsonResponse(['error' => 'Coupon has expired']);
}

// Check if not started yet
if ($coupon['starts_at'] && strtotime($coupon['starts_at']) > time()) {
    jsonResponse(['error' => 'Coupon is not yet active']);
}

// Check usage limit
if ($coupon['max_uses'] && $coupon['times_used'] >= $coupon['max_uses']) {
    jsonResponse(['error' => 'Coupon usage limit reached']);
}

// Check minimum order
if ($coupon['min_order_amount'] && $subtotal < $coupon['min_order_amount']) {
    jsonResponse(['error' => 'Minimum order of ' . formatCurrency($coupon['min_order_amount']) . ' required']);
}

jsonResponse([
    'valid' => true,
    'code' => $coupon['code'],
    'type' => $coupon['discount_type'],
    'value' => floatval($coupon['discount_value']),
    'description' => $coupon['discount_type'] === 'percentage' 
        ? $coupon['discount_value'] . '% off'
        : formatCurrency($coupon['discount_value']) . ' off'
]);
