<?php
/**
 * Discount Code Validation API
 * Validates discount codes in real-time
 */

require_once '../includes/middleware.php';
require_once '../config/database.php';

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

$db = getDB();
$code = $_GET['code'] ?? '';

if (empty($code)) {
    echo json_encode(['valid' => false, 'message' => 'Please enter a discount code']);
    exit;
}

$code = strtoupper(trim($code));

try {
    $stmt = $db->prepare("
        SELECT * FROM discount_codes
        WHERE code = ? AND is_active = 1
        AND (valid_from IS NULL OR valid_from <= NOW())
        AND (valid_until IS NULL OR valid_until >= NOW())
    ");
    $stmt->execute([$code]);
    $discount = $stmt->fetch();

    if (!$discount) {
        echo json_encode(['valid' => false, 'message' => 'Invalid or expired discount code']);
        exit;
    }

    // Check usage limit
    if ($discount['usage_limit'] && $discount['usage_count'] >= $discount['usage_limit']) {
        echo json_encode(['valid' => false, 'message' => 'This discount code has reached its usage limit']);
        exit;
    }

    // Format discount message
    if ($discount['discount_type'] === 'percentage') {
        $message = sprintf('%.0f%% discount applied!', $discount['discount_value']);
    } else {
        $message = sprintf('$%.2f discount applied!', $discount['discount_value']);
    }

    echo json_encode([
        'valid' => true,
        'message' => $message,
        'discount_type' => $discount['discount_type'],
        'discount_value' => $discount['discount_value']
    ]);

} catch (Exception $e) {
    echo json_encode(['valid' => false, 'message' => 'Unable to validate discount code']);
}
