<?php
require_once 'common/config.php';

$id = (int)($_GET['id'] ?? 1);
$stmt = $pdo->prepare("SELECT * FROM games WHERE id = ? AND status='active'");
$stmt->execute([$id]);
$game = $stmt->fetch();
if (!$game) {
    header('Location: index.php');
    exit;
}

$pstmt = $pdo->prepare("SELECT * FROM packages WHERE game_id = ? AND status='active' ORDER BY sort_order ASC, id ASC");
$pstmt->execute([$id]);
$packages = $pstmt->fetchAll();

$gameName = $game['name'];
$gameSlug = $game['slug'] ?? '';
$gameType = $game['type'] ?: 'uid';
$gameIdentity = strtolower($gameSlug . ' ' . $gameName);
$isFreeFireProduct = ($gameType === 'uid' && preg_match('/free\s*fire|(^|[-\s])ff([-\s]|$)|uid-topup-bd|weekly-monthly|weekly-lite|level-up-pass-bd/i', $gameIdentity));
$thumbnail = $game['thumbnail'];
$rules = array_filter(array_map('trim', preg_split("/\r\n|\n|\r/", (string)$game['rules'])));
$isLoggedIn = isset($_SESSION['user_id']);
$pageTitle = $gameName . ' | ' . siteName();

require_once 'common/header.php';
require_once 'common/navbar.php';
?>

<main class="max-w-3xl mx-auto px-4 py-6 pb-28">
    <div class="bg-white rounded-xl p-3 shadow-soft mb-6 flex items-center gap-4">
        <div class="w-16 h-16 rounded-lg bg-gray-100 overflow-hidden border border-gray-200 flex-shrink-0">
            <img src="<?= htmlspecialchars($thumbnail) ?>" class="w-full h-full object-cover" alt="Game Icon">
        </div>
        <div>
            <h1 class="text-lg font-bold text-gray-800 leading-tight uppercase"><?= htmlspecialchars($gameName) ?></h1>
            <div class="inline-flex items-center gap-1 bg-orange-50 text-accent px-2 py-0.5 rounded text-xs font-semibold mt-1 border border-orange-100">
                <i class="fa-solid fa-bolt"></i> Topup in 2 seconds
            </div>
        </div>
    </div>

    <form action="<?= SITE_URL ?>/instantpay.php" method="POST" id="orderForm">
        <input type="hidden" name="game_id" value="<?= (int)$game['id'] ?>">
        <input type="hidden" name="price" id="priceField" value="<?= $packages[0]['price'] ?? 0 ?>">

        <div class="mb-6">
            <div class="flex items-center mb-4">
                <span class="w-7 h-7 rounded-full bg-accent text-white flex items-center justify-center font-bold text-sm mr-2">1</span>
                <h2 class="text-lg font-bold text-gray-800">Select Recharge</h2>
            </div>
            <div class="grid grid-cols-2 gap-3" id="packageGrid">
                <?php foreach ($packages as $index => $pkg): ?>
                <label class="package-card relative border border-gray-200 rounded-lg p-3 flex justify-between items-center cursor-pointer transition bg-white hover:border-accent">
                    <input type="radio" name="package_id" value="<?= (int)$pkg['id'] ?>" data-price="<?= htmlspecialchars($pkg['price']) ?>" class="hidden" <?= $index === 0 ? 'checked' : '' ?>>
                    <div class="flex items-center gap-2">
                        <div class="w-4 h-4 rounded-full border border-gray-300 radio-indicator flex items-center justify-center">
                            <div class="w-2 h-2 rounded-full bg-accent hidden inner-dot"></div>
                        </div>
                        <span class="text-sm text-gray-600 font-medium"><?= htmlspecialchars($pkg['name']) ?></span>
                    </div>
                    <span class="text-sm font-bold text-accent"><?= (int)$pkg['price'] ?> TK</span>
                </label>
                <?php endforeach; ?>
            </div>
            <div class="mt-4">
                <a href="tutorial.php" class="text-sm font-bold text-purple-700 hover:underline"><i class="fa-solid fa-arrow-up-right-from-square mr-1"></i> কীভাবে অর্ডার করবেন? <i class="fa-solid fa-arrow-right ml-1"></i></a>
            </div>
        </div>

        <?php if ($gameType === 'voucher'): ?>
        <div class="mb-6 flex justify-between items-center bg-white p-4 rounded-xl shadow-soft">
                <h3 class="font-bold text-gray-800">Quantity</h3>
            <div class="flex items-center gap-4 border border-gray-200 rounded-lg p-1">
                <button type="button" class="w-8 h-8 flex items-center justify-center text-gray-500 hover:bg-gray-100 rounded" onclick="updateQty(-1)"><i class="fa-solid fa-minus"></i></button>
                <input type="number" name="quantity" id="qtyInput" value="1" min="1" max="10" class="w-10 text-center font-bold text-gray-800 outline-none bg-transparent" readonly>
                <button type="button" class="w-8 h-8 flex items-center justify-center text-gray-500 hover:bg-gray-100 rounded" onclick="updateQty(1)"><i class="fa-solid fa-plus"></i></button>
            </div>
        </div>
        <?php endif; ?>

        <?php if ($gameType === 'uid'): ?>
        <div class="mb-6">
            <div class="flex items-center mb-4">
                <span class="w-7 h-7 rounded-full bg-accent text-white flex items-center justify-center font-bold text-sm mr-2">2</span>
                    <h2 class="text-lg font-bold text-gray-800">Account Info</h2>
            </div>
            <div class="bg-white p-4 rounded-xl shadow-soft">
                <label class="block text-sm font-bold text-gray-700 mb-2">Player Id</label>
                <input type="text" name="player_id" required class="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent transition" placeholder="Player Id">
                <?php if ($isFreeFireProduct): ?>
                <button type="button" id="checkPlayerName" data-game-id="<?= (int)$game['id'] ?>" data-default-label="Check Player Name" class="w-full mt-3 bg-accent text-white font-bold py-2.5 rounded-lg text-sm">Check Player Name</button>
                <p id="playerNameResult" class="hidden text-center text-sm font-bold mt-2"></p>
                <?php endif; ?>
                <?php if (!empty($game['stock_note'])): ?>
                    <p class="text-xs font-bold text-primary mt-2">Available Stock : <span class="text-green-600"><?= htmlspecialchars($game['stock_note']) ?></span></p>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="mb-8">
            <div class="flex items-center mb-4">
                <span class="w-7 h-7 rounded-full bg-accent text-white flex items-center justify-center font-bold text-sm mr-2"><?= $gameType === 'uid' ? '3' : '2' ?></span>
                <h2 class="text-lg font-bold text-gray-800">Select one option</h2>
            </div>
            <div class="grid grid-cols-2 gap-3 mb-4">
                <label class="payment-tab relative border-2 border-accent rounded-xl p-3 flex flex-col items-center justify-center cursor-pointer transition bg-orange-50">
                    <input type="radio" name="payment_method" value="wallet" class="hidden" checked>
                    <i class="fa-solid fa-wallet text-3xl text-accent mb-2"></i>
                    <span class="text-sm font-bold text-gray-800">Wallet Pay</span>
                </label>
                <label class="payment-tab relative border border-gray-200 rounded-xl p-3 flex flex-col items-center justify-center cursor-pointer transition bg-white hover:border-gray-300">
                    <input type="radio" name="payment_method" value="instant" class="hidden">
                    <div class="flex gap-1 mb-2">
                        <i class="fa-solid fa-building-columns text-2xl text-pink-500"></i>
                        <i class="fa-solid fa-mobile-screen-button text-2xl text-orange-500"></i>
                        <i class="fa-solid fa-money-bill-transfer text-2xl text-purple-600"></i>
                    </div>
                    <span class="text-sm font-bold text-gray-500">Instant Pay</span>
                </label>
            </div>
            <div class="mb-4 space-y-1 pl-1">
                <p class="text-xs text-gray-500"><i class="fa-solid fa-circle-info mr-1"></i> Your wallet balance is 0. Add money to buy this product.</p>
                <?php if (!$isLoggedIn): ?>
                <p class="text-xs text-red-500"><i class="fa-solid fa-circle-exclamation mr-1"></i> Please Login To Purchase</p>
                <?php endif; ?>
            </div>
            <?php if ($isLoggedIn): ?>
                <button type="submit" class="w-full bg-accent hover:bg-orange-600 text-white font-bold py-3.5 rounded-lg shadow-md transition uppercase tracking-wide">এখনই কিনুন</button>
            <?php else: ?>
                <a href="<?= SITE_URL ?>/login.php" class="block text-center w-full bg-accent hover:bg-orange-600 text-white font-bold py-3.5 rounded-lg shadow-md transition uppercase tracking-wide">Login</a>
            <?php endif; ?>
        </div>

        <div class="bg-white rounded-xl shadow-soft p-4 mb-6">
            <h3 class="font-bold text-gray-800 mb-3">Rules & Conditions</h3>
            <div class="text-sm text-gray-600 space-y-2">
                <ul class="list-none space-y-1.5 ml-1">
                    <?php foreach ($rules as $rule): ?>
                    <li><i class="fa-solid fa-circle-dot text-[8px] text-accent mr-1"></i> <?= htmlspecialchars($rule) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </form>
</main>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const packageInputs = document.querySelectorAll('input[name="package_id"]');
    packageInputs.forEach(input => {
        input.addEventListener('change', function() {
            document.querySelectorAll('.package-card').forEach(card => {
                card.classList.remove('border-accent', 'bg-orange-50');
                card.classList.add('border-gray-200', 'bg-white');
                card.querySelector('.radio-indicator').classList.remove('border-accent');
                card.querySelector('.inner-dot').classList.add('hidden');
            });
            if (this.checked) {
                const activeCard = this.closest('.package-card');
                activeCard.classList.remove('border-gray-200', 'bg-white');
                activeCard.classList.add('border-accent', 'bg-orange-50');
                activeCard.querySelector('.radio-indicator').classList.add('border-accent');
                activeCard.querySelector('.inner-dot').classList.remove('hidden');
                const pf = document.getElementById('priceField');
                if (pf) pf.value = this.dataset.price;
            }
        });
    });
    const paymentInputs = document.querySelectorAll('input[name="payment_method"]');
    paymentInputs.forEach(input => {
        input.addEventListener('change', function() {
            document.querySelectorAll('.payment-tab').forEach(tab => {
                tab.classList.remove('border-2', 'border-accent', 'bg-orange-50');
                tab.classList.add('border', 'border-gray-200', 'bg-white');
                const textSpan = tab.querySelector('span');
                textSpan.classList.remove('text-gray-800');
                textSpan.classList.add('text-gray-500');
            });
            if (this.checked) {
                const activeTab = this.closest('.payment-tab');
                activeTab.classList.remove('border', 'border-gray-200', 'bg-white');
                activeTab.classList.add('border-2', 'border-accent', 'bg-orange-50');
                const textSpan = activeTab.querySelector('span');
                textSpan.classList.remove('text-gray-500');
                textSpan.classList.add('text-gray-800');
            }
        });
    });
    const firstPkg = document.querySelector('input[name="package_id"]:checked');
    if (firstPkg) firstPkg.dispatchEvent(new Event('change'));
    const firstPay = document.querySelector('input[name="payment_method"]:checked');
    if (firstPay) firstPay.dispatchEvent(new Event('change'));
});
function updateQty(change) {
    const input = document.getElementById('qtyInput');
    if (!input) return;
    let newVal = parseInt(input.value) + change;
    if (newVal >= 1 && newVal <= 10) input.value = newVal;
}
const playerCheckButton = document.getElementById('checkPlayerName');
if (playerCheckButton) {
    playerCheckButton.addEventListener('click', async function () {
        const input = document.querySelector('input[name="player_id"]');
        const result = document.getElementById('playerNameResult');
        if (!input || !input.value.trim()) { result.textContent = 'আগে Player ID লিখুন।'; result.className = 'text-center text-sm font-bold mt-2 text-red-600'; result.classList.remove('hidden'); return; }
        result.textContent = '';
        result.classList.add('hidden');
        playerCheckButton.disabled = true;
        playerCheckButton.textContent = 'Checking...';
        try {
            const fd = new FormData(); fd.append('player_id', input.value.trim()); fd.append('game_id', playerCheckButton.dataset.gameId);
            const response = await fetch('ajax/check-player-id.php', {method:'POST', body:fd, headers:{'Accept':'application/json'}});
            const data = await response.json();
            if (data.status === 'success') {
                playerCheckButton.textContent = data.player_name;
                playerCheckButton.title = data.player_name;
                result.classList.add('hidden');
            } else {
                result.textContent = data.message || 'Player name not found.';
                result.className = 'text-center text-sm font-bold mt-2 text-red-600';
                result.classList.remove('hidden');
            }
        } catch (e) { result.textContent = 'API is unavailable. Please try again.'; result.className = 'text-center text-sm font-bold mt-2 text-red-600'; result.classList.remove('hidden'); }
        playerCheckButton.disabled = false;
        if (!playerCheckButton.title) playerCheckButton.textContent = playerCheckButton.dataset.defaultLabel;
    });
}
</script>

<?php
require_once 'common/bottom-nav.php';
require_once 'common/footer.php';
?>
