<?php
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'].'23:59:59') < time())
    { echo json_encode(['success'=>false,'msg'=>'এই কুপনের মেয়াদ শেষ।']); exit; }

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

// Login required check
$requireLogin = (int)($coupon['require_login'] ?? 0);
if ($requireLogin && !isLoggedIn())
    { echo json_encode(['success'=>false,'msg'=>'এই কুপন ব্যবহার করতে লগইন করতে হবে।']); exit; }

// Assigned to specific user
$assignedUserId = (int)($coupon['assigned_user_id'] ?? 0);
if ($assignedUserId) {
    if (!isLoggedIn()) { echo json_encode(['success'=>false,'msg'=>'এই কুপনটি নির্দিষ্ট অ্যাকাউন্টের জন্য।']); exit; }
    if ($_SESSION['user_id'] != $assignedUserId) { echo json_encode(['success'=>false,'msg'=>'এই কুপনটি আপনার অ্যাকাউন্টের জন্য নয়।']); exit; }
}

// Per-user once check (logged in users)
if (isLoggedIn()) {
    $used=$pdo->prepare("SELECT id FROM coupon_usage WHERE coupon_id=? AND user_id=?");
    $used->execute([$coupon['id'],$_SESSION['user_id']]);
    if ($used->fetch()) { 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
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).' ছাড় পেলেন।',
]);
