<?php
// buy-tokens.php
session_start();
require_once 'config.php';

// Auth Check
if (!isset($_SESSION['user_id'])) {
    $_SESSION['redirect_after_login'] = "buy-tokens.php" . ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '');
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$needed = isset($_GET['needed']) ? intval($_GET['needed']) : 0;

// Token Rules
$min_tokens = 1000;
$batch_size = 500;
$cost_per_token = COST_BASE_VALUE;

// Calculate default amount based on 'needed' parameter and rules
$default_amount = max($min_tokens, ceil($needed / $batch_size) * $batch_size);

// Handle form submission
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['tokens'])) {
    $tokens = intval($_POST['tokens']);
    if ($tokens < $min_tokens) {
        $error = "Minimum order is " . number_format($min_tokens) . " tokens.";
    } elseif ($tokens % $batch_size !== 0) {
        $error = "Tokens must be purchased in batches of " . number_format($batch_size) . ".";
    } else {
        $price = $tokens * $cost_per_token;

        // Ensure cart structure exists
        if (!isset($_SESSION['cart'])) {
            $_SESSION['cart'] = ['package' => null, 'topup' => null];
        }

        $_SESSION['cart']['topup'] = [
            'tokens' => $tokens,
            'price' => $price
        ];

        header("Location: cart.php");
        exit;
    }
} else {
    $tokens = $default_amount;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Buy Top-Up Tokens | SaniBook Kenya</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Space+Grotesk:wght@500;600;700&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        brand: {
                            dark: '#0f172a', blue: '#2563eb', cyan: '#0891b2',
                            red: '#dc2626', lime: '#65a30d', gold: '#ca8a04',
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                        display: ['Space Grotesk', 'sans-serif'],
                    },
                }
            }
        }
    </script>
</head>

<body class="bg-slate-50 font-sans text-slate-800 antialiased flex flex-col min-h-screen">

    <?php include 'navbar.php'; ?>

    <!-- Main Content -->
    <main class="flex-grow pt-24 pb-16">
        <div class="container mx-auto px-4 sm:px-6 lg:px-8 max-w-2xl">

            <div class="bg-white rounded-2xl shadow-xl border border-slate-100 overflow-hidden">
                <div class="bg-brand-dark p-6 text-center text-white">
                    <i class="fa-solid fa-coins text-4xl text-brand-gold mb-4 drop-shadow-lg"></i>
                    <h1 class="text-3xl font-display font-bold">Buy Top-Up Tokens</h1>
                    <p class="text-slate-300 mt-2">Instantly add tokens to your active subscription.</p>
                </div>

                <div class="p-8">
                    <?php if ($needed > 0): ?>
                        <div
                            class="bg-blue-50 border border-blue-200 text-blue-800 px-4 py-3 rounded-lg mb-6 flex items-start gap-3">
                            <i class="fa-solid fa-circle-info mt-1"></i>
                            <div>
                                <p class="font-bold text-sm text-blue-900">Tokens Needed</p>
                                <p class="text-xs">Your data submission requires <span class="font-bold">
                                        <?php echo number_format($needed); ?>
                                    </span> more tokens.<br>The slider below has been pre-set to the minimum required batch
                                    to cover this.</p>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if ($error): ?>
                        <div class="bg-red-50 text-red-700 p-4 rounded-lg mb-6 border border-red-200 text-sm font-medium">
                            <i class="fa-solid fa-triangle-exclamation mr-2"></i>
                            <?php echo $error; ?>
                        </div>
                    <?php endif; ?>

                    <form action="buy-tokens.php" method="POST" id="buy-form">

                        <div class="mb-8 p-6 bg-slate-50 rounded-xl border border-slate-200 text-center">
                            <label class="block text-slate-700 font-bold mb-4 uppercase tracking-widest text-sm">Select
                                Token Amount</label>

                            <div class="flex items-center justify-center gap-4 mb-6">
                                <button type="button" onclick="adjustTokens(-<?php echo $batch_size; ?>)"
                                    class="w-10 h-10 rounded-full bg-white border border-slate-300 text-slate-600 hover:bg-slate-100 hover:text-brand-blue transition flex items-center justify-center">
                                    <i class="fa-solid fa-minus"></i>
                                </button>
                                <div class="relative w-48">
                                    <input type="number" name="tokens" id="tokens-input" value="<?php echo $tokens; ?>"
                                        min="<?php echo $min_tokens; ?>" step="<?php echo $batch_size; ?>"
                                        class="w-full text-center text-3xl font-bold font-display text-brand-dark bg-transparent border-none focus:ring-0 p-0"
                                        onchange="updatePrice()">
                                </div>
                                <button type="button" onclick="adjustTokens(<?php echo $batch_size; ?>)"
                                    class="w-10 h-10 rounded-full bg-white border border-slate-300 text-slate-600 hover:bg-slate-100 hover:text-brand-blue transition flex items-center justify-center">
                                    <i class="fa-solid fa-plus"></i>
                                </button>
                            </div>

                            <p class="text-xs text-slate-500 mb-2">Minimum: <span class="font-bold">
                                    <?php echo number_format($min_tokens); ?>
                                </span> | Sold in batches of <span class="font-bold">
                                    <?php echo number_format($batch_size); ?>
                                </span></p>
                        </div>

                        <div class="border-t border-slate-100 pt-6 mb-8">
                            <div class="flex justify-between items-center mb-2">
                                <span class="text-slate-600 font-medium">Price per token:</span>
                                <span class="text-slate-800 font-bold">KES
                                    <?php echo number_format($cost_per_token, 2); ?>
                                </span>
                            </div>
                            <div class="flex justify-between items-center mt-4 p-4 bg-brand-lime/10 rounded-lg">
                                <span class="text-lg font-bold text-slate-800">Total Price:</span>
                                <span class="text-2xl font-black text-brand-lime" id="total-price">KES
                                    <?php echo number_format($tokens * $cost_per_token); ?>
                                </span>
                            </div>
                        </div>

                        <button type="submit"
                            class="w-full py-4 bg-brand-blue text-white rounded-lg font-bold text-lg uppercase tracking-wider hover:bg-blue-700 transition shadow-lg flex items-center justify-center gap-2">
                            <span>Proceed to Checkout</span>
                            <i class="fa-solid fa-arrow-right"></i>
                        </button>
                    </form>

                </div>
            </div>
        </div>
    </main>

    <?php include 'footer.php'; ?>

    <script>
        const minTokens = <?php echo $min_tokens; ?>;
        const batchSize = <?php echo $batch_size; ?>;
        const costPerToken = <?php echo $cost_per_token; ?>;
        const input = document.getElementById('tokens-input');
        const priceDisplay = document.getElementById('total-price');

        function adjustTokens(amount) {
            let currentVal = parseInt(input.value) || minTokens;
            let newVal = currentVal + amount;

            // Re-align to batch sizes
            newVal = Math.round(newVal / batchSize) * batchSize;

            if (newVal < minTokens) newVal = minTokens;

            input.value = newVal;
            updatePrice();
        }

        function updatePrice() {
            let val = parseInt(input.value) || minTokens;

            // Snap to grid
            val = Math.round(val / batchSize) * batchSize;
            if (val < minTokens) val = minTokens;

            if (val !== parseInt(input.value)) {
                input.value = val;
            }

            const cost = val * costPerToken;
            priceDisplay.innerText = 'KES ' + cost.toLocaleString();
        }

        // Initial setup
        updatePrice();
    </script>
</body>

</html>