<?php
/**
 * User Deposit Page - Automatic UPI Deposit System
 * Multi-step flow: Enter Amount → QR/UPI Payment → Submit UTR → Auto-Verify
 */
$pageTitle = 'Deposit';
require_once 'includes/header.php';

// Get UPI settings
$upiId = getSetting('upi_id', 'merchant@upi');
$merchantName = getSetting('upi_merchant_name', 'Merchant');
$minDeposit = (float)getSetting('upi_min_deposit', 100);
$maxDeposit = (float)getSetting('upi_max_deposit', 100000);
$upiStatus = getSetting('upi_status', 'active');

// Get existing pending payment
$pendingPayment = dbFetch(
    "SELECT * FROM upi_payments WHERE user_id = :uid AND status = 'pending' AND expires_at > NOW() ORDER BY created_at DESC LIMIT 1",
    ['uid' => $user['id']]
);

// Get deposit history
$deposits = dbFetchAll(
    "SELECT p.*, 
            CASE WHEN p.auto_verified = 1 THEN 'Auto' ELSE 'Manual' END as verify_type
     FROM upi_payments p 
     WHERE p.user_id = :uid 
     ORDER BY p.created_at DESC 
     LIMIT 20",
    ['uid' => $user['id']]
);

// Bonus info
$bonusEnabled = getSetting('deposit_bonus_enabled', '0') === '1';
$bonusTiers = [];
if ($bonusEnabled) {
    $bonusTiers = dbFetchAll("SELECT * FROM deposit_bonus_tiers WHERE status = 'active' ORDER BY min_amount ASC");
}
?>
<style>
/* ===== Deposit Page Styles ===== */
.deposit-container { max-width: 680px; margin: 0 auto; }

/* Tabs */
.deposit-tabs { display: flex; gap: 4px; margin-bottom: 24px; background: var(--bg-secondary); border-radius: 12px; padding: 4px; }
.tab-btn { flex: 1; padding: 12px; text-align: center; border: none; background: transparent; color: var(--text-secondary); border-radius: 10px; font-weight: 600; font-size: .9rem; cursor: pointer; transition: all .2s; }
.tab-btn.active { background: var(--accent-green); color: #000; }
.tab-content { display: none; }
.tab-content.active { display: block; }

/* Step Wizard */
.steps-bar { display: flex; align-items: center; margin-bottom: 28px; padding: 0 8px; }
.step-item { display: flex; align-items: center; gap: 8px; flex: 1; }
.step-num { width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: .85rem; background: var(--bg-tertiary); color: var(--text-muted); border: 2px solid var(--border-color); transition: all .3s; flex-shrink: 0; }
.step-item.active .step-num { background: var(--accent-green); color: #000; border-color: var(--accent-green); box-shadow: 0 0 12px rgba(0,208,156,.35); }
.step-item.done .step-num { background: var(--accent-green); color: #000; border-color: var(--accent-green); }
.step-label { font-size: .78rem; color: var(--text-muted); white-space: nowrap; }
.step-item.active .step-label, .step-item.done .step-label { color: var(--text-primary); }
.step-line { flex: 0 0 auto; width: 30px; height: 2px; background: var(--border-color); margin: 0 4px; }
.step-line.done { background: var(--accent-green); }

.step-panel { display: none; animation: fadeIn .3s ease; }
.step-panel.active { display: block; }

/* Amount Preset Buttons */
.amount-presets { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin-bottom: 16px; }
.preset-btn { padding: 12px 8px; border: 1px solid var(--border-color); border-radius: 10px; background: var(--bg-secondary); color: var(--text-primary); font-weight: 600; font-size: .95rem; cursor: pointer; transition: all .2s; text-align: center; }
.preset-btn:hover { border-color: var(--accent-green); background: rgba(0,208,156,.08); }
.preset-btn.selected { border-color: var(--accent-green); background: rgba(0,208,156,.12); color: var(--accent-green); }

/* Amount Input */
.amount-input-wrap { position: relative; margin-bottom: 12px; }
.amount-input-wrap .currency-symbol { position: absolute; left: 14px; top: 50%; transform: translateY(-50%); font-size: 1.3rem; font-weight: 700; color: var(--accent-green); }
.amount-input-wrap input { width: 100%; padding: 16px 16px 16px 40px; font-size: 1.4rem; font-weight: 700; background: var(--bg-primary); border: 2px solid var(--border-color); border-radius: 12px; color: var(--text-primary); outline: none; transition: border-color .2s; }
.amount-input-wrap input:focus { border-color: var(--accent-green); }
.amount-limits { display: flex; justify-content: space-between; font-size: .8rem; color: var(--text-muted); margin-bottom: 20px; }

/* Bonus Banner */
.bonus-banner { background: linear-gradient(135deg, rgba(251,191,36,.12), rgba(251,191,36,.04)); border: 1px solid rgba(251,191,36,.25); border-radius: 12px; padding: 14px 16px; margin-bottom: 20px; display: flex; align-items: center; gap: 12px; }
.bonus-banner i { font-size: 1.5rem; color: var(--accent-yellow); }
.bonus-banner .bonus-text { font-size: .85rem; color: var(--text-secondary); }
.bonus-banner .bonus-text strong { color: var(--accent-yellow); }

/* QR Section */
.qr-payment-area { text-align: center; }
.qr-container { background: #fff; border-radius: 16px; padding: 20px; display: inline-block; margin: 16px auto; box-shadow: 0 4px 20px rgba(0,0,0,.15); }
.qr-container img { width: 220px; height: 220px; border-radius: 8px; }
.payment-info { background: var(--bg-secondary); border-radius: 12px; padding: 16px; margin: 16px 0; text-align: left; }
.payment-info-row { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid var(--border-color); }
.payment-info-row:last-child { border-bottom: none; }
.payment-info-row .label { color: var(--text-muted); font-size: .85rem; }
.payment-info-row .value { font-weight: 600; font-size: .95rem; }
.payment-info-row .value.amount-highlight { color: var(--accent-green); font-size: 1.1rem; }

/* UPI App Buttons */
.upi-apps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin: 16px 0; }
.upi-app-btn { display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 14px 8px; border: 1px solid var(--border-color); border-radius: 12px; background: var(--bg-secondary); cursor: pointer; transition: all .2s; text-decoration: none; color: var(--text-primary); }
.upi-app-btn:hover { border-color: var(--accent-green); background: rgba(0,208,156,.06); transform: translateY(-2px); }
.upi-app-btn img { width: 36px; height: 36px; border-radius: 8px; }
.upi-app-btn span { font-size: .78rem; font-weight: 600; }

/* Timer */
.timer-section { display: flex; align-items: center; justify-content: center; gap: 8px; margin: 14px 0; padding: 10px; background: rgba(255,71,87,.08); border: 1px solid rgba(255,71,87,.2); border-radius: 10px; }
.timer-section i { color: var(--accent-red); }
.timer-section .timer-text { font-size: .9rem; color: var(--accent-red); font-weight: 600; font-family: var(--font-mono); }

/* UTR Form */
.utr-input-section { margin-top: 20px; }
.utr-input-wrapper { position: relative; }
.utr-input-wrapper input { width: 100%; padding: 14px 16px; font-size: 1rem; font-family: var(--font-mono); letter-spacing: 1px; background: var(--bg-primary); border: 2px solid var(--border-color); border-radius: 12px; color: var(--text-primary); outline: none; transition: border-color .2s; }
.utr-input-wrapper input:focus { border-color: var(--accent-green); }
.utr-input-wrapper .utr-status { position: absolute; right: 14px; top: 50%; transform: translateY(-50%); font-size: 1.1rem; }

/* Result card */
.verify-result { text-align: center; padding: 24px; animation: fadeIn .4s ease; }
.verify-result .result-icon { font-size: 3.5rem; margin-bottom: 16px; }
.verify-result .result-icon.success { color: var(--accent-green); }
.verify-result .result-icon.error { color: var(--accent-red); }
.verify-result .result-title { font-size: 1.2rem; font-weight: 700; margin-bottom: 8px; }
.verify-result .result-amount { font-size: 1.8rem; font-weight: 700; color: var(--accent-green); margin: 12px 0; }

/* History table */
.deposit-history-item { display: flex; align-items: center; justify-content: space-between; padding: 14px 0; border-bottom: 1px solid var(--border-color); }
.deposit-history-item:last-child { border-bottom: none; }
.dh-left { display: flex; align-items: center; gap: 12px; }
.dh-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1rem; }
.dh-icon.completed { background: rgba(0,208,156,.12); color: var(--accent-green); }
.dh-icon.pending { background: rgba(251,191,36,.12); color: var(--accent-yellow); }
.dh-icon.failed { background: rgba(255,71,87,.12); color: var(--accent-red); }
.dh-ref { font-size: .78rem; color: var(--text-muted); font-family: var(--font-mono); }
.dh-date { font-size: .78rem; color: var(--text-muted); }
.dh-right { text-align: right; }
.dh-amount { font-weight: 700; font-size: 1rem; }
.dh-status { font-size: .72rem; font-weight: 600; padding: 2px 8px; border-radius: 20px; }
.dh-status.completed { background: rgba(0,208,156,.12); color: var(--accent-green); }
.dh-status.pending { background: rgba(251,191,36,.12); color: var(--accent-yellow); }
.dh-status.failed, .dh-status.expired { background: rgba(255,71,87,.12); color: var(--accent-red); }
.empty-state { text-align: center; padding: 40px; color: var(--text-muted); }
.empty-state i { font-size: 2.5rem; margin-bottom: 12px; opacity: .4; }

/* Animations */
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
@keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.05); } }

/* Loader */
.btn-loading { pointer-events: none; opacity: .7; }
.btn-loading .btn-text { display: none; }
.btn-loading .btn-loader { display: inline-block; }
.btn-loader { display: none; }
.spinner { width: 18px; height: 18px; border: 2px solid rgba(0,0,0,.2); border-top-color: #000; border-radius: 50%; animation: spin .6s linear infinite; display: inline-block; }
@keyframes spin { to { transform: rotate(360deg); } }

@media (max-width: 600px) {
    .amount-presets { grid-template-columns: repeat(2, 1fr); }
    .upi-apps { grid-template-columns: repeat(3, 1fr); }
    .steps-bar { padding: 0; }
    .step-label { display: none; }
    .step-line { width: 20px; }
    .qr-container img { width: 180px; height: 180px; }
}
</style>

<div class="deposit-container">
    <!-- Tabs -->
    <div class="deposit-tabs">
        <button class="tab-btn active" onclick="switchTab('deposit')">
            <i class="fas fa-plus-circle"></i> New Deposit
        </button>
        <button class="tab-btn" onclick="switchTab('history')">
            <i class="fas fa-clock"></i> History
        </button>
    </div>

    <!-- ==================== DEPOSIT TAB ==================== -->
    <div id="tab-deposit" class="tab-content active">
        
        <!-- Step Indicators -->
        <div class="steps-bar">
            <div class="step-item active" id="step-ind-1"><div class="step-num">1</div><span class="step-label">Amount</span></div>
            <div class="step-line" id="step-line-1"></div>
            <div class="step-item" id="step-ind-2"><div class="step-num">2</div><span class="step-label">Pay</span></div>
            <div class="step-line" id="step-line-2"></div>
            <div class="step-item" id="step-ind-3"><div class="step-num">3</div><span class="step-label">UTR</span></div>
            <div class="step-line" id="step-line-3"></div>
            <div class="step-item" id="step-ind-4"><div class="step-num">4</div><span class="step-label">Done</span></div>
        </div>

        <!-- ===== STEP 1: Enter Amount ===== -->
        <div class="step-panel active" id="step-1">
            <div class="card">
                <div class="card-title"><i class="fas fa-coins" style="color:var(--accent-yellow);margin-right:8px"></i>Enter Deposit Amount</div>
                
                <?php if ($upiStatus !== 'active'): ?>
                    <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> UPI deposits are currently disabled. Please try again later.</div>
                <?php else: ?>
                
                <!-- Preset Amounts -->
                <div class="amount-presets">
                    <button class="preset-btn" onclick="setAmount(100)">₹100</button>
                    <button class="preset-btn" onclick="setAmount(200)">₹200</button>
                    <button class="preset-btn" onclick="setAmount(500)">₹500</button>
                    <button class="preset-btn" onclick="setAmount(1000)">₹1,000</button>
                    <button class="preset-btn" onclick="setAmount(2000)">₹2,000</button>
                    <button class="preset-btn" onclick="setAmount(5000)">₹5,000</button>
                    <button class="preset-btn" onclick="setAmount(10000)">₹10,000</button>
                    <button class="preset-btn" onclick="setAmount(25000)">₹25,000</button>
                </div>
                
                <!-- Custom Amount -->
                <div class="amount-input-wrap">
                    <span class="currency-symbol">₹</span>
                    <input type="number" id="depositAmount" placeholder="Enter amount" min="<?= $minDeposit ?>" max="<?= $maxDeposit ?>" step="1">
                </div>
                <div class="amount-limits">
                    <span>Min: ₹<?= number_format($minDeposit) ?></span>
                    <span>Max: ₹<?= number_format($maxDeposit) ?></span>
                </div>
                
                <?php if ($bonusEnabled && !empty($bonusTiers)): ?>
                <div class="bonus-banner">
                    <i class="fas fa-gift"></i>
                    <div class="bonus-text">
                        <strong>Deposit Bonus!</strong><br>
                        <?php foreach ($bonusTiers as $tier): ?>
                            ₹<?= number_format($tier['min_amount']) ?>+ → <strong><?= $tier['bonus_percent'] ?>%</strong> &nbsp;
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <div id="bonusPreview" style="display:none" class="alert alert-success">
                    <i class="fas fa-gift"></i> <span id="bonusText"></span>
                </div>
                
                <button class="btn btn-primary btn-block" onclick="createPayment()" id="btnCreatePayment" style="padding:14px;font-size:1rem">
                    <span class="btn-text"><i class="fas fa-arrow-right"></i> Continue to Payment</span>
                    <span class="btn-loader"><span class="spinner"></span></span>
                </button>
                
                <?php endif; ?>
            </div>
        </div>

        <!-- ===== STEP 2: QR Code & Pay ===== -->
        <div class="step-panel" id="step-2">
            <div class="card">
                <div class="qr-payment-area">
                    <h3 style="margin-bottom:4px"><i class="fas fa-qrcode" style="color:var(--accent-green)"></i> Scan & Pay</h3>
                    <p style="color:var(--text-muted);font-size:.85rem;margin-bottom:8px">Scan with any UPI app to pay</p>
                    
                    <!-- Timer -->
                    <div class="timer-section">
                        <i class="fas fa-clock"></i>
                        <span class="timer-text" id="paymentTimer">10:00</span>
                        <span style="font-size:.8rem;color:var(--text-muted)">remaining</span>
                    </div>
                    
                    <!-- QR Code -->
                    <div class="qr-container" style="margin-bottom: 8px; padding: 12px;">
                        <img id="qrCodeImage" src="" alt="UPI QR Code" crossorigin="anonymous">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <button class="btn btn-sm" style="background:var(--bg-secondary);color:var(--text-primary);border:1px solid var(--border-color);border-radius:8px" onclick="downloadQR()">
                            <i class="fas fa-download"></i> Download QR Code
                        </button>
                    </div>
                    
                    <!-- Payment Info -->
                    <div class="payment-info">
                        <div class="payment-info-row">
                            <span class="label">Amount</span>
                            <span class="value amount-highlight" id="payAmountDisplay">₹0.00</span>
                        </div>
                        <div class="payment-info-row">
                            <span class="label">UPI ID</span>
                            <span class="value" style="font-family:var(--font-mono);font-size:.85rem" id="payUpiIdDisplay"><?= htmlspecialchars($upiId) ?></span>
                        </div>
                        <div class="payment-info-row">
                            <span class="label">Reference</span>
                            <span class="value" style="font-family:var(--font-mono);font-size:.82rem;color:var(--text-secondary)" id="payRefDisplay">-</span>
                        </div>
                    </div>
                    
                    <!-- UPI App Deep Links -->
                    <p style="color:var(--text-muted);font-size:.82rem;margin-bottom:10px">Or pay directly with:</p>
                    <div class="upi-apps">
                        <a href="#" id="gpayLink" class="upi-app-btn">
                            <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/Google_Pay_Logo.svg/512px-Google_Pay_Logo.svg.png" alt="GPay" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%2236%22 height=%2236%22><rect fill=%22%234285f4%22 width=%2236%22 height=%2236%22 rx=%228%22/><text x=%2218%22 y=%2224%22 fill=%22white%22 text-anchor=%22middle%22 font-size=%2216%22 font-weight=%22bold%22>G</text></svg>'">
                            <span>Google Pay</span>
                        </a>
                        <a href="#" id="phonepeLink" class="upi-app-btn">
                            <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/71/PhonePe_Logo.svg/512px-PhonePe_Logo.svg.png" alt="PhonePe" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%2236%22 height=%2236%22><rect fill=%22%235f259f%22 width=%2236%22 height=%2236%22 rx=%228%22/><text x=%2218%22 y=%2224%22 fill=%22white%22 text-anchor=%22middle%22 font-size=%2216%22 font-weight=%22bold%22>P</text></svg>'">
                            <span>PhonePe</span>
                        </a>
                        <a href="#" id="paytmLink" class="upi-app-btn">
                            <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Paytm_Logo_%28standalone%29.svg/512px-Paytm_Logo_%28standalone%29.svg.png" alt="Paytm" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%2236%22 height=%2236%22><rect fill=%22%2300baf2%22 width=%2236%22 height=%2236%22 rx=%228%22/><text x=%2218%22 y=%2224%22 fill=%22white%22 text-anchor=%22middle%22 font-size=%2216%22 font-weight=%22bold%22>₹</text></svg>'">
                            <span>Paytm</span>
                        </a>
                    </div>
                    
                    <button class="btn btn-primary btn-block" onclick="goToStep(3)" style="margin-top:16px;padding:14px;font-size:1rem">
                        <i class="fas fa-check-circle"></i> I Have Paid — Enter UTR
                    </button>
                    <button class="btn btn-secondary btn-block" onclick="cancelPayment()" style="margin-top:8px;font-size:.85rem">
                        Cancel Payment
                    </button>
                </div>
            </div>
        </div>

        <!-- ===== STEP 3: Submit UTR ===== -->
        <div class="step-panel" id="step-3">
            <div class="card">
                <div class="card-title"><i class="fas fa-receipt" style="color:var(--accent-blue);margin-right:8px"></i>Enter UTR Number</div>
                <p style="color:var(--text-muted);font-size:.85rem;margin-bottom:16px">Enter the 12-digit UTR / Transaction ID from your UPI payment confirmation.</p>
                
                <div class="payment-info" style="margin-bottom:16px">
                    <div class="payment-info-row">
                        <span class="label">Payment Amount</span>
                        <span class="value amount-highlight" id="utrAmountDisplay">₹0.00</span>
                    </div>
                    <div class="payment-info-row">
                        <span class="label">Reference</span>
                        <span class="value" style="font-family:var(--font-mono);font-size:.82rem;color:var(--text-secondary)" id="utrRefDisplay">-</span>
                    </div>
                </div>
                
                <div class="utr-input-section">
                    <label class="form-label">UTR / Transaction ID</label>
                    <div class="utr-input-wrapper">
                        <input type="text" id="utrInput" placeholder="Enter 12-digit UTR number" maxlength="30" autocomplete="off" style="text-transform:uppercase">
                        <span class="utr-status" id="utrInputStatus"></span>
                    </div>
                    <div class="form-text" id="utrHint">Find this in your UPI app's transaction history</div>
                </div>
                
                <div style="margin-top:8px">
                    <div class="alert alert-info" style="font-size:.82rem">
                        <i class="fas fa-info-circle"></i> 
                        <strong>Where to find UTR?</strong> Open your UPI app → Transaction History → Tap on the payment → Copy the UTR/Reference number.
                    </div>
                </div>
                
                <button class="btn btn-primary btn-block" onclick="submitUtr()" id="btnSubmitUtr" style="margin-top:16px;padding:14px;font-size:1rem">
                    <span class="btn-text"><i class="fas fa-shield-alt"></i> Verify & Credit Balance</span>
                    <span class="btn-loader"><span class="spinner"></span> Verifying...</span>
                </button>
                <button class="btn btn-secondary btn-block" onclick="goToStep(2)" style="margin-top:8px;font-size:.85rem">
                    <i class="fas fa-arrow-left"></i> Back to QR Code
                </button>
            </div>
        </div>

        <!-- ===== STEP 4: Result ===== -->
        <div class="step-panel" id="step-4">
            <div class="card">
                <div class="verify-result" id="verifyResult">
                    <!-- Filled by JS -->
                </div>
                <button class="btn btn-primary btn-block" onclick="newDeposit()" style="padding:14px;font-size:1rem">
                    <i class="fas fa-plus-circle"></i> Make Another Deposit
                </button>
                <a href="trade.php" class="btn btn-secondary btn-block" style="margin-top:8px;font-size:.9rem;justify-content:center">
                    <i class="fas fa-chart-line"></i> Start Trading
                </a>
            </div>
        </div>
    </div>

    <!-- ==================== HISTORY TAB ==================== -->
    <div id="tab-history" class="tab-content">
        <div class="card">
            <div class="card-title"><i class="fas fa-history" style="color:var(--accent-blue);margin-right:8px"></i>Deposit History</div>
            <?php if (empty($deposits)): ?>
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <p>No deposits yet</p>
                </div>
            <?php else: ?>
                <?php foreach ($deposits as $dep): ?>
                    <div class="deposit-history-item">
                        <div class="dh-left">
                            <div class="dh-icon <?= $dep['status'] === 'completed' ? 'completed' : ($dep['status'] === 'pending' ? 'pending' : 'failed') ?>">
                                <i class="fas fa-<?= $dep['status'] === 'completed' ? 'check' : ($dep['status'] === 'pending' ? 'clock' : 'times') ?>"></i>
                            </div>
                            <div>
                                <div style="font-weight:600;font-size:.9rem">UPI Deposit</div>
                                <div class="dh-ref"><?= htmlspecialchars($dep['payment_ref']) ?></div>
                                <div class="dh-date"><?= date('d M Y, h:i A', strtotime($dep['created_at'])) ?></div>
                            </div>
                        </div>
                        <div class="dh-right">
                            <div class="dh-amount text-green">+₹<?= number_format($dep['amount'], 2) ?></div>
                            <span class="dh-status <?= $dep['status'] ?>"><?= ucfirst($dep['status']) ?></span>
                            <?php if ($dep['auto_verified']): ?>
                                <span style="font-size:.65rem;color:var(--accent-blue);display:block;margin-top:2px">⚡ Auto</span>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php
$extraJs = '<script>
// State
let currentStep = 1;
let paymentRef = ' . ($pendingPayment ? '"' . $pendingPayment['payment_ref'] . '"' : 'null') . ';
let paymentAmount = ' . ($pendingPayment ? $pendingPayment['amount'] : 0) . ';
let paymentExpiresIn = ' . ($pendingPayment ? max(0, strtotime($pendingPayment['expires_at']) - time()) : 0) . ';
let timerInterval = null;
const MIN_DEPOSIT = ' . $minDeposit . ';
const MAX_DEPOSIT = ' . $maxDeposit . ';
const BONUS_TIERS = ' . json_encode($bonusTiers) . ';

// Resume pending payment
if (paymentRef && paymentExpiresIn > 0) {
    document.getElementById("depositAmount").value = paymentAmount;
    // Re-generate QR data for pending payment
    const upiLink = "upi://pay?pa=' . urlencode($upiId) . '&pn=' . urlencode($merchantName) . '&am=" + paymentAmount.toFixed(2) + "&cu=INR&tn=Deposit+" + paymentRef;
    setPaymentUI(paymentRef, paymentAmount, upiLink, {
        gpay: upiLink.replace("upi://", "tez://upi/"),
        phonepe: upiLink.replace("upi://", "phonepe://"),
        paytm: upiLink.replace("upi://", "paytmmp://")
    }, paymentExpiresIn);
    goToStep(2);
}

// Tab switching
function switchTab(tab) {
    document.querySelectorAll(".tab-btn").forEach(b => b.classList.remove("active"));
    document.querySelectorAll(".tab-content").forEach(c => c.classList.remove("active"));
    event.target.closest(".tab-btn").classList.add("active");
    document.getElementById("tab-" + tab).classList.add("active");
}

// Amount presets
function setAmount(amt) {
    document.getElementById("depositAmount").value = amt;
    document.querySelectorAll(".preset-btn").forEach(b => b.classList.remove("selected"));
    event.target.classList.add("selected");
    updateBonusPreview(amt);
}

// Bonus preview
function updateBonusPreview(amount) {
    if (!BONUS_TIERS.length) return;
    let matchedTier = null;
    for (let t of BONUS_TIERS) {
        if (amount >= parseFloat(t.min_amount)) matchedTier = t;
    }
    const preview = document.getElementById("bonusPreview");
    if (matchedTier && parseFloat(matchedTier.bonus_percent) > 0) {
        const bonusAmt = amount * (parseFloat(matchedTier.bonus_percent) / 100);
        document.getElementById("bonusText").textContent = "You will get " + matchedTier.bonus_percent + "% bonus = ₹" + bonusAmt.toFixed(2) + " extra!";
        preview.style.display = "flex";
    } else {
        preview.style.display = "none";
    }
}

document.getElementById("depositAmount").addEventListener("input", function() {
    updateBonusPreview(parseFloat(this.value) || 0);
});

// Step navigation
function goToStep(step) {
    currentStep = step;
    document.querySelectorAll(".step-panel").forEach(p => p.classList.remove("active"));
    document.getElementById("step-" + step).classList.add("active");
    
    // Update step indicators
    for (let i = 1; i <= 4; i++) {
        const ind = document.getElementById("step-ind-" + i);
        ind.classList.remove("active", "done");
        if (i < step) ind.classList.add("done");
        if (i === step) ind.classList.add("active");
        
        const line = document.getElementById("step-line-" + (i - 1));
        if (line) line.classList.toggle("done", i <= step);
    }
}

// Create payment
function createPayment() {
    const amount = parseFloat(document.getElementById("depositAmount").value);
    if (!amount || amount < MIN_DEPOSIT) {
        showToast("Minimum deposit is ₹" + MIN_DEPOSIT, "error");
        return;
    }
    if (amount > MAX_DEPOSIT) {
        showToast("Maximum deposit is ₹" + MAX_DEPOSIT.toLocaleString(), "error");
        return;
    }
    
    const btn = document.getElementById("btnCreatePayment");
    btn.classList.add("btn-loading");
    
    fetch(API_URL + "/payment/create.php", {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({ amount: amount })
    })
    .then(r => r.json())
    .then(data => {
        btn.classList.remove("btn-loading");
        if (data.success) {
            paymentRef = data.payment_ref;
            paymentAmount = data.amount;
            setPaymentUI(data.payment_ref, data.amount, data.upi_link, data.deep_links, data.expires_in);
            goToStep(2);
        } else {
            showToast(data.error || data.message || "Error creating payment", "error");
        }
    })
    .catch(err => {
        btn.classList.remove("btn-loading");
        showToast("Network error. Try again.", "error");
    });
}

// Set payment UI with QR, links, timer
function setPaymentUI(ref, amount, upiLink, deepLinks, expiresIn) {
    // QR Code
    const qrUrl = "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=" + encodeURIComponent(upiLink);
    document.getElementById("qrCodeImage").src = qrUrl;
    
    // Payment info
    document.getElementById("payAmountDisplay").textContent = "₹" + parseFloat(amount).toLocaleString("en-IN", {minimumFractionDigits: 2});
    document.getElementById("payRefDisplay").textContent = ref;
    
    // UTR step info
    document.getElementById("utrAmountDisplay").textContent = "₹" + parseFloat(amount).toLocaleString("en-IN", {minimumFractionDigits: 2});
    document.getElementById("utrRefDisplay").textContent = ref;
    
    // Deep links
    if (deepLinks) {
        document.getElementById("gpayLink").href = deepLinks.gpay || upiLink;
        document.getElementById("phonepeLink").href = deepLinks.phonepe || upiLink;
        document.getElementById("paytmLink").href = deepLinks.paytm || upiLink;
    }
    
    // Timer
    startTimer(expiresIn || 600);
}

// Countdown timer
function startTimer(seconds) {
    if (timerInterval) clearInterval(timerInterval);
    let remaining = seconds;
    
    function updateTimer() {
        const mins = Math.floor(remaining / 60);
        const secs = remaining % 60;
        document.getElementById("paymentTimer").textContent = 
            String(mins).padStart(2, "0") + ":" + String(secs).padStart(2, "0");
        
        if (remaining <= 0) {
            clearInterval(timerInterval);
            showToast("Payment session expired", "error");
            goToStep(1);
            paymentRef = null;
        }
        remaining--;
    }
    updateTimer();
    timerInterval = setInterval(updateTimer, 1000);
}

// Cancel payment
function cancelPayment() {
    if (timerInterval) clearInterval(timerInterval);
    paymentRef = null;
    paymentAmount = 0;
    goToStep(1);
    showToast("Payment cancelled", "warning");
}

// UTR input real-time validation
document.getElementById("utrInput").addEventListener("input", function() {
    const val = this.value.replace(/[^0-9A-Za-z]/g, "");
    this.value = val.toUpperCase();
    const status = document.getElementById("utrInputStatus");
    const hint = document.getElementById("utrHint");
    
    if (val.length === 0) {
        status.innerHTML = "";
        hint.textContent = "Find this in your UPI app transaction history";
        hint.style.color = "";
    } else if (val.length < 6) {
        status.innerHTML = "<i class=\"fas fa-times-circle\" style=\"color:var(--accent-red)\"></i>";
        hint.textContent = "UTR must be at least 6 characters";
        hint.style.color = "var(--accent-red)";
    } else if (val.length >= 6 && val.length <= 30) {
        status.innerHTML = "<i class=\"fas fa-check-circle\" style=\"color:var(--accent-green)\"></i>";
        hint.textContent = "UTR format looks valid ✓";
        hint.style.color = "var(--accent-green)";
    }
});

// Submit UTR
function submitUtr() {
    const utr = document.getElementById("utrInput").value.trim();
    if (!utr || utr.length < 6) {
        showToast("Please enter a valid UTR number (at least 6 characters)", "error");
        return;
    }
    if (!paymentRef) {
        showToast("No active payment. Please create a new deposit.", "error");
        goToStep(1);
        return;
    }
    
    const btn = document.getElementById("btnSubmitUtr");
    btn.classList.add("btn-loading");
    
    fetch(API_URL + "/payment/submit-utr.php", {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({
            payment_ref: paymentRef,
            utr_number: utr
        })
    })
    .then(r => r.json())
    .then(data => {
        btn.classList.remove("btn-loading");
        if (timerInterval) clearInterval(timerInterval);
        
        if (data.success) {
            showVerifyResult(true, data);
        } else {
            showVerifyResult(false, { error: data.error || data.message || "Verification failed" });
        }
        goToStep(4);
    })
    .catch(err => {
        btn.classList.remove("btn-loading");
        showToast("Network error. Try again.", "error");
    });
}

// Show verification result
function showVerifyResult(success, data) {
    const container = document.getElementById("verifyResult");
    if (success) {
        const bonus = data.bonus ? "<div style=\"font-size:.9rem;color:var(--accent-yellow);margin-top:8px\"><i class=\"fas fa-gift\"></i> Bonus: ₹" + parseFloat(data.bonus).toFixed(2) + " credited!</div>" : "";
        container.innerHTML = 
            "<div class=\"result-icon success\"><i class=\"fas fa-check-circle\"></i></div>" +
            "<div class=\"result-title\">Deposit Successful!</div>" +
            "<p style=\"color:var(--text-secondary);font-size:.9rem\">Your deposit has been auto-verified and credited to your account.</p>" +
            "<div class=\"result-amount\">₹" + parseFloat(data.amount || paymentAmount).toLocaleString("en-IN", {minimumFractionDigits: 2}) + "</div>" +
            bonus +
            "<div style=\"margin-top:12px;padding:12px;background:var(--bg-secondary);border-radius:10px;font-size:.85rem\">" +
            "<span style=\"color:var(--text-muted)\">New Balance:</span> <strong style=\"color:var(--accent-green)\">₹" + parseFloat(data.new_balance || 0).toLocaleString("en-IN", {minimumFractionDigits: 2}) + "</strong>" +
            "</div>";
        
        // Refresh balance in header
        refreshBalance();
    } else {
        container.innerHTML = 
            "<div class=\"result-icon error\"><i class=\"fas fa-times-circle\"></i></div>" +
            "<div class=\"result-title\">Verification Failed</div>" +
            "<p style=\"color:var(--text-secondary);font-size:.9rem\">" + (data.error || "Auto-verification failed. Admin will review manually.") + "</p>" +
            "<div style=\"margin-top:16px;padding:12px;background:rgba(251,191,36,.08);border:1px solid rgba(251,191,36,.2);border-radius:10px;font-size:.85rem;color:var(--accent-yellow)\">" +
            "<i class=\"fas fa-info-circle\"></i> If you have paid, your deposit will be reviewed by our team within 15 minutes." +
            "</div>";
    }
}

// New deposit
function newDeposit() {
    paymentRef = null;
    paymentAmount = 0;
    document.getElementById("depositAmount").value = "";
    document.getElementById("utrInput").value = "";
    document.querySelectorAll(".preset-btn").forEach(b => b.classList.remove("selected"));
    document.getElementById("bonusPreview").style.display = "none";
    goToStep(1);
}
// Download QR code
function downloadQR() {
    const imgUrl = document.getElementById("qrCodeImage").src;
    if (!imgUrl) return;
    
    const a = document.createElement("a");
    a.href = imgUrl;
    a.download = "UPI-QR.png";
    a.target = "_blank";
    
    // Try to fetch as blob to enforce download instead of viewing
    fetch(imgUrl)
      .then(response => response.blob())
      .then(blob => {
          const url = window.URL.createObjectURL(blob);
          a.href = url;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
      })
      .catch(e => {
          // Fallback if CORS blocks fetch
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
      });
}
</script>';

require_once 'includes/footer.php';
?>
