<?php 
// Include Configuration
include 'common/config.php'; 
include 'common/header.php'; 

// ====================================================
// 1. AJAX HANDLERS
// ====================================================

// A. Handle Balance Refresh
if(isset($_GET['action']) && $_GET['action'] == 'get_balance') {
    header('Content-Type: application/json');
    if(isset($_SESSION['user_id'])) {
        $uid = $_SESSION['user_id'];
        $res = $conn->query("SELECT balance FROM users WHERE id=$uid");
        if ($res && $row = $res->fetch_assoc()) {
            echo json_encode(['balance' => (float)$row['balance']]);
        } else {
            echo json_encode(['balance' => 0]);
        }
    } else {
        echo json_encode(['balance' => 0]);
    }
    exit;
}

// B. Handle UID Check (HL Gaming + Fallback)
if(isset($_GET['action']) && $_GET['action'] == 'check_uid_api') {
    $uid = isset($_GET['uid']) ? trim($_GET['uid']) : '';
    
    if (empty($uid)) {
        echo json_encode(['error' => 'UID Required']);
        exit;
    }

    // --- CONFIGURATION ---
    $useruid = "YOUR_USER_UID"; 
    $apiKey = "YOUR_API_KEY";   
    $region = "bd";             

    // Primary API URL (HL Gaming)
    $primaryUrl = "https://proapis.hlgamingofficial.com/main/games/freefire/account/api?sectionName=AllData&PlayerUid=$uid&region=$region&useruid=$useruid&api=$apiKey";
    
    // Fallback API URL (bhauxinfo2)
    $fallbackUrl = "https://bhauxinfo2.vercel.app/bhau?uid=$uid&region=BD";

    // Helper Function
    function fetchUrl($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return ($httpCode == 200) ? $response : false;
    }

    // Try Primary API
    $response = fetchUrl($primaryUrl);
    $finalResponse = null;

    if ($response) {
        $data = json_decode($response, true);
        if (isset($data['result']['AccountInfo']['AccountName'])) {
            $finalResponse = json_encode(['name' => $data['result']['AccountInfo']['AccountName']]);
        }
    }

    // Try Fallback API if Primary Failed
    if (!$finalResponse) {
        $response = fetchUrl($fallbackUrl);
        if ($response) {
            $data = json_decode($response, true);
            if (isset($data['basicInfo']['nickname'])) {
                $finalResponse = json_encode(['name' => $data['basicInfo']['nickname']]);
            }
        }
    }

    // Output Result
    header('Content-Type: application/json');
    if ($finalResponse) {
        echo $finalResponse;
    } else {
        echo json_encode(['error' => 'Player Not Found']);
    }
    exit;
}

// ====================================================
// 2. PAGE LOAD LOGIC
// ====================================================

if(!isset($_GET['id'])) {
    echo "<script>window.location='index.php';</script>";
    exit;
}

$id = (int)$_GET['id'];
$game_query = $conn->query("SELECT * FROM games WHERE id=$id");

if(!$game_query || $game_query->num_rows === 0) {
    echo "<script>window.location='index.php';</script>";
    exit;
}

$game = $game_query->fetch_assoc();

// FIX: Normalize Game Type
$gameType = strtolower(trim($game['type']));

// Get Configuration for Subscription/UID
$hintText = !empty($game['hint_text']) ? $game['hint_text'] : 'এখানে গেমের আইডি কোড দিন';
$isUidCheckEnabled = isset($game['check_uid']) ? (int)$game['check_uid'] : 1; 

// CHECK: Ensure 'status' column exists in products table
if(isset($conn)) {
    $chk_st = $conn->query("SHOW COLUMNS FROM products LIKE 'status'");
    if($chk_st->num_rows == 0) {
        $conn->query("ALTER TABLE products ADD COLUMN status TINYINT DEFAULT 1");
    }
}

$products = $conn->query("SELECT * FROM products WHERE game_id=$id ORDER BY price ASC");

// Initial Balance
$user_balance = 0.00;
$is_logged_in = false;
if(isset($_SESSION['user_id'])) {
    $is_logged_in = true;
    $uid = $_SESSION['user_id'];
    $ub_res = $conn->query("SELECT balance FROM users WHERE id=$uid");
    if($ub_res && $row = $ub_res->fetch_assoc()){
        $user_balance = (float)$row['balance'];
    }
}

// Fetch Dynamic Primary Color
$db_primary_color = '#DC2626'; // Default
if(function_exists('getSetting')) {
    $db_color = getSetting($conn, 'primary_color');
    if(!empty($db_color)) {
        $db_primary_color = $db_color;
    }
}
?>

<link href="https://fonts.googleapis.com/css2?family=Bree+Serif&family=Noto+Serif+Bengali:wght@400;500;600;700&display=swap" rel="stylesheet">

<style>
    /* =========================================
       COLOR CONFIGURATION
       ========================================= */
    :root {
        --primary-blue: <?php echo $db_primary_color; ?>; 
        --dark-blue: #1e3a5f;
        --light-blue: #3b82f6;
        --red-tick: #dc2626;
    }

    body { background-color: #f4f6f9; font-family: 'Bree Serif', serif; padding-bottom: 80px; font-weight: normal; } 
    .font-bangla { font-family: 'Noto Serif Bengali', serif; }

    /* Number Badge */
    .step-badge {
        background-color: var(--primary-blue);
        color: white; 
        width: 26px; 
        height: 26px; 
        border-radius: 50%;
        display: inline-flex; 
        align-items: center; 
        justify-content: center;
        font-size: 14px; 
        font-weight: normal;
        margin-right: 10px;
    }

    /* Product Card */
    .pkg-card {
        background-color: white;
        border: 1px solid #e5e7eb;
        border-radius: 6px;
        transition: all 0.2s ease-in-out;
        min-height: 65px; 
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        position: relative;
    }
    
    .pkg-radio:checked + .pkg-card {
        border-color: var(--primary-blue);
        box-shadow: 0 0 0 1px var(--primary-blue);
        background-color: #f8fbff;
    }
    
    .pkg-title { color: var(--dark-blue); font-weight: normal; font-size: 14px; line-height: 1.2; margin-bottom: 3px; }
    .pkg-price { color: var(--primary-blue); font-weight: normal; font-size: 13px; }
    .pkg-stockout { color: var(--red-tick); font-weight: normal; font-size: 12px; margin-top: 2px; }

    /* Payment Method Styling */
    .pay-card { 
        border: 1px solid #e5e7eb; 
        background: white;
        border-radius: 4px;
        position: relative;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        height: 100%;
    }
    
    .pay-radio:checked + .pay-card { 
        border-color: #d1d5db; /* Keep border standard as per image */
    }
    
    .pay-radio:checked + .pay-card::before {
        content: ''; 
        position: absolute; 
        top: 0; left: 0; 
        width: 0; height: 0;
        border-style: solid; 
        border-width: 28px 28px 0 0;
        border-color: var(--red-tick) transparent transparent transparent; 
        z-index: 1;
    }
    
    .pay-radio:checked + .pay-card::after {
        content: '✓'; 
        position: absolute; 
        top: 2px; left: 4px;
        color: white; 
        font-size: 12px; 
        font-weight: normal; 
        z-index: 2;
        font-family: sans-serif;
    }

    .pay-bar {
        background-color: #cbd5e1;
        color: #475569;
        font-size: 11px;
        font-weight: normal;
        text-align: center;
        padding: 5px 0;
        margin-top: auto;
    }
    
    /* Errors */
    .error-msg-box {
        background-color: #fee2e2;
        border: 1px solid var(--red-tick);
        color: var(--red-tick);
        font-size: 12px;
        padding: 8px;
        border-radius: 4px;
        margin-top: 8px;
        display: none; 
        align-items: center;
        gap: 6px;
        font-family: 'Noto Serif Bengali', serif;
    }
    .input-error { border: 1px solid var(--red-tick) !important; background-color: #fef2f2; }
</style>

<div class="bg-white px-4 py-3 shadow-sm mb-4 flex items-center gap-4">
    <img src="<?php echo $game['image']; ?>" class="w-16 h-16 rounded border border-gray-200 object-cover shadow-sm">
    <div>
        <h1 class="text-xl font-normal text-[var(--dark-blue)] leading-tight"><?php echo $game['name']; ?></h1>
        <p class="text-sm text-gray-400 font-medium">Game / Top up</p>
    </div>
</div>

<form action="getway/sketpay/payemnt_create.php" method="POST" id="topupForm" class="container mx-auto px-3 max-w-lg" onsubmit="return validateForm(event)">
    <input type="hidden" name="game_id" value="<?php echo $game['id']; ?>">
    <input type="hidden" name="action" value="create_order">
    <input type="hidden" name="order_txid" id="orderTxid">
    
    <input type="hidden" name="amount" id="formAmount" value="0">
    <input type="hidden" name="cus_name" value="Customer">
    <input type="hidden" name="cus_email" value="customer@email.com">
    <input type="hidden" name="phone" value="01700000000">
    
    <div class="bg-white p-4 rounded shadow-sm border border-gray-100 mb-4">
        <h3 class="font-normal text-[16px] text-gray-800 mb-4 flex items-center border-b border-gray-100 pb-3">
            <span class="step-badge">1</span> Select Recharge
        </h3>
        
        <div class="grid grid-cols-2 gap-3">
            <?php while($prod = $products->fetch_assoc()): ?>
            <label class="cursor-pointer relative block select-none">
                <input type="radio" name="product_id" value="<?php echo $prod['id']; ?>" 
                       data-price="<?php echo $prod['price']; ?>" 
                       data-pname="<?php echo $prod['name']; ?>" 
                       class="pkg-radio sr-only" 
                       onchange="updateTotal()">
                
                <div class="pkg-card p-2">
                    <span class="pkg-title text-center block">
                        <?php echo htmlspecialchars($prod['name']); ?>
                    </span>
                    <span class="pkg-price text-center block">
                        BDT <?php echo number_format((float)$prod['price'], 0); ?>
                    </span>
                </div>
            </label>
            <?php endwhile; ?>
        </div>
        
        <div id="pkgError" class="error-msg-box mt-3">
            <i class="fa-solid fa-exclamation-circle"></i> অনুগ্রহ করে একটি প্যাকেজ সিলেক্ট করুন
        </div>
    </div>

    <div class="px-2 mb-4">
        <a href="#" class="text-[#e8437a] flex items-center gap-2 font-bangla text-[16px] font-medium hover:underline">
            <i class="fa-solid fa-external-link-alt"></i> কিভাবে অর্ডার করবেন ?
        </a>
    </div>

    <div class="bg-white p-4 rounded shadow-sm border border-gray-100 mb-4" id="accountInfoSection" style="<?php echo ($gameType == 'voucher') ? 'display:none;' : ''; ?>">
        <h3 class="font-normal text-[16px] text-gray-800 mb-4 flex items-center border-b border-gray-100 pb-3">
            <span class="step-badge">2</span> Account Info
        </h3>
        
        <div class="space-y-4">
            <div>
                <label class="text-sm text-[var(--dark-blue)] block mb-2 font-bangla" id="inputLabel">
                    <?php echo ($gameType == 'subscription') ? htmlspecialchars($hintText) : 'এখানে গেমের আইডি কোড দিন'; ?>
                </label>
                
                <input type="text" id="playerIdInput" name="player_id" 
                       placeholder="<?php echo ($gameType == 'subscription') ? 'Type here...' : 'এখানে গেমের আইডি কোড দিন'; ?>" 
                       class="w-full border border-gray-300 rounded p-3 text-sm font-bangla focus:outline-none focus:border-[var(--primary-blue)]" 
                       autocomplete="off">
                
                <div id="idError" class="error-msg-box mt-2">
                    <i class="fa-solid fa-exclamation-circle"></i> দয়া করে গেম আইডি দিন
                </div>
            </div>
            
            <?php if($gameType == 'uid' && $isUidCheckEnabled == 1): ?>
            <button type="button" id="btnCheckName" onclick="checkUidName()" class="w-full bg-[var(--primary-blue)] text-white py-3 rounded font-bangla text-[15px] hover:opacity-90 transition-opacity">
                আপনার গেম আইডির নাম চেক করুন
            </button>
            <?php endif; ?>
        </div>
    </div>

    <?php if($gameType == 'voucher'): ?>
        <input type="hidden" name="player_id" value="Voucher_Request_No_ID">
    <?php endif; ?>

    <div class="bg-white p-4 rounded shadow-sm border border-gray-100 mb-4">
        <h3 class="font-normal text-[16px] text-gray-800 mb-4 flex items-center border-b border-gray-100 pb-3">
            <span class="step-badge">3</span> Select one option
        </h3>

        <div class="grid grid-cols-2 gap-4 mb-4">
            <label class="cursor-pointer relative block h-28">
                <input type="radio" name="payment_method" value="wallet" checked class="pay-radio sr-only" onchange="toggleWalletCheck(true)">
                <div class="pay-card">
                    <div class="flex-1 flex items-center justify-center p-2 bg-white">
                        <img src="res/images/walletpay.png" class="w-full h-14 object-contain" alt="Wallet">
                    </div>
                    <div class="pay-bar">Wallet Pay</div>
                </div>
            </label>

            <label class="cursor-pointer relative block h-28">
                <input type="radio" name="payment_method" value="online" class="pay-radio sr-only" onchange="toggleWalletCheck(false)">
                <div class="pay-card">
                    <div class="flex-1 flex items-center justify-center p-2 bg-white">
                        <img src="res/images/instantpay.png" class="w-full h-14 object-contain" alt="Instant">
                    </div>
                    <div class="pay-bar">Instant Pay</div>
                </div>
            </label>
        </div>

        <div class="text-[13px] text-gray-500 space-y-2 mb-4">
            <p class="flex items-center gap-1.5 font-bangla">
                <i class="fa-solid fa-info-circle"></i> প্রোডাক্ট কিনতে আপনার প্রয়োজন <span class="text-[var(--primary-blue)] font-normal px-1" id="neededPrice">0</span> টাকা।
            </p>
            
            <?php if(!$is_logged_in): ?>
                <p class="flex items-center gap-1.5 font-normal" style="color: #e58d20;">
                    <i class="fa-solid fa-info-circle"></i> Please Login To Purchase
                </p>
            <?php else: ?>
                <p class="flex items-center gap-1.5 font-bangla">
                    <i class="fa-solid fa-info-circle"></i> আপনার ওয়ালেট ব্যালেন্স: <span class="font-normal text-[var(--primary-blue)] px-1">৳ <span id="userBalanceDisplay"><?php echo number_format($user_balance, 2); ?></span></span>
                </p>
            <?php endif; ?>
            
            <div id="balanceError" class="error-msg-box">
                <i class="fa-solid fa-exclamation-circle"></i> আপনার ওয়ালেটে পর্যাপ্ত ব্যালেন্স নেই!
            </div>
        </div>

        <?php if(!$is_logged_in): ?>
            <a href="login.php" class="block w-full text-center bg-[var(--primary-blue)] hover:opacity-90 text-white font-normal py-3 rounded shadow-sm transition-all text-base">
                Login
            </a>
        <?php else: ?>
            <button type="submit" id="mainSubmitBtn" class="w-full bg-[var(--primary-blue)] hover:opacity-90 text-white font-normal py-3 rounded shadow-sm transition-all text-base">
                Buy Now
            </button>
        <?php endif; ?>
    </div>

    <div class="bg-white rounded shadow-sm border border-gray-100 mb-8 overflow-hidden">
        <div class="bg-gray-50 px-4 py-3 border-b border-gray-100">
            <h3 class="text-gray-800 text-lg font-normal">Rules & Conditions</h3>
        </div>
        <div class="p-4 text-sm text-gray-700 font-normal" style="font-family: system-ui, -apple-system, sans-serif; white-space: pre-line; word-wrap: break-word;">
            <?php 
            if(!empty($game['description'])) {
                echo htmlspecialchars(trim($game['description'])); 
            } else {
                echo "No rules found.";
            }
            ?>
        </div>
    </div>
</form>

<div id="confirmPopup" class="fixed inset-0 hidden z-[999] flex items-center justify-center bg-black/60 px-4">
    <div class="bg-white rounded-lg p-6 shadow-2xl relative w-full max-w-sm">
        <div class="w-full flex flex-col items-center justify-center text-center">
            <h2 class="text-xl font-normal mb-4 text-gray-800">Confirm Purchase</h2>
            <div id="confirmDetails" class="text-gray-600 text-sm mb-6 leading-relaxed bg-gray-50 w-full p-4 rounded border border-gray-100"></div>
            <div class="flex gap-3 w-full">
                <button onclick="closeConfirm()" class="flex-1 py-2.5 rounded font-normal text-gray-700 bg-gray-200 hover:bg-gray-300">Cancel</button>
                <button onclick="submitFinalForm()" class="flex-1 py-2.5 rounded font-normal text-white bg-[var(--primary-blue)] hover:opacity-90">Confirm</button>
            </div>
        </div>
    </div>
</div>

<script>
    let currentPrice = 0;
    let selectedPackageName = "";
    let userBalance = <?php echo $user_balance; ?>;
    let isWalletSelected = true;

    function generateTXID() {
        const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
        let result = '';
        for (let i = 0; i < 10; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    }

    function checkUidName() {
        const uidInput = document.getElementById('playerIdInput');
        const btn = document.getElementById('btnCheckName');
        
        if(!uidInput) return;

        const uid = uidInput.value.trim();

        if(uid === "") {
            document.getElementById('idError').style.display = 'flex';
            uidInput.classList.add('input-error');
            return;
        }

        btn.innerHTML = 'Checking...';
        btn.disabled = true;

        fetch('game_detail.php?action=check_uid_api&uid=' + uid)
            .then(response => response.json())
            .then(data => {
                let foundName = "";
                
                if(data.name) {
                    foundName = data.name;
                } else if(data.basicInfo && data.basicInfo.nickname) {
                    foundName = data.basicInfo.nickname;
                } else if(data.nickname) {
                    foundName = data.nickname;
                } else if(data.PlayerName) {
                    foundName = data.PlayerName;
                }

                if (foundName) {
                    btn.innerHTML = foundName;
                } else {
                    btn.innerHTML = 'Player Not Found';
                    setTimeout(() => {
                        btn.innerHTML = 'আপনার গেম আইডির নাম চেক করুন';
                        btn.disabled = false;
                    }, 3000);
                }
            })
            .catch(error => {
                btn.innerHTML = 'Error Checking';
                setTimeout(() => {
                    btn.innerHTML = 'আপনার গেম আইডির নাম চেক করুন';
                    btn.disabled = false;
                }, 3000);
            });
    }

    function updateTotal() {
        const radios = document.getElementsByName('product_id');
        for(let r of radios) {
            if(r.checked) {
                currentPrice = parseFloat(r.getAttribute('data-price'));
                selectedPackageName = r.getAttribute('data-pname');
                break;
            }
        }
        const needed = document.getElementById('neededPrice');
        if(needed) needed.innerText = currentPrice;
        
        const formAmount = document.getElementById('formAmount');
        if(formAmount) formAmount.value = currentPrice;
        
        const err = document.getElementById('pkgError');
        if(err) err.style.display = 'none';
    }

    function toggleWalletCheck(isWallet) {
        isWalletSelected = isWallet;
        const balErr = document.getElementById('balanceError');
        if(balErr) balErr.style.display = 'none';
    }

    function validateForm(e) {
        e.preventDefault();
        
        <?php if(!$is_logged_in): ?>
            window.location.href = 'login.php';
            return false;
        <?php endif; ?>

        let valid = true;
        document.querySelectorAll('.error-msg-box').forEach(el => el.style.display = 'none');
        document.querySelectorAll('.input-error').forEach(el => el.classList.remove('input-error'));
        
        if(currentPrice === 0) {
            const pkgErr = document.getElementById('pkgError');
            if(pkgErr) pkgErr.style.display = 'flex';
            valid = false;
        }

        const playerId = document.getElementById('playerIdInput');
        if(playerId && document.body.contains(playerId) && playerId.offsetParent !== null) {
            if(playerId.value.trim() === "") {
                const idErr = document.getElementById('idError');
                if(idErr) idErr.style.display = 'flex';
                playerId.classList.add('input-error');
                valid = false;
            }
        }

        if(isWalletSelected && userBalance < currentPrice) {
            const balErr = document.getElementById('balanceError');
            if(balErr) balErr.style.display = 'flex';
            valid = false;
        }

        if(valid) {
            if(isWalletSelected) {
                const pidVal = (playerId && playerId.offsetParent !== null) ? playerId.value : 'N/A';
                document.getElementById('confirmDetails').innerHTML = `
                    <div class="flex justify-between border-b pb-2 mb-2"><span>Package:</span> <span>${selectedPackageName}</span></div>
                    <div class="flex justify-between border-b pb-2 mb-2"><span>Total Price:</span> <span>৳${currentPrice}</span></div>
                    <div class="flex justify-between"><span>Player ID:</span> <span>${pidVal}</span></div>
                `;
                document.getElementById('confirmPopup').classList.remove('hidden');
            } else {
                const orderTx = document.getElementById('orderTxid');
                if(orderTx) orderTx.value = generateTXID();
                
                const form = document.getElementById('topupForm');
                form.action = 'getway/sketpay/payemnt_create.php';
                
                const btn = document.getElementById('mainSubmitBtn');
                if(btn) btn.disabled = true;
                
                form.submit();
            }
        }
        return false;
    }

    function closeConfirm() {
        document.getElementById('confirmPopup').classList.add('hidden');
    }

    function submitFinalForm() {
        const orderTx = document.getElementById('orderTxid');
        if(orderTx) orderTx.value = generateTXID();
        
        const form = document.getElementById('topupForm');
        form.action = 'order.php';
        
        const btn = document.getElementById('mainSubmitBtn');
        if(btn) btn.disabled = true;
        
        form.submit();
    }
    
    // Initialize
    updateTotal();
</script>

<?php 
include 'common/footer.php'; 
include 'common/bottom.php'; 
?>
