<?php
ob_start();
require 'config.php';
ob_clean();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Belum login']);
    exit;
}

$code     = strtoupper(trim($_POST['code']     ?? ''));
$subtotal = max(0, (int)($_POST['subtotal']    ?? 0));

if (empty($code)) {
    echo json_encode(['success' => false, 'message' => 'Kode voucher kosong']);
    exit;
}

$stmt = $pdo->prepare("
    SELECT * FROM vouchers
     WHERE code        = ?
       AND is_active   = 1
       AND valid_from  <= CURDATE()
       AND valid_until >= CURDATE()
     LIMIT 1
");
$stmt->execute([$code]);
$voucher = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$voucher) {
    echo json_encode(['success' => false, 'message' => '❌ Voucher tidak ditemukan atau sudah kadaluarsa']);
    exit;
}

if ($voucher['quota'] > 0 && $voucher['used_count'] >= $voucher['quota']) {
    echo json_encode(['success' => false, 'message' => '❌ Kuota voucher sudah habis']);
    exit;
}

if ($subtotal < $voucher['min_order']) {
    $min_fmt = number_format($voucher['min_order'], 0, ',', '.');
    echo json_encode(['success' => false, 'message' => "❌ Minimum order Rp {$min_fmt} untuk voucher ini"]);
    exit;
}

$discount_amount = 0;
if ($voucher['discount_type'] === 'percent') {
    $discount_amount = (int)round($subtotal * $voucher['discount_value'] / 100);
    if ($voucher['max_discount'] > 0 && $discount_amount > $voucher['max_discount']) {
        $discount_amount = (int)$voucher['max_discount'];
    }
} else {
    $discount_amount = (int)$voucher['discount_value'];
}

$discount_amount = min($discount_amount, $subtotal);

echo json_encode([
    'success'         => true,
    'code'            => $voucher['code'],
    'description'     => $voucher['description'],
    'discount_type'   => $voucher['discount_type'],
    'discount_value'  => $voucher['discount_value'],
    'discount_amount' => $discount_amount,
    'message'         => '✅ Voucher diterapkan! Hemat Rp ' . number_format($discount_amount, 0, ',', '.')
]);