<?php
// apply-coupon.php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/functions.php';

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

$coupon_code = $_POST['coupon'] ?? '';
$subtotal = floatval($_POST['subtotal'] ?? 0);

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

// Check if coupon exists
$stmt = $pdo->prepare("SELECT * FROM coupons WHERE code = ? AND status = 1 AND expires_at > NOW()");
$stmt->execute([$coupon_code]);
$coupon = $stmt->fetch();

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

// Check minimum order
if ($coupon['min_order'] > 0 && $subtotal < $coupon['min_order']) {
    echo json_encode([
        'success' => false, 
        'message' => 'Minimum order amount for this coupon is ' . number_format($coupon['min_order']) . ' TK'
    ]);
    exit;
}

// Check usage limit
if ($coupon['usage_limit'] && $coupon['used_count'] >= $coupon['usage_limit']) {
    echo json_encode(['success' => false, 'message' => 'Coupon usage limit exceeded']);
    exit;
}

// Calculate discount
if ($coupon['discount_type'] == 'percentage') {
    $discount_amount = ($subtotal * $coupon['discount_amount']) / 100;
} else {
    $discount_amount = $coupon['discount_amount'];
}

echo json_encode([
    'success' => true,
    'message' => 'Coupon applied successfully!',
    'coupon' => $coupon,
    'discount_amount' => $discount_amount
]);
?>