<?php
// pricing.php  
session_start();
require_once 'config.php';
$is_logged_in = isset($_SESSION['user_id']);

// Fetch user's active subscription
$user_sub = null;
if ($is_logged_in && $conn) {
    $sub_stmt = $conn->prepare(
        "SELECT us.package_id, sp.name AS package_name, sp.price AS package_price, sp.token_amount AS package_tokens
         FROM user_subscriptions us
         JOIN subscription_packages sp ON us.package_id = sp.id
         WHERE us.user_id = ? AND us.status = 'active'
         LIMIT 1"
    );
    if ($sub_stmt) {
        $sub_stmt->bind_param("i", $_SESSION['user_id']);
        $sub_stmt->execute();
        $user_sub = $sub_stmt->get_result()->fetch_assoc();
        $sub_stmt->close();
    }
}

// Fetch Packages
$packages = [];
if ($conn) {
    $result = $conn->query("SELECT * FROM subscription_packages WHERE is_active = 1 ORDER BY price ASC");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            // Calculate savings and metrics
            $row['cost_per_token'] = $row['token_amount'] > 0 ? $row['price'] / $row['token_amount'] : 0;
            $packages[] = $row;
        }
    }
}

// Calculate savings (baseline is first non-free package)
$baseline_rate = 0;
foreach ($packages as $pkg) {
    if ($pkg['price'] > 0 && $pkg['token_amount'] > 0 && $baseline_rate == 0) {
        $baseline_rate = $pkg['cost_per_token'];
        break;
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pricing & 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>
    <style>
        .gradient-community {
            background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
        }

        .gradient-basic {
            background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
        }

        .gradient-standard {
            background: linear-gradient(135deg, #a5f3fc 0%, #67e8f9 100%);
        }

        .gradient-premium {
            background: linear-gradient(135deg, #d4a574 0%, #ca8a04 100%);
        }

        .gradient-enterprise {
            background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
        }
    </style>
</head>

<body class="antialiased text-slate-900 bg-gradient-to-br from-slate-50 to-blue-50 min-h-screen">
    <?php include 'navbar.php'; ?>

    <main class="py-12 px-4">

        <!-- Hero Header -->
        <div class="max-w-5xl mx-auto text-center mb-16">
            <div
                class="inline-flex items-center gap-2 px-4 py-2 bg-blue-100 text-blue-700 rounded-full text-sm font-semibold mb-6">
                <i class="fa-solid fa-bolt"></i> Pay-as-you-go Token System
            </div>
            <h1 class="text-3xl md:text-4xl font-display font-extrabold text-slate-900 mb-6 leading-tight">
                Choose Your <span
                    class="bg-gradient-to-r from-blue-600 to-cyan-500 bg-clip-text text-transparent">Data</span> Power
            </h1>
            <p class="text-xl text-slate-600 leading-relaxed max-w-3xl mx-auto">
                Buy tokens once, use them to publish impactful sanitation data with text, images, and videos—no
                monthly fees.
            </p>
        </div>

        <!-- Token Cost Reference & Calculator -->
        <section class="max-w-6xl mx-auto mb-16 px-4">
            <div class="bg-gradient-to-br from-slate-800 to-slate-900 rounded-2xl shadow-2xl p-8 md:p-10 text-white">
                <div class="flex flex-col md:flex-row gap-8">
                    <!-- Rates Overview -->
                    <div class="flex-1">
                        <div class="flex items-center gap-3 mb-6">
                            <div class="w-12 h-12 bg-blue-500 rounded-xl flex items-center justify-center shrink-0">
                                <i class="fa-solid fa-calculator text-2xl"></i>
                            </div>
                            <div>
                                <h2 class="text-2xl font-display font-bold">Token Consumption Rates</h2>
                                <p class="text-slate-300">Understand how your tokens are spent</p>
                            </div>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div class="bg-white/10 backdrop-blur-sm rounded-xl p-4 border border-white/20">
                                <i class="fa-solid fa-align-left text-2xl text-blue-400 mb-2"></i>
                                <div class="text-xl font-bold"><?= COST_PER_CHAR ?> <span
                                        class="text-xs font-normal text-slate-300">token/char</span></div>
                            </div>
                            <div class="bg-white/10 backdrop-blur-sm rounded-xl p-4 border border-white/20">
                                <i class="fa-solid fa-image text-2xl text-green-400 mb-2"></i>
                                <div class="text-xl font-bold"><?= number_format(COST_PER_IMAGE) ?> <span
                                        class="text-xs font-normal text-slate-300">tokens/img</span></div>
                            </div>
                            <div class="bg-white/10 backdrop-blur-sm rounded-xl p-4 border border-white/20">
                                <i class="fa-solid fa-video text-2xl text-red-400 mb-2"></i>
                                <div class="text-xl font-bold"><?= number_format(COST_PER_VIDEO_SEC) ?> <span
                                        class="text-xs font-normal text-slate-300">tokens/sec (video)</span></div>
                            </div>
                            <div class="bg-white/10 backdrop-blur-sm rounded-xl p-4 border border-white/20">
                                <i class="fa-solid fa-headphones text-2xl text-purple-400 mb-2"></i>
                                <div class="text-xl font-bold"><?= number_format(COST_PER_AUDIO_SEC) ?> <span
                                        class="text-xs font-normal text-slate-300">tokens/sec (audio)</span></div>
                            </div>
                        </div>
                        <div
                            class="mt-4 p-4 bg-amber-500/20 border border-amber-400/30 rounded-xl text-sm leading-relaxed">
                            <i class="fa-solid fa-layer-group text-amber-400 mr-2"></i>
                            Base cost covers 1 category. Each additional category costs
                            <strong><?= number_format(COST_PER_EXTRA_CATEGORY) ?></strong> tokens.
                        </div>
                    </div>

                    <!-- Interactive Calculator -->
                    <div class="flex-1 bg-white/5 rounded-xl p-6 border border-white/10">
                        <h3 class="font-bold text-lg mb-4 text-blue-100 flex items-center"><i
                                class="fa-solid fa-chart-pie mr-2"></i> Interactive Cost Estimator</h3>

                        <div class="space-y-4">
                            <div class="flex items-center justify-between">
                                <label class="text-sm font-medium text-slate-300 w-1/3">Characters</label>
                                <input type="number" id="calc-chars" value="1500" min="0" step="100"
                                    class="w-2/3 bg-slate-800 border border-slate-600 rounded px-3 py-2 text-white outline-none focus:border-blue-400 transition-colors"
                                    oninput="calculateTokens()">
                            </div>
                            <div class="flex items-center justify-between">
                                <label class="text-sm font-medium text-slate-300 w-1/3">Images</label>
                                <input type="number" id="calc-images" value="3" min="0"
                                    class="w-2/3 bg-slate-800 border border-slate-600 rounded px-3 py-2 text-white outline-none focus:border-green-400 transition-colors"
                                    oninput="calculateTokens()">
                            </div>
                            <div class="flex items-center justify-between">
                                <label class="text-sm font-medium text-slate-300 w-1/3">Video (sec)</label>
                                <input type="number" id="calc-video" value="30" min="0" step="10"
                                    class="w-2/3 bg-slate-800 border border-slate-600 rounded px-3 py-2 text-white outline-none focus:border-red-400 transition-colors"
                                    oninput="calculateTokens()">
                            </div>
                            <div class="flex items-center justify-between">
                                <label class="text-sm font-medium text-slate-300 w-1/3">Audio (sec)</label>
                                <input type="number" id="calc-audio" value="0" min="0" step="10"
                                    class="w-2/3 bg-slate-800 border border-slate-600 rounded px-3 py-2 text-white outline-none focus:border-purple-400 transition-colors"
                                    oninput="calculateTokens()">
                            </div>
                            <div class="flex items-center justify-between">
                                <label class="text-sm font-medium text-slate-300 w-1/3">Extra Categories</label>
                                <input type="number" id="calc-categories" value="0" min="0"
                                    class="w-2/3 bg-slate-800 border border-slate-600 rounded px-3 py-2 text-white outline-none focus:border-amber-400 transition-colors"
                                    oninput="calculateTokens()">
                            </div>
                        </div>

                        <div class="mt-6 pt-4 border-t border-white/20 flex items-end justify-between">
                            <span class="text-slate-300 font-medium">Estimated Total:</span>
                            <div class="text-right">
                                <div class="text-4xl font-display font-extrabold text-green-400" id="calc-total">0</div>
                                <div class="text-xs text-slate-400 uppercase tracking-widest mt-1">Tokens</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <script>
            // Token rates
            const RATE_CHAR = <?= COST_PER_CHAR ?>;
            const RATE_IMAGE = <?= COST_PER_IMAGE ?>;
            const RATE_VIDEO = <?= COST_PER_VIDEO_SEC ?>;
            const RATE_AUDIO = <?= COST_PER_AUDIO_SEC ?>;
            const RATE_CATEGORY = <?= COST_PER_EXTRA_CATEGORY ?>;
            const RATE_BASE_VALUE = <?= COST_BASE_VALUE ?>;

            function calculateTokens() {
                const chars = parseInt(document.getElementById('calc-chars').value) || 0;
                const images = parseInt(document.getElementById('calc-images').value) || 0;
                const video = parseInt(document.getElementById('calc-video').value) || 0;
                const audio = parseInt(document.getElementById('calc-audio').value) || 0;
                const categories = parseInt(document.getElementById('calc-categories').value) || 0;

                const total = (chars * RATE_CHAR) +
                    (images * RATE_IMAGE) +
                    (video * RATE_VIDEO) +
                    (audio * RATE_AUDIO) +
                    (categories * RATE_CATEGORY);

                document.getElementById('calc-total').innerText = total.toLocaleString();
            }

            // Run once on load
            document.addEventListener('DOMContentLoaded', calculateTokens);
        </script>

        <!-- Pricing Tiers Grid -->
        <section class="max-w-7xl mx-auto mb-20">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6">

                <?php
                $tier_classes = ['community', 'basic', 'standard', 'premium', 'enterprise'];
                $tier_icons = [
                    'fa-users',
                    'fa-seedling',
                    'fa-building',
                    'fa-gem',
                    'fa-rocket'
                ];
                $idx = 0;
                foreach ($packages as $pkg):
                    $tier_class = $tier_classes[$idx] ?? 'basic';
                    $icon = $tier_icons[$idx] ?? 'fa-box';
                    $is_featured = $pkg['is_featured'];
                    $is_free = $pkg['price'] == 0;
                    $savings = 0;
                    if ($baseline_rate > 0 && $pkg['cost_per_token'] > 0) {
                        $savings = round(($baseline_rate - $pkg['cost_per_token']) * $pkg['token_amount']);
                    }
                    $idx++;
                    ?>

                    <div
                        class="group relative bg-white rounded-2xl shadow-lg border-2 <?= $is_featured ? 'border-gold-500 scale-105 z-10' : 'border-slate-200' ?> hover:shadow-2xl transition-all duration-300 overflow-hidden flex flex-col h-full">





                        <!-- Gradient Header -->
                        <div class="gradient-<?= $tier_class ?> p-6 text-center">
                            <div
                                class="w-16 h-16 mx-auto bg-white/30 backdrop-blur-sm rounded-2xl flex items-center justify-center mb-4 shadow-inner">
                                <i
                                    class="fa-solid <?= $icon ?> text-3xl <?= $is_free ? 'text-slate-600' : 'text-slate-800' ?>"></i>
                            </div>
                            <h3 class="text-2xl font-display font-bold text-slate-900 uppercase tracking-wide">
                                <?= htmlspecialchars($pkg['name']) ?>
                            </h3>
                        </div>

                        <div class="p-6 flex flex-col flex-grow">
                            <!-- Pricing -->
                            <div class="text-center mb-6">
                                <div class="text-4xl font-display font-extrabold text-slate-900 mb-1">
                                    <?= $is_free ? 'FREE' : 'KES ' . number_format($pkg['price']) ?>
                                </div>
                                <div class="text-lg font-bold text-blue-600">
                                    <?= $is_free ? '0 Tokens' : number_format($pkg['token_amount']) . ' Tokens' ?>
                                </div>
                                <?php if (!$is_free && $pkg['token_amount'] > 0): ?>
                                    <div class="text-xs text-slate-500 mt-1">
                                        <?= number_format($pkg['cost_per_token'], 2) ?> KES/token
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Description -->
                            <div
                                class="text-sm text-slate-600 leading-relaxed mb-6 min-h-[80px] border-t border-b border-slate-100 py-4 flex-grow">
                                <?php
                                if ($is_free) {
                                    echo "Get listed and be found in the National Digital Directory.";
                                } else {
                                    $desc = $pkg['description'];
                                    // Remove specific phrases requested by user
                                    $strip_phrases = [
                                        '/Ideal for County-level programs with high volume\.?/i',
                                        '/For National Partners & International NGOs\.?/i',
                                        '/Best for [^.]+\.?/i',
                                        '/Entry-level package[\s.]*/i'
                                    ];
                                    $desc = preg_replace($strip_phrases, '', $desc);
                                    $desc = trim($desc, " .");
                                    echo nl2br(htmlspecialchars($desc));

                                    if ($savings > 5000) {
                                        echo "<div class='mt-3 font-bold text-blue-600 italic'>*Save KES " . number_format($savings) . "*</div>";
                                    }
                                }
                                ?>
                            </div>

                            <!-- CTA -->
                            <?php
                            $is_current = $user_sub && $user_sub['package_id'] == $pkg['id'];
                            $is_downgrade = $user_sub && $user_sub['package_price'] > 0 && $pkg['price'] <= $user_sub['package_price'] && !$is_current && !$is_free;
                            $upgrade_price = ($user_sub && $user_sub['package_price'] > 0 && $pkg['price'] > $user_sub['package_price'])
                                ? $pkg['price'] - $user_sub['package_price'] : $pkg['price'];
                            ?>
                            <?php if ($is_free): ?>
                                <span
                                    class="block w-full text-center py-3 rounded-lg font-bold text-sm uppercase tracking-wider bg-slate-200 text-slate-500 cursor-not-allowed">
                                    Free Tier
                                </span>
                            <?php elseif ($is_current): ?>
                                <span
                                    class="block w-full text-center py-3 rounded-lg font-bold text-sm uppercase tracking-wider bg-green-100 text-green-700 cursor-default">
                                    <i class="fa-solid fa-check-circle mr-1"></i> Current Plan
                                </span>
                            <?php elseif ($is_downgrade): ?>
                                <span
                                    class="block w-full text-center py-3 rounded-lg font-bold text-sm uppercase tracking-wider bg-slate-100 text-slate-400 cursor-not-allowed"
                                    title="You cannot downgrade while your current plan is active">
                                    <i class="fa-solid fa-lock mr-1"></i> Downgrade N/A
                                </span>
                            <?php elseif (!$is_logged_in): ?>
                                <a href="login.php?redirect=pricing.php"
                                    class="block w-full text-center py-3 rounded-lg font-bold text-sm uppercase tracking-wider bg-blue-600 text-white hover:bg-blue-700 shadow-md transition-all duration-200">
                                    Login to Purchase
                                </a>
                            <?php else: ?>
                                <button onclick="addPackageToCart(<?= $pkg['id'] ?>, this)"
                                    class="add-to-cart-btn w-full text-center py-3 rounded-lg font-bold text-sm uppercase tracking-wider transition-all duration-200 <?= $is_featured ? 'bg-gradient-to-r from-yellow-500 to-yellow-600 text-white shadow-lg hover:shadow-xl transform hover:-translate-y-0.5' : 'bg-blue-600 text-white hover:bg-blue-700 shadow-md' ?>">
                                    <i class="fa-solid fa-cart-plus mr-1"></i>
                                    <?php if ($user_sub && $user_sub['package_price'] > 0): ?>
                                        Upgrade
                                    <?php else: ?>
                                        Add to Cart
                                    <?php endif; ?>
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>

                <?php endforeach; ?>
            </div>
        </section>

        <!-- 30-Day Refund Policy -->
        <div class="max-w-7xl mx-auto mb-6 px-4">
            <div class="bg-white border text-center border-slate-200 p-6 rounded-2xl shadow-sm">
                <div class="mb-4">
                    <div
                        class="w-12 h-12 bg-green-100 mx-auto rounded-full flex items-center justify-center text-green-600">
                        <i class="fa-solid fa-shield-halved text-xl"></i>
                    </div>
                </div>
                <h4 class="text-slate-900 font-bold text-lg mb-2">30-Day Money-Back Guarantee</h4>
                <p class="text-slate-600 text-sm max-w-2xl mx-auto">We are confident in the value SaniBook provides. If
                    you are not completely satisfied with your subscription, contact us within 30 days of purchase for a
                    full refund, no questions asked.</p>
            </div>
        </div>

        <!-- Payment Contact Notice (Transitional) -->
        <div class="max-w-7xl mx-auto mb-20 px-4">
            <div
                class="bg-blue-50 border-l-4 border-blue-600 p-6 rounded-r-2xl shadow-sm flex flex-col md:flex-row items-center justify-between gap-6">
                <div class="flex items-center gap-4">
                    <div
                        class="w-12 h-12 bg-blue-600 rounded-full flex items-center justify-center text-white shrink-0">
                        <i class="fa-solid fa-envelope"></i>
                    </div>
                    <div>
                        <h4 class="text-blue-900 font-bold">Billing, Payment & Sponsorship Inquiries</h4>
                        <p class="text-blue-700 text-sm">Our payment gateway is currently being finalized. For payment
                            details, custom billing requirements, or <strong>corporate sponsorship inquiries</strong>,
                            please reach out to our team.</p>
                    </div>
                </div>
                <a href="mailto:ewambui@washvoiceafrica.org"
                    class="inline-flex items-center gap-2 px-6 py-3 bg-white text-blue-600 border border-blue-200 rounded-xl hover:bg-blue-50 transition-all font-bold group">
                    ewambui@washvoiceafrica.org
                    <i class="fa-solid fa-arrow-right group-hover:translate-x-1 transition-transform"></i>
                </a>
            </div>
        </div>

        <!-- Feature Comparison Table -->
        <section class="max-w-7xl mx-auto mb-20">
            <div class="bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
                <div class="bg-gradient-to-r from-blue-900 to-blue-800 p-8 text-white">
                    <h2 class="text-3xl font-display font-bold mb-2">Compare All Features</h2>
                    <p class="text-blue-200">Find the perfect package for your organization</p>
                </div>

                <div class="overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead class="bg-slate-50 border-b border-slate-200">
                            <tr>
                                <th class="text-left p-4 font-bold text-slate-700 sticky left-0 bg-slate-50 z-10">
                                    Feature</th>
                                <?php foreach ($packages as $pkg): ?>
                                    <th class="p-4 text-center font-bold text-slate-700 min-w-[140px]">
                                        <?= htmlspecialchars($pkg['name']) ?>
                                    </th>
                                <?php endforeach; ?>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                            <tr class="hover:bg-slate-50">
                                <td class="p-4 font-semibold text-slate-800 sticky left-0 bg-white">Directory Listing
                                </td>
                                <?php foreach ($packages as $pkg): ?>
                                    <td class="p-4 text-center">
                                        <i class="fa-solid fa-check text-green-600 text-lg"></i>
                                    </td>
                                <?php endforeach; ?>
                            </tr>
                            <tr class="hover:bg-slate-50">
                                <td class="p-4 font-semibold text-slate-800 sticky left-0 bg-white">Data Submissions
                                </td>
                                <?php foreach ($packages as $pkg): ?>
                                    <td class="p-4 text-center">
                                        <?= $pkg['token_amount'] > 0 ? '<i class="fa-solid fa-check text-green-600 text-lg"></i>' : '<i class="fa-solid fa-xmark text-red-400 text-lg"></i>' ?>
                                    </td>
                                <?php endforeach; ?>
                            </tr>
                            <tr class="hover:bg-slate-50">
                                <td class="p-4 font-semibold text-slate-800 sticky left-0 bg-white">Public Profile Page
                                </td>
                                <?php foreach ($packages as $pkg): ?>
                                    <td class="p-4 text-center">
                                        <i class="fa-solid fa-check text-green-600 text-lg"></i>
                                    </td>
                                <?php endforeach; ?>
                            </tr>
                            <tr class="hover:bg-slate-50 bg-blue-50/30">
                                <td class="p-4 font-semibold text-slate-800 sticky left-0 bg-blue-50/30"><i
                                        class="fa-solid fa-coins text-blue-600 mr-2"></i>Token Amount</td>
                                <?php foreach ($packages as $pkg): ?>
                                    <td class="p-4 text-center font-bold text-blue-700">
                                        <?= $pkg['token_amount'] > 0 ? number_format($pkg['token_amount']) : '—' ?>
                                    </td>
                                <?php endforeach; ?>
                            </tr>
                            <tr class="hover:bg-slate-50">
                                <td class="p-4 font-semibold text-slate-800 sticky left-0 bg-white">Priority Support
                                </td>
                                <?php foreach ($packages as $idx => $pkg): ?>
                                    <td class="p-4 text-center">
                                        <?= $idx >= 3 ? '<i class="fa-solid fa-check text-green-600 text-lg"></i>' : '<i class="fa-solid fa-xmark text-red-400 text-lg"></i>' ?>
                                    </td>
                                <?php endforeach; ?>
                            </tr>
                            <tr class="hover:bg-slate-50">
                                <td class="p-4 font-semibold text-slate-800 sticky left-0 bg-white">Dedicated Account
                                    Manager</td>
                                <?php foreach ($packages as $idx => $pkg): ?>
                                    <td class="p-4 text-center">
                                        <?= $idx >= 4 ? '<i class="fa-solid fa-check text-green-600 text-lg"></i>' : '<i class="fa-solid fa-xmark text-red-400 text-lg"></i>' ?>
                                    </td>
                                <?php endforeach; ?>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>


        <!-- Token Top-Up Section -->
        <section class="max-w-5xl mx-auto mb-20">
            <div class="bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
                <div class="bg-gradient-to-r from-green-600 to-emerald-600 p-8 text-white">
                    <div class="flex items-center gap-3 mb-2">
                        <div class="w-12 h-12 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center">
                            <i class="fa-solid fa-battery-half text-2xl"></i>
                        </div>
                        <div>
                            <h2 class="text-3xl font-display font-bold">Need More Tokens?</h2>
                            <p class="text-green-100">Top up your balance — buy exactly what you need</p>
                        </div>
                    </div>
                </div>

                <div class="p-8">
                    <?php
                    // Check if user has a paid subscription (Basic+)
                    $has_paid_sub = false;
                    if ($is_logged_in && $conn) {
                        $sub_check = $conn->prepare(
                            "SELECT sp.price FROM user_subscriptions us
                             JOIN subscription_packages sp ON us.package_id = sp.id
                             WHERE us.user_id = ? AND us.status = 'active' AND sp.price > 0
                             LIMIT 1"
                        );
                        if ($sub_check) {
                            $sub_check->bind_param("i", $_SESSION['user_id']);
                            $sub_check->execute();
                            $has_paid_sub = $sub_check->get_result()->num_rows > 0;
                            $sub_check->close();
                        }
                    }
                    ?>

                    <?php if (!$is_logged_in): ?>
                        <div class="text-center py-8">
                            <p class="text-slate-600 mb-4">Log in to purchase tokens.</p>
                            <a href="login.php"
                                class="px-6 py-3 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 transition-colors">Log
                                In</a>
                        </div>
                    <?php elseif (!$has_paid_sub): ?>
                        <div class="text-center py-8">
                            <div class="w-16 h-16 mx-auto bg-amber-100 rounded-full flex items-center justify-center mb-4">
                                <i class="fa-solid fa-lock text-amber-600 text-2xl"></i>
                            </div>
                            <p class="text-slate-700 font-semibold mb-2">Token top-ups are available to paid subscribers</p>
                            <p class="text-slate-500 text-sm mb-4">Purchase a Basic package or above to unlock on-demand
                                token top-ups.</p>
                        </div>
                    <?php else: ?>
                        <div class="max-w-2xl mx-auto">
                            <!-- Rate Display -->
                            <div class="text-center mb-8">
                                <div
                                    class="inline-flex items-center gap-2 px-4 py-2 bg-green-50 text-green-700 rounded-full text-sm font-bold mb-4">
                                    <i class="fa-solid fa-tag"></i> 1 token = KES <?= number_format(COST_BASE_VALUE, 2) ?>
                                </div>
                            </div>

                            <!-- Slider -->
                            <div class="mb-8">
                                <label class="block text-sm font-bold text-slate-700 mb-3">Select token amount</label>
                                <input type="range" id="token-slider" min="1000" max="50000" step="500" value="2500"
                                    class="w-full h-3 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-green-600">
                                <div class="flex justify-between text-xs text-slate-400 mt-1">
                                    <span>1,000</span>
                                    <span>10,000</span>
                                    <span>25,000</span>
                                    <span>50,000</span>
                                </div>
                            </div>

                            <!-- Live Summary -->
                            <div class="bg-slate-50 rounded-xl p-6 text-center mb-6 border border-slate-200">
                                <div class="text-sm text-slate-500 mb-1">You're buying</div>
                                <div class="text-4xl font-display font-extrabold text-slate-900 mb-2" id="topup-tokens">
                                    2,500</div>
                                <div class="text-sm text-slate-500 mb-1">tokens for</div>
                                <div class="text-3xl font-display font-bold text-green-600" id="topup-price">KES
                                    <?= number_format(2500 * COST_BASE_VALUE) ?></div>
                            </div>

                            <!-- Quick-Select Buttons -->
                            <div class="flex flex-wrap gap-2 justify-center mb-6">
                                <button onclick="setTokens(1000)"
                                    class="topup-quick px-4 py-2 bg-slate-100 hover:bg-green-100 text-slate-700 rounded-lg text-sm font-semibold transition-colors">1,000</button>
                                <button onclick="setTokens(2500)"
                                    class="topup-quick px-4 py-2 bg-slate-100 hover:bg-green-100 text-slate-700 rounded-lg text-sm font-semibold transition-colors">2,500</button>
                                <button onclick="setTokens(5000)"
                                    class="topup-quick px-4 py-2 bg-slate-100 hover:bg-green-100 text-slate-700 rounded-lg text-sm font-semibold transition-colors">5,000</button>
                                <button onclick="setTokens(10000)"
                                    class="topup-quick px-4 py-2 bg-slate-100 hover:bg-green-100 text-slate-700 rounded-lg text-sm font-semibold transition-colors">10,000</button>
                                <button onclick="setTokens(25000)"
                                    class="topup-quick px-4 py-2 bg-slate-100 hover:bg-green-100 text-slate-700 rounded-lg text-sm font-semibold transition-colors">25,000</button>
                            </div>

                            <!-- Purchase Button -->
                            <button id="topup-buy-btn" onclick="addTopupToCart()"
                                class="block w-full text-center py-4 rounded-xl font-bold text-lg bg-gradient-to-r from-green-600 to-emerald-600 text-white shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 transition-all duration-200">
                                <i class="fa-solid fa-cart-shopping mr-2"></i> Add Tokens to Cart
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </section>

        <script>
            const slider = document.getElementById('token-slider');
            const tokensDisplay = document.getElementById('topup-tokens');
            const priceDisplay = document.getElementById('topup-price');
            const buyBtn = document.getElementById('topup-buy-btn');

            function updateTopup(tokens) {
                if (!slider) return;
                const price = tokens * RATE_BASE_VALUE;
                tokensDisplay.textContent = tokens.toLocaleString();
                priceDisplay.textContent = 'KES ' + price.toLocaleString();
                // buyBtn handled by onclick now
            }

            function setTokens(val) {
                if (!slider) return;
                slider.value = val;
                updateTopup(val);
            }

            if (slider) {
                slider.addEventListener('input', function () {
                    updateTopup(parseInt(this.value));
                });
            }

            // --- AJAX Cart Functions ---

            function addPackageToCart(packageId, btn) {
                const originalText = btn.innerHTML;
                btn.innerHTML = '<i class="fa-solid fa-circle-notch fa-spin"></i> Adding...';
                btn.disabled = true;

                fetch('cart-api.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'action=add_package&package_id=' + packageId
                })
                    .then(r => r.json())
                    .then(data => {
                        btn.innerHTML = originalText;
                        btn.disabled = false;

                        if (data.ok) {
                            if (window.refreshCartDropdown) window.refreshCartDropdown();
                            showToast('Package added to cart!', 'success');
                        } else {
                            showToast(data.error, 'error');
                        }
                    })
                    .catch(e => {
                        btn.innerHTML = originalText;
                        btn.disabled = false;
                        showToast('Connection error', 'error');
                    });
            }

            function addTopupToCart() {
                const tokens = parseInt(document.getElementById('token-slider').value);
                const btn = document.getElementById('topup-buy-btn');
                const originalText = btn.innerHTML;

                btn.innerHTML = '<i class="fa-solid fa-circle-notch fa-spin"></i> Adding...';
                btn.disabled = true;

                fetch('cart-api.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'action=add_topup&tokens=' + tokens
                })
                    .then(r => r.json())
                    .then(data => {
                        btn.innerHTML = originalText;
                        btn.disabled = false;
                        if (data.ok) {
                            if (window.refreshCartDropdown) window.refreshCartDropdown();
                            showToast('Tokens added to cart!', 'success');
                        } else {
                            showToast(data.error, 'error');
                        }
                    })
                    .catch(e => {
                        btn.innerHTML = originalText;
                        btn.disabled = false;
                        showToast('Connection error', 'error');
                    });
            }

            function showToast(message, type = 'success') {
                const toast = document.createElement('div');
                toast.className = `fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-xl text-white font-bold z-50 transform transition-all duration-300 translate-y-10 opacity-0 ${type === 'error' ? 'bg-red-500' : 'bg-green-600'}`;
                toast.innerHTML = (type === 'error' ? '<i class="fa-solid fa-circle-exclamation mr-2"></i>' : '<i class="fa-solid fa-check-circle mr-2"></i>') + message;

                document.body.appendChild(toast);

                // Animate in
                requestAnimationFrame(() => {
                    toast.classList.remove('translate-y-10', 'opacity-0');
                });

                // Remove after 3s
                setTimeout(() => {
                    toast.classList.add('translate-y-10', 'opacity-0');
                    setTimeout(() => toast.remove(), 300);
                }, 3000);
            }
        </script>
    </main>

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

</html>