<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../login.php'); exit; }
require_once __DIR__ . '/../config.php';

// Force Pakistan Timezone so the server stops using US time
date_default_timezone_set('Asia/Karachi'); 
$pdo->exec("SET time_zone = '+05:00';");

$uid = (int)$_SESSION['user_id'];
$deposit_alert = null;

if (isset($_SESSION['deposit_error'])) {
    $deposit_alert = ['type' => 'error', 'msg' => $_SESSION['deposit_error']];
    unset($_SESSION['deposit_error']);
}

// Fetch Global Settings
$settings_st = $pdo->query("SELECT setting_key, setting_value FROM admin_settings WHERE setting_key IN ('base_deposit_wager_multiplier', 'bonus_wager_multiplier', 'deposit_wager_multiplier', 'deposit_bonus_tiers', 'payment_routing')");
$settings = $settings_st->fetchAll(PDO::FETCH_KEY_PAIR);
$base_wager_multiplier = (float)($settings['base_deposit_wager_multiplier'] ?? 1);
$bonus_wager_multiplier = (float)($settings['bonus_wager_multiplier'] ?? ($settings['deposit_wager_multiplier'] ?? 1));
$bonus_tiers_json = $settings['deposit_bonus_tiers'] ?? '[]';
$bonus_tiers = json_decode($bonus_tiers_json, true) ?: [];

$routing = json_decode($settings['payment_routing'] ?? '{}', true);
if (empty($routing) || !isset($routing['gateways'])) {
    $routing = [
        'gateways' => [
            'lg_pay' => [
                'status' => 'active',
                'methods' => [
                    'easypaisa' => ['status' => 'active', 'code' => 'PKRPH-EASY', 'label' => 'Easypaisa'],
                    'jazzcash' => ['status' => 'active', 'code' => 'PKRPH', 'label' => 'Jazz Cash']
                ]
            ]
        ],
        'default_deposit_gateway' => 'lg_pay'
    ];
}

// Handle deposit form POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount'])) {
    $amount = (float)$_POST['amount'];
    $method_raw = $_POST['method'] ?? ''; // e.g. "lg_pay:PKRPH-EASY"

    $parts = explode(':', $method_raw);
    $gateway = $parts[0] ?? '';
    $method = $parts[1] ?? '';

    if (empty($method_raw) || count($parts) !== 2) {
        $deposit_alert = ['type' => 'error', 'msg' => 'Please select a valid payment method.'];
    } elseif ($amount < 300) {
        $deposit_alert = ['type' => 'error', 'msg' => 'Minimum deposit is Rs. 300.'];
    } elseif ($amount > 50000) {
        $deposit_alert = ['type' => 'error', 'msg' => 'Maximum deposit is Rs. 50,000.'];
    } else {
        $now_pkt = date('Y-m-d H:i:s'); // Exact PKT Time injection
        $is_demo = $_SESSION['is_demo'] ?? 0;
        if (!$is_demo) {
            $user_demo_check = (int)$pdo->query("SELECT is_demo FROM users WHERE id = $uid")->fetchColumn();
            if ($user_demo_check) $is_demo = 1;
        }

        if ($is_demo) {
            $order_id = "DEMO_" . time() . "_" . $uid . "_" . rand(1000, 9999);
            try {
                $pdo->beginTransaction();
                $pdo->prepare("INSERT INTO deposits (user_id, order_id, amount, method, status, created_at) VALUES(?,?,?,?,'approved',?)")
                    ->execute([$uid, $order_id, $amount, $method_raw, $now_pkt]);
                $pdo->prepare("UPDATE users SET balance = balance + ?, total_deposits = total_deposits + ? WHERE id = ?")
                    ->execute([$amount, $amount, $uid]);
                $pdo->commit();
                header('Location: deposit.php?status=return');
                exit;
            } catch (Exception $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                $deposit_alert = ['type' => 'error', 'msg' => 'Something went wrong. Please try again.'];
            }
        } else {
            $order_id = "EP_" . time() . "_" . $uid . "_" . rand(1000, 9999);
            try {
                // FORCE THE CREATED_AT DATE TO PAKISTAN TIME
                $pdo->prepare("INSERT INTO deposits (user_id, order_id, amount, method, created_at) VALUES(?,?,?,?,?)")
                    ->execute([$uid, $order_id, $amount, $method_raw, $now_pkt]);

                $_SESSION['tmp_deposit_order']  = $order_id;
                $_SESSION['tmp_deposit_amount'] = $amount;
                $_SESSION['tmp_deposit_gateway'] = $gateway;
                $_SESSION['tmp_deposit_method'] = $method;
                
                if ($gateway === 'lg_pay') {
                    header('Location: ../lg_pay_process.php');
                } else if ($gateway === 'io_pay') {
                    header('Location: ../io_pay_process.php');
                } else if ($gateway === 'go_pay') {
                    header('Location: ../gopay_process.php');
                } else if ($gateway === 'boom_pay') {
                    header('Location: ../boompay_process.php');
                }
                exit;
            } catch (Exception $e) {
                $deposit_alert = ['type' => 'error', 'msg' => 'Something went wrong. Please try again.'];
            }
        }
    }
}

// Fetch user balance
$u = $pdo->prepare("SELECT balance, wager, total_deposits FROM users WHERE id=?"); $u->execute([$uid]); $u=$u->fetch();
$balance      = (float)$u['balance'];
$wager        = (float)$u['wager'];
$withdrawable = ($wager <= 0) ? max(0, $balance) : 0;

// Recent deposits
$deps = $pdo->prepare("SELECT * FROM deposits WHERE user_id=? ORDER BY id DESC LIMIT 150"); 
$deps->execute([$uid]); 
$deps=$deps->fetchAll();

// Method display helper
function methodName($code) {
    if (strpos($code, ':') !== false) {
        $parts = explode(':', $code);
        $clean = $parts[1] ?? $code;
        if (stripos($clean, 'easy') !== false || $clean === 'PKRPH-EASY') return 'Easypaisa';
        if (stripos($clean, 'jazz') !== false || $clean === 'PKRPH') return 'Jazz Cash';
        if (stripos($clean, 'usdt') !== false) return 'USDT';
        return $clean;
    }
    return $code === 'PKRPH-EASY' ? 'Easypaisa' : ($code === 'PKRPH' ? 'Jazz Cash' : $code);
}

// Deposit Bonus Calculation Helper for History Display & Quick Tiles
function calculateBonus($amount, $date, $tiers) {
    if (strtotime($date) < strtotime('2026-05-15 00:00:00')) return 0;
    
    foreach ($tiers as $tier) {
        if ($amount >= $tier['min']) return $tier['bonus'];
    }
    return 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Deposit — PakClub</title>

<link rel="icon" href="../favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="../css/global.css">
<style>
/* --- Base Styles --- */
* { box-sizing: border-box; margin: 0; padding: 0; }
body { background: #160e0a; color: #fff; font-family: 'Segoe UI', sans-serif; max-width: 414px; margin: 0 auto; min-height: 100vh; position: relative; }

/* --- Header Wrapper (Hidden but Included) --- */
.header-wrapper { display: none; }

/* --- Top App Bar --- */
.app-header { background: #1a0f0a; padding: 14px 16px; display: flex; align-items: center; justify-content: space-between; position: sticky; top: 0; z-index: 10; border-bottom: 1px solid #2c1a12; }
.app-header .title { font-size: 17px; font-weight: 700; flex: 1; text-align: center; }
.hbtn { color: #fff; font-size: 18px; text-decoration: none; width: 32px; display: flex; justify-content: center; cursor: pointer; transition: color 0.2s; }
.hbtn-group { display: flex; gap: 8px; color: #a6958a; }
.hbtn-group .hbtn { color: #a6958a; }

/* --- Alerts --- */
.alert-box{padding:12px 15px;border-radius:12px;margin:12px 16px;font-size:13px;font-weight:600;display:flex;align-items:center;gap:10px;}
.alert-success{background:rgba(34,197,94,.12);color:#22c55e;border:1px solid rgba(34,197,94,.3)}
.alert-error{background:rgba(239,68,68,.1);color:#f87171;border:1px solid rgba(239,68,68,.3)}

/* --- Main Deposit Tab --- */
#depositTab { padding-bottom: 90px; }

/* --- Balance Cards --- */
.balance-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px; }
.bal-card { background: #2b221e; border: 1px solid #3c302a; border-radius: 12px; padding: 12px; }
.bal-label { font-size: 13px; color: #fff; font-weight: 600; margin-bottom: 12px; display: flex; align-items: center; gap: 6px; justify-content: center; }
.bal-label i { cursor: pointer; color: #a6958a; font-size: 12px; }
.bal-content { display: flex; align-items: center; justify-content: center; gap: 10px; }
.bal-icon { color: #5a4b43; font-size: 24px; }
.bal-val { font-size: 18px; font-weight: 800; color: #f59e0b; }
.bal-val-wd { color: #f59e0b; }

/* --- Form Section --- */
.section { padding: 0 16px; margin-bottom: 20px; }
.amount-hint { font-size: 13px; color: #fff; margin-bottom: 12px; }
.amount-input-wrap { background: #1a0f0a; border: 1px solid #3c302a; border-radius: 8px; display: flex; align-items: center; padding: 0 14px; margin-bottom: 10px; transition: border-color .3s; }
.amount-input-wrap:focus-within { border-color: #f26d0f; }
.amount-prefix { font-size: 15px; font-weight: 700; color: #fff; margin-right: 12px; padding: 14px 0; border-right: 1px solid #3c302a; padding-right: 12px; }
.amount-input { flex: 1; background: transparent; border: none; color: #fff; font-size: 16px; font-weight: 600; outline: none; padding: 14px 0; }
.amount-input::placeholder { color: #5a4b43; }
.amount-clear { color: #a6958a; font-size: 16px; cursor: pointer; padding: 14px 0; }
.net-amount { font-size: 12px; color: #fff; margin-bottom: 14px; font-weight: 600; }
.net-amount span { color: #f26d0f; }

/* Dynamic Wager Notice */
.wager-notice { font-size: 12px; color: #f59e0b; margin-bottom: 14px; font-weight: 600; background: #2b221e; padding: 10px 12px; border-radius: 6px; border: 1px solid #3c302a; display: none; align-items: center; gap: 8px; }
.wager-notice i { font-size: 14px; }

/* HIDE NUMBER INPUT ARROWS */
input[type=number]::-webkit-outer-spin-button,
input[type=number]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
input[type=number] {
    -moz-appearance: textfield; /* Firefox */
}

/* --- Quick Tiles & Badges --- */
.quick-tiles { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px 10px; margin-bottom: 24px; margin-top: 8px; }
.tile { background: #1a0f0a; border: 1px solid #3c302a; border-radius: 6px; padding: 16px 4px 10px 4px; text-align: center; font-size: 13px; font-weight: 600; color: #a6958a; cursor: pointer; transition: all .2s; position: relative; }
.tile:active, .tile.selected { background: #d97706; border-color: #d97706; color: #fff; }
.tile-badge { position: absolute; top: -1px; right: -1px; background: #f59e0b; color: #fff; font-size: 11px; font-weight: 700; padding: 3px 6px; border-bottom-left-radius: 8px; border-top-right-radius: 6px; z-index: 2; line-height: 1; }

/* --- Payment Methods --- */
.section-label { font-size: 14px; font-weight: 700; color: #fff; margin-bottom: 12px; display: block; }
.section-label span { color: #ef4444; }

.gateway-tabs { display: flex; gap: 8px; margin-bottom: 16px; background: #1a0f0a; padding: 4px; border-radius: 10px; border: 1px solid #3c302a; }
.gateway-tab { flex: 1; text-align: center; padding: 10px; border-radius: 6px; font-size: 14px; font-weight: 700; color: #8b7a70; cursor: pointer; transition: 0.3s; }
.gateway-tab.active { background: #d97706; color: #fff; }

.method-grid { display: flex; gap: 12px; margin-bottom: 24px; overflow-x: auto; padding-bottom: 5px; }
.method-card { background: #1a0f0a; border: 2px solid #3c302a; border-radius: 10px; padding: 10px 14px; display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 10px; cursor: pointer; transition: all .2s; min-width: 110px; position: relative; overflow: hidden; }
.method-card.active { border-color: #f26d0f; }
.method-card.active::after { content: '\f00c'; font-family: 'Font Awesome 6 Free'; font-weight: 900; color: #fff; background: #f26d0f; position: absolute; bottom: 0; right: 0; font-size: 10px; padding: 3px 5px 2px 6px; border-top-left-radius: 10px; }
.method-icon { width: 40px; height: 40px; background: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; padding: 6px; margin: 0 auto; }
.method-icon img { width: 100%; height: 100%; object-fit: contain; }
.method-name { font-size: 13px; font-weight: 600; color: #fff; text-align: center; }

.method-card.maintenance { opacity: 0.5; cursor: not-allowed; border-color: #3c302a !important; filter: grayscale(100%); }
.method-card.maintenance::after { display: none; }
.maint-badge { position: absolute; top: 0; width: 100%; background: rgba(239, 68, 68, 0.9); color: white; font-size: 10px; font-weight: 700; text-align: center; padding: 2px 0; z-index: 10; left: 0; text-transform: uppercase; }

/* --- Error States & Animations --- */
@keyframes shake {
    0%, 100% { transform: translateX(0); }
    20%, 60% { transform: translateX(-5px); }
    40%, 80% { transform: translateX(5px); }
}
.error-shake { animation: shake 0.4s ease-in-out; }
.error-border { border-color: #ef4444 !important; }

/* --- Text Sections & Promos --- */
.text-box { margin-bottom: 20px; }
.text-title { font-size: 13px; font-weight: 700; color: #fff; margin-bottom: 10px; }
.text-list { font-size: 12px; color: #a6958a; line-height: 1.6; list-style-type: decimal; padding-left: 14px; margin: 0; }
.text-para { font-size: 12px; color: #a6958a; line-height: 1.6; }
.promo-img { width: 100%; border-radius: 8px; display: block; margin-top: 10px; margin-bottom: 20px; }

/* --- Sticky Pay Button Wrapper --- */
.sticky-pay-wrapper { position: fixed; bottom: 0; left: 50%; transform: translateX(-50%); width: 100%; max-width: 414px; background: #160e0a; padding: 12px 16px; border-top: 1px solid #2c1a12; z-index: 100; }
.pay-btn { width: 100%; background: #d97706; color: #fff; border: none; border-radius: 30px; padding: 14px; font-size: 16px; font-weight: 700; cursor: pointer; transition: all .2s; }
.pay-btn:active { transform: scale(0.98); background: #b45309; }
.pay-btn:disabled { background: #4b3020; color: #8b7a70; cursor: not-allowed; }

/* --- History Tab & Cards --- */
#historyTab { display: none; padding-bottom: 30px; }
.hist-nav { display: flex; border-bottom: 1px solid #2c1a12; margin-bottom: 16px; }
.hist-nav-item { flex: 1; text-align: center; padding: 14px 0; font-size: 14px; color: #8b7a70; cursor: pointer; border-bottom: 2px solid transparent; transition: 0.2s; }
.hist-nav-item.active { color: #d97706; border-bottom-color: #d97706; }

.hist-summary { display: flex; justify-content: space-between; padding: 0 16px 12px 16px; font-size: 14px; color: #fff; font-weight: 600; }
.hist-summary .total-val { color: #f59e0b; font-weight: 500; }

.hist-card { background: #26160d; border-radius: 10px; padding: 16px; margin: 0 16px 12px 16px; display: flex; flex-direction: column; gap: 12px; }
.hist-card-top { display: flex; justify-content: space-between; align-items: flex-start; }
.hist-left-group { display: flex; gap: 12px; align-items: flex-start; }
.hist-icon { width: 34px; height: 34px; background: #d97706; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 18px; flex-shrink: 0; }
.hist-details { display: flex; flex-direction: column; gap: 6px; }
.hist-date { color: #d97706; font-size: 13px; font-weight: 500; }
.hist-order { color: #d1d5db; font-size: 13px; display: flex; align-items: center; gap: 6px; }
.hist-order i { color: #8b7a70; cursor: pointer; font-size: 14px; }
.hist-method { color: #d1d5db; font-size: 13px; }

.hist-amounts { text-align: right; display: flex; flex-direction: column; gap: 6px; }
.hist-bal { color: #f59e0b; font-size: 13px; font-weight: 500; }
.hist-bonus { color: #22c55e; font-size: 13px; }
.hist-status { color: #fff; font-size: 13px; font-weight: 600; }

.no-more { text-align: center; color: #8b7a70; font-size: 14px; padding: 20px 0; display: none; }
.empty-msg { text-align: center; color: #8b7a70; font-size: 14px; padding: 40px 0; font-weight: 600; display: none; }

/* --- Toast --- */
.toast { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background: rgba(20,20,20,.95); border: 1px solid #3c302a; color: #fff; padding: 12px 24px; border-radius: 30px; font-size: 13px; font-weight: 600; display: none; z-index: 9999; white-space: nowrap; box-shadow: 0 4px 12px rgba(0,0,0,0.5); }
</style>
</head>
<body>

<div class="header-wrapper">
    <?php @require_once __DIR__ . '/../external/header.php'; ?>
</div>

<div class="app-header">
    <a href="javascript:void(0)" onclick="handleBack()" class="hbtn"><i class="fa-solid fa-angle-left"></i></a>
    <div class="title" id="pageTitle">Deposit</div>
    <div class="hbtn-group">
        <a href="../support.php" class="hbtn"><i class="fa-solid fa-headset"></i></a>
        <a href="javascript:void(0)" class="hbtn" id="historyToggleBtn" onclick="toggleHistory()"><i class="fa-solid fa-file-invoice-dollar"></i></a>
    </div>
</div>

<?php if($deposit_alert): ?>
<div class="alert-box alert-<?= $deposit_alert['type'] ?>">
    <i class="fa <?= $deposit_alert['type']=='success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?>"></i>
    <?= htmlspecialchars($deposit_alert['msg']) ?>
</div>
<?php endif; ?>

<?php if(isset($_GET['err'])): ?>
<div class="alert-box alert-error"><i class="fa fa-exclamation-circle"></i> <?= htmlspecialchars($_GET['err']) ?></div>
<?php endif; ?>
<?php if(isset($_GET['status']) && $_GET['status']==='return'): ?>
<div class="alert-box alert-success"><i class="fa fa-check-circle"></i> Payment submitted! Balance will update shortly.</div>
<?php endif; ?>

<form method="POST" id="depositForm">
    <div id="depositTab">
        <div class="balance-row">
            <div class="bal-card">
                <div class="bal-label">Cash Balance <i class="fa-solid fa-rotate-right" onclick="refreshBal()"></i></div>
                <div class="bal-content">
                    <i class="fa-solid fa-wallet bal-icon"></i>
                    <div class="bal-val" id="balVal">Rs<?= number_format($balance,0) ?></div>
                </div>
            </div>
            <div class="bal-card">
                <div class="bal-label">Withdrawable</div>
                <div class="bal-content">
                    <i class="fa-solid fa-money-bill-transfer bal-icon"></i>
                    <div class="bal-val bal-val-wd" id="wdVal">Rs<?= number_format($withdrawable,0) ?></div>
                </div>
            </div>
        </div>

        <div class="section">
            <div class="amount-hint">Deposit amount: Min: Rs300 Max: Rs50,000</div>
            <div class="amount-input-wrap">
                <span class="amount-prefix">Rs</span>
                <input type="number" class="amount-input" name="amount" id="amountInput" placeholder="300" min="300" max="50000" oninput="calcNet()">
                <span class="amount-clear" onclick="clearAmt()"><i class="fa-regular fa-circle-xmark"></i></span>
            </div>
            
            <div class="net-amount">Net Amount Received <span id="netVal">Rs0</span></div>
            
            <div class="quick-tiles">
                <?php foreach([300, 500, 1000, 3000, 5000, 10000, 30000, 50000] as $v): 
                    $b = calculateBonus($v, date('Y-m-d H:i:s'), $bonus_tiers); 
                ?>
                <div class="tile" onclick="setAmt(<?= $v ?>)">
                    Rs<?= number_format($v) ?>
                    <?php if($b > 0): ?>
                        <div class="tile-badge">+<?= $b ?></div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="section">
            <?php 
            $defaultGateway = $routing['default_deposit_gateway'] ?? 'lg_pay';
            
            // Sort gateways so default is first
            $gateways = $routing['gateways'];
            uksort($gateways, function($a, $b) use ($defaultGateway) {
                if ($a === $defaultGateway) return -1;
                if ($b === $defaultGateway) return 1;
                return 0;
            });

            // Count active gateways
            $active_gateways_count = 0;
            foreach($gateways as $gw_data) {
                if ($gw_data['status'] === 'active') $active_gateways_count++;
            }
            ?>
            
            <?php if ($active_gateways_count > 1): ?>
                <label class="section-label">Payment Gateway <span>*</span></label>
                <div class="gateway-tabs">
                    <?php 
                    foreach($gateways as $gw_key => $gw_data): 
                        if($gw_data['status'] !== 'active') continue; 
                        $isActive = ($gw_key === $defaultGateway) ? 'active' : '';
                    ?>
                    <div class="gateway-tab <?= $isActive ?>" onclick="switchGateway('<?= $gw_key ?>', this)">
                        <?php 
                            if ($gw_key === 'lg_pay') echo 'LG-Pay';
                            elseif ($gw_key === 'io_pay') echo 'IO-Pay';
                            elseif ($gw_key === 'boom_pay') echo 'Woompay';
                            elseif ($gw_key === 'go_pay') echo 'GoPay';
                            else echo ucfirst(str_replace('_', ' ', $gw_key));
                        ?>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <label class="section-label" style="margin-top: <?= ($active_gateways_count > 1) ? '16px' : '0' ?>;">Payment Method <span>*</span></label>
            <?php 
            foreach($gateways as $gw_key => $gw_data): 
                if($gw_data['status'] !== 'active') continue; 
                $isGwActive = ($gw_key === $defaultGateway) ? 'flex' : 'none';
            ?>
            <div class="method-grid method-grid-container" id="grid_<?= $gw_key ?>" style="display: <?= $isGwActive ?>;">
                <?php foreach($gw_data['methods'] as $m_key => $m_data): 
                    $img = 'https://cryptologos.cc/logos/tether-usdt-logo.png';
                    if($m_key === 'easypaisa') $img = 'https://vectorseek.com/wp-content/uploads/2023/12/EASYPAISA-New-Logo-Vector.svg--300x161.png';
                    if($m_key === 'jazzcash') $img = 'https://iconape.com/wp-content/png_logo_vector/jazz-cash-logo.png';
                    
                    $val = $gw_key . ':' . $m_data['code'];
                    $js_id = str_replace(':', '_', $val);
                    $isMaint = ($m_data['status'] === 'maintenance');
                ?>
                <div class="method-card <?= $isMaint ? 'maintenance' : '' ?>" id="m-<?= $js_id ?>" onclick="<?= $isMaint ? 'toast(\'Method under maintenance\', false)' : "selectMethod(this,'$val', '$js_id')" ?>">
                    <?php if($isMaint): ?><div class="maint-badge">Maintenance</div><?php endif; ?>
                    <div class="method-icon"><img src="<?= $img ?>" alt="<?= htmlspecialchars($m_data['label']) ?>"></div>
                    <div class="method-name"><?= htmlspecialchars($m_data['label']) ?></div>
                </div>
                <input type="radio" name="method" id="radio_<?= $js_id ?>" value="<?= htmlspecialchars($val) ?>" style="display:none">
                <?php endforeach; ?>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="section">
            <div class="text-box">
                <div class="text-title">Deposit tips:</div>
                <ul class="text-list">
                    <li>Each deposit will be credited within 1-5 minutes</li>
                    <li>After the payment is successful, please return to the Pakclub deposit page to check your account balance.</li>
                    <li>If your deposit does not arrive within 30 minutes, please contact customer service for help.</li>
                </ul>
            </div>
            
            <div class="text-box">
                <div class="text-title">Important notes:</div>
                <div class="text-para">Please do not modify the payment amount. Avoid reusing saved QR codes or Easypaisa/Jazzcash accounts for multiple payments. Base deposits require a <?= $base_wager_multiplier ?>x wager. Bonus amounts require a <?= $bonus_wager_multiplier ?>x wager prior to withdrawal.</div>
            </div>
            
            <label class="section-label">You May Be Interested In <span>*</span></label>
            <img src="https://pakclub.bet/img/6004/other/022202582-31765-file_20260417142202564.webp" class="promo-img" alt="Deposit Promo">
        </div>
    </div>

    <div class="sticky-pay-wrapper" id="stickyPay">
        <button type="submit" class="pay-btn" id="payBtn">Pay now</button>
    </div>
</form>

<div id="historyTab">
    <div class="hist-nav">
        <div class="hist-nav-item active" id="filter-1d" onclick="filterHistory(1, this)">1 Day</div>
        <div class="hist-nav-item" onclick="filterHistory(7, this)">7 Days</div>
        <div class="hist-nav-item" onclick="filterHistory(30, this)">30 Days</div>
    </div>
    
    <div class="hist-summary">
        <div id="histDateRange">-- to --</div>
        <div>Total: <span class="total-val" id="histTotalVal">Rs0.00</span></div>
    </div>

    <div id="histList">
        <?php if($deps): foreach($deps as $d): 
            $st = strtolower($d['status']);
            $display_st = $st === 'approved' ? 'Completed' : ($st === 'rejected' ? 'Failed' : ucfirst($st));
            
            $oid = $d['order_id'] ?? ('RC' . date('ym', strtotime($d['created_at'])) . '...' . rand(1000,9999));
            $short_oid = strlen($oid) > 15 ? substr($oid, 0, 6).'…'.substr($oid, -6) : $oid;
            
            $timestamp = strtotime($d['created_at']) * 1000;
            $display_date = date('Y-m-d H:i:s', strtotime($d['created_at']));
            
            // Calculate assigned bonus
            $bonus = calculateBonus($d['amount'], $d['created_at'], $bonus_tiers);
        ?>
        <div class="hist-card" data-timestamp="<?= $timestamp ?>" data-amount="<?= $d['amount'] ?>" data-status="<?= $st ?>">
            <div class="hist-card-top">
                <div class="hist-left-group">
                    <div class="hist-icon"><i class="fa-solid fa-clock" style="transform: scaleX(-1);"></i></div>
                    <div class="hist-details">
                        <div class="hist-date"><?= $display_date ?></div>
                        <div class="hist-order">Order ID: <?= $short_oid ?> <i class="fa-regular fa-copy" onclick="copyToClipboard('<?= htmlspecialchars($oid) ?>')"></i></div>
                        <div class="hist-method">Method: <?= methodName($d['method']) ?></div>
                    </div>
                </div>
                <div class="hist-amounts">
                    <div class="hist-bal">Balance: + <?= number_format($d['amount'] + $bonus, 0) ?></div>
                    <div class="hist-bonus" style="color: <?= $bonus > 0 ? '#22c55e' : '#9ca3af' ?>;">
                        Bonus: <?= $bonus > 0 ? '+ '.number_format($bonus, 0) : '0' ?>
                    </div>
                    <div class="hist-status"><?= $display_st ?></div>
                </div>
            </div>
        </div>
        <?php endforeach; endif; ?>
        
        <div class="empty-msg" id="histEmpty">No deposit history found.</div>
        <div class="no-more" id="histNoMore">no more</div>
    </div>
</div>

<div class="toast" id="toast"></div>

<script>
let selMethod = '';

function switchGateway(gatewayKey, btn) {
    document.querySelectorAll('.gateway-tab').forEach(el => el.classList.remove('active'));
    btn.classList.add('active');
    
    document.querySelectorAll('.method-grid-container').forEach(el => el.style.display = 'none');
    document.getElementById('grid_' + gatewayKey).style.display = 'flex';
    
    // Clear selection when switching tabs
    selMethod = '';
    document.querySelectorAll('.method-card').forEach(el => el.classList.remove('active'));
}

document.addEventListener("DOMContentLoaded", () => {
    filterHistory(1, document.getElementById('filter-1d'));
});

function filterHistory(days, btnElement) {
    document.querySelectorAll('.hist-nav-item').forEach(el => el.classList.remove('active'));
    if(btnElement) btnElement.classList.add('active');
    
    const now = new Date();
    now.setHours(23, 59, 59, 999);
    
    const startDate = new Date();
    startDate.setDate(now.getDate() - (days - 1));
    startDate.setHours(0, 0, 0, 0);
    
    const pad = n => String(n).padStart(2, '0');
    const endYMD = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`;
    const startYMD = `${startDate.getFullYear()}-${pad(startDate.getMonth()+1)}-${pad(startDate.getDate())}`;
    
    let total = 0;
    let visibleCount = 0;
    
    document.querySelectorAll('.hist-card').forEach(card => {
        const cardTime = parseInt(card.getAttribute('data-timestamp'));
        
        if (cardTime >= startDate.getTime() && cardTime <= now.getTime()) {
            card.style.display = 'flex';
            visibleCount++;
            
            const status = card.getAttribute('data-status');
            if (status === 'approved' || status === 'completed') {
                total += parseFloat(card.getAttribute('data-amount'));
            }
        } else {
            card.style.display = 'none';
        }
    });
    
    document.getElementById('histDateRange').innerText = `${startYMD} to ${endYMD}`;
    document.getElementById('histTotalVal').innerText = 'Rs' + total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
    
    if (visibleCount === 0) {
        document.getElementById('histEmpty').style.display = 'block';
        document.getElementById('histNoMore').style.display = 'none';
    } else {
        document.getElementById('histEmpty').style.display = 'none';
        document.getElementById('histNoMore').style.display = 'block';
    }
}

function selectMethod(card, value, js_id) {
    document.querySelectorAll('.method-card').forEach(el => {
        el.classList.remove('active');
        el.classList.remove('error-border'); // Remove error state on selection
    });
    card.classList.add('active');
    selMethod = value;
    document.getElementById('radio_' + js_id).checked = true;
}

function setAmt(v) {
    document.getElementById('amountInput').value = v;
    document.querySelectorAll('.tile').forEach(t => t.classList.remove('selected'));
    event.target.classList.add('selected');
    calcNet();
}

function clearAmt() {
    document.getElementById('amountInput').value = '';
    document.querySelectorAll('.tile').forEach(t => t.classList.remove('selected'));
    calcNet();
}

const dynBonusTiers = <?= $bonus_tiers_json ?>;

function getBonusAmount(val) {
    if (new Date() < new Date('2026-05-15T00:00:00+05:00')) return 0;
    for (let i = 0; i < dynBonusTiers.length; i++) {
        if (val >= dynBonusTiers[i].min) return dynBonusTiers[i].bonus;
    }
    return 0;
}

function calcNet() {
    let val = parseFloat(document.getElementById('amountInput').value) || 0;
    
    // Clear error state if valid typing is detected
    if(val >= 300) {
        document.querySelector('.amount-input-wrap').classList.remove('error-border');
    }

    let bonus = getBonusAmount(val);
    let text = 'Rs' + (val + bonus).toLocaleString();
    
    if (bonus > 0) {
        text += ' (+ Rs' + bonus.toLocaleString() + ' bonus)';
    }
    
    document.getElementById('netVal').innerText = text;
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        toast('Order ID copied!');
    }).catch(err => {
        toast('Failed to copy', false);
    });
}

function toggleHistory() {
    const depTab = document.getElementById('depositTab');
    const histTab = document.getElementById('historyTab');
    const title = document.getElementById('pageTitle');
    const stickyPay = document.getElementById('stickyPay');
    const histBtn = document.getElementById('historyToggleBtn');
    
    if (histTab.style.display === 'block') {
        histTab.style.display = 'none';
        depTab.style.display = 'block';
        stickyPay.style.display = 'block';
        title.innerText = 'Deposit';
        histBtn.style.color = '#a6958a';
    } else {
        histTab.style.display = 'block';
        depTab.style.display = 'none';
        stickyPay.style.display = 'none';
        title.innerText = 'Deposit history';
        histBtn.style.color = '#fff';
    }
}

function handleBack() {
    const histTab = document.getElementById('historyTab');
    if (histTab.style.display === 'block') {
        toggleHistory();
    } else {
        window.location.href = '../index.php';
    }
}

function toast(m, ok=true) {
    const t = document.getElementById('toast');
    t.style.display = 'block';
    t.style.borderLeft = '4px solid ' + (ok ? '#22c55e' : '#ef4444');
    t.innerText = m;
    setTimeout(() => t.style.display = 'none', 2500);
}

function refreshBal() {
    fetch('../balance.php').then(r=>r.json()).then(d => {
        if(d.ok) {
            document.getElementById('balVal').innerText = 'Rs' + d.balance.toLocaleString();
            document.getElementById('wdVal').innerText = 'Rs' + d.withdrawable.toLocaleString();
            toast('Balance refreshed successfully');
        }
    });
}

document.getElementById('depositForm').addEventListener('submit', function(e) {
    e.preventDefault(); // Stop default submit to allow custom visual feedback
    
    let hasError = false;
    const amtWrap = document.querySelector('.amount-input-wrap');
    const methodCards = document.querySelectorAll('.method-card');
    const amt = parseFloat(document.getElementById('amountInput').value);

    // Reset visual errors and trigger reflow
    amtWrap.classList.remove('error-shake', 'error-border');
    methodCards.forEach(c => c.classList.remove('error-shake', 'error-border'));
    void amtWrap.offsetWidth;

    // Validate Amount
    if (!amt || amt < 300 || amt > 50000) {
        amtWrap.classList.add('error-shake', 'error-border');
        if (!amt || amt < 300) toast('Minimum deposit is Rs. 300', false);
        else toast('Maximum deposit is Rs. 50,000', false);
        hasError = true;
    }

    // Validate Method
    if (!selMethod) {
        methodCards.forEach(c => {
            void c.offsetWidth; // trigger reflow
            c.classList.add('error-shake', 'error-border');
        });
        if (!hasError) toast('Please select a payment method', false); // Avoid double-toast if both fail
        hasError = true;
    }

    if (hasError) return;
    
    // Proceed if all validations pass
    const btn = document.getElementById('payBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Processing…';
    
    this.submit(); // Trigger the actual form submission
});
</script>
</body>
</html>