<?php
// coupon-check.php — AJAX endpoint for coupon validation
require_once __DIR__ . '/config/database.php';
header('Content-Type: application/json');

$code     = strtoupper(trim($_POST['code'] ?? ''));
$subtotal = (float)($_POST['subtotal'] ?? 0);

if (!$code) { echo json_encode(['success'=>false,'msg'=>'কুপন কোড লিখুন।']); exit; }

$stmt = $pdo->prepare("SELECT * FROM coupons WHERE code=? AND is_active=1");
$stmt->execute([$code]);
$coupon = $stmt->fetch();

if (!$coupon) { echo json_encode(['success'=>false,'msg'=>'এই কুপন কোডটি বৈধ নয়।']); exit; }

// Expiry check
if ($coupon['expiry_date'] && strtotime($coupon['expiry_date']) < time()) {
    echo json_encode(['success'=>false,'msg'=>'এই কুপনের মেয়াদ শেষ হয়ে গেছে।']); exit;
}

// Usage limit check
if ($coupon['usage_limit'] > 0 && $coupon['used_count'] >= $coupon['usage_limit']) {
    echo json_encode(['success'=>false,'msg'=>'এই কুপনের ব্যবহার সীমা শেষ হয়ে গেছে।']); exit;
}

// Min order check
if ($coupon['min_order_amount'] > 0 && $subtotal < $coupon['min_order_amount']) {
    echo json_encode([
        'success'=>false,
        'msg'=>'এই কুপন ব্যবহার করতে কমপক্ষে ৳'.number_format($coupon['min_order_amount'],0).' এর অর্ডার করতে হবে।'
    ]); exit;
}

// Calculate discount
$discount = 0;
if ($coupon['discount_type'] === 'percent') {
    $discount = ($subtotal * $coupon['discount_value']) / 100;
    if ($coupon['max_discount'] > 0 && $discount > $coupon['max_discount']) {
        $discount = $coupon['max_discount'];
    }
} else {
    $discount = min($coupon['discount_value'], $subtotal);
}
$discount = round($discount, 2);

echo json_encode([
    'success'   => true,
    'discount'  => $discount,
    'coupon_id' => $coupon['id'],
    'msg'       => 'কুপন সফলভাবে প্রয়োগ হয়েছে! ৳'.number_format($discount,2).' ছাড় পেলেন।',
    'type'      => $coupon['discount_type'],
    'value'     => $coupon['discount_value'],
]);
