<?php
require_once 'includes/config.php';
require_once 'includes/dingconnect.php';
requireLogin();
require_once 'includes/service_check.php';
checkServiceEnabled('international');
$user = getCurrentUser();
$db   = getDB();

// User's preferred secondary currency (non-BDT)
$_intl_uc = null;
try {
    $s = $db->prepare("SELECT c.* FROM users u JOIN currencies c ON u.preferred_currency=c.code WHERE u.id=? AND c.is_active=1 AND c.code<>'BDT'");
    $s->execute([$user['id']]);
    $_intl_uc = $s->fetch() ?: null;
} catch(Exception $e) { $_intl_uc = null; }
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>International - <?= SITE_NAME ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        *{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
        :root{
            --primary:<?= getSetting('color_primary') ?: '#1a3c8f' ?>;
            --secondary:<?= getSetting('color_secondary') ?: '#f5a623' ?>;
            --dark:<?= getSetting('color_dark') ?: '#0d1f4e' ?>;
        }
        body{font-family:'Segoe UI',sans-serif;background:#f5f7fa;min-height:100vh;padding-bottom:160px}

        /* Header */
        .hdr{background:linear-gradient(135deg,var(--dark),var(--primary));padding:0 18px}
        .hdr-in{display:flex;align-items:center;gap:14px;height:56px;max-width:480px;margin:0 auto}
        .back{background:none;border:none;color:white;font-size:18px;cursor:pointer;width:36px;height:36px;display:flex;align-items:center;justify-content:center;border-radius:50%}
        .hdr-title{color:white;font-size:18px;font-weight:700;flex:1}
        .bal-badge{background:rgba(255,255,255,0.15);color:white;padding:5px 12px;border-radius:20px;font-size:12px;font-weight:600;white-space:nowrap}

        /* Hero + Tabs */
        .hero{background:linear-gradient(135deg,var(--dark),var(--primary));padding:14px 18px 18px;position:relative;z-index:1}
        .hero-inner{max-width:480px;margin:0 auto}
        .hero-text{color:rgba(255,255,255,0.7);font-size:13px;margin-bottom:10px}
        .pills{display:flex;gap:8px;flex-wrap:wrap}
        .pill{background:rgba(255,255,255,0.15);border-radius:20px;padding:4px 12px;font-size:11px;color:white;font-weight:600}

        /* Tabs - below separate  */
        .tab-wrap{background:white;border-bottom:2px solid #f0f0f0;position:sticky;top:0;z-index:50}
        .main-tabs{display:grid;grid-template-columns:1fr 1fr;max-width:480px;margin:0 auto}
        .main-tab{padding:15px;border:none;border-bottom:3px solid transparent;background:none;font-size:15px;font-weight:700;color:#aaa;cursor:pointer;transition:0.2s;display:flex;align-items:center;justify-content:center;gap:8px;-webkit-tap-highlight-color:rgba(0,0,0,0.1)}
        .main-tab.active{color:var(--primary);border-bottom-color:var(--primary);background:#f8faff}

        .main{max-width:480px;margin:0 auto;padding:16px 18px}

        /* Steps */
        .steps{display:flex;align-items:center;margin-bottom:16px}
        .step{display:flex;flex-direction:column;align-items:center;flex:1}
        .sc{width:32px;height:32px;border-radius:50%;border:2px solid #e8ecf4;background:white;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#aaa;transition:0.3s}
        .step.done .sc{background:var(--primary);border-color:var(--primary);color:white}
        .step.active .sc{border-color:var(--primary);color:var(--primary);box-shadow:0 0 0 3px rgba(26,60,143,0.12)}
        .sl{font-size:10px;color:#aaa;margin-top:4px;font-weight:600}
        .step.active .sl,.step.done .sl{color:var(--primary)}
        .sline{flex:1;height:2px;background:#e8ecf4;margin-bottom:16px}
        .sline.done{background:var(--primary)}

        .card{background:white;border-radius:16px;padding:18px;box-shadow:0 2px 12px rgba(0,0,0,0.06);margin-bottom:14px}
        .card-title{font-size:14px;font-weight:700;color:var(--primary);margin-bottom:14px;display:flex;align-items:center;gap:8px}
        .back-btn{background:none;border:none;color:var(--primary);cursor:pointer;font-size:15px;padding:0}

        /* Search */
        .srch{position:relative;margin-bottom:12px}
        .srch i{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#aaa;font-size:13px}
        .srch input{width:100%;padding:11px 11px 11px 35px;border:2px solid #e8ecf4;border-radius:12px;font-size:14px;outline:none;transition:0.2s}
        .srch input:focus{border-color:var(--primary)}

        /* Country Grid */
        .cgrid{display:grid;grid-template-columns:1fr 1fr;gap:10px;max-height:320px;overflow-y:auto}
        .ccard{border:2px solid #e8ecf4;border-radius:12px;padding:11px;cursor:pointer;transition:0.2s;display:flex;align-items:center;gap:8px;background:white}
        .ccard:hover,.ccard.sel{border-color:var(--primary);background:#f0f4ff}
        .cflag{font-size:20px;flex-shrink:0}
        .cname{font-size:12px;font-weight:700;color:#333;line-height:1.2}
        .cdial{font-size:11px;color:#888}

        /* Package / PIN List */
        .plist{display:flex;flex-direction:column;gap:10px;max-height:400px;overflow-y:auto}
        .pitem{border:2px solid #e8ecf4;border-radius:12px;padding:14px;cursor:pointer;transition:0.2s;background:white;display:flex;align-items:center;justify-content:space-between}
        .pitem:hover,.pitem.sel{border-color:var(--primary);background:#f0f4ff}
        .pitem-left{flex:1;min-width:0}
        .pitem-name{font-size:14px;font-weight:700;color:#333}
        .pitem-desc{font-size:11px;color:#888;margin-top:3px}
        .pitem-recv{font-size:13px;font-weight:600;color:#38a169;margin-top:4px}
        .pitem-right{text-align:right;flex-shrink:0;margin-left:10px}
        .pitem-price{font-size:17px;font-weight:800;color:var(--primary)}
        .pitem-bdt{font-size:11px;color:#888}

        /* PIN item special */
        .pin-item{border:2px solid #e8ecf4;border-radius:12px;padding:14px;cursor:pointer;transition:0.2s;background:white}
        .pin-item:hover,.pin-item.sel{border-color:var(--secondary);background:#fffaf0}
        .pin-top{display:flex;align-items:center;gap:10px;margin-bottom:6px}
        .pin-logo{width:40px;height:40px;border-radius:9px;object-fit:contain;border:1px solid #eee;flex-shrink:0;background:white}
        .pin-logo-fallback{width:40px;height:40px;border-radius:9px;background:linear-gradient(135deg,#f5a623,#e8940f);display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
        .pin-provider{font-size:13px;font-weight:800;color:var(--dark)}
        .pin-country{font-size:11px;color:#888;margin-top:2px}
        .pin-bottom{display:flex;align-items:center;justify-content:space-between}
        .pin-value{font-size:15px;font-weight:700;color:#333}
        .pin-price{text-align:right}
        .pin-usd{font-size:16px;font-weight:800;color:var(--primary)}
        .pin-bdt{font-size:11px;color:#888}

        /* Phone/Confirm step */
        .lbl{font-size:13px;color:#555;font-weight:600;margin-bottom:7px;display:block}
        .ph-in{width:100%;padding:14px 16px;border:2px solid #e8ecf4;border-radius:14px;font-size:16px;outline:none;transition:0.2s}
        .ph-in:focus{border-color:var(--primary)}
        .ph-hint{font-size:12px;color:#888;margin-top:5px}
        .summary{background:#f0f4ff;border-radius:12px;padding:14px;margin-bottom:14px}
        .sum-provider{font-size:12px;color:#888;margin-bottom:3px}
        .sum-pkg{font-size:15px;font-weight:800;color:var(--dark);margin-bottom:6px}
        .sum-row{display:flex;justify-content:space-between;align-items:center}
        .sum-price{font-size:18px;font-weight:800;color:var(--primary)}
        .deduct-note{background:#fffaf0;border-radius:10px;padding:10px 13px;font-size:12px;color:#92400e;margin-top:10px}

        /* PIN confirm - no phone needed */
        .pin-confirm-box{background:#fffaf0;border:2px solid #f6ad55;border-radius:14px;padding:16px;margin-bottom:14px;text-align:center}
        .pin-confirm-box i{font-size:28px;color:#d69e2e;display:block;margin-bottom:8px}
        .pin-confirm-box h3{font-size:15px;font-weight:700;color:#92400e;margin-bottom:4px}
        .pin-confirm-box p{font-size:12px;color:#b7791f}

        /* Tap Hold */
        .thold-wrap{position:fixed;bottom:65px;left:0;right:0;padding:10px 18px 12px;background:white;border-top:2px solid #eef0f5;z-index:150;box-shadow:0 -4px 20px rgba(0,0,0,0.08)}
        .thold-inner{max-width:480px;margin:0 auto}
        .thold-btn{width:100%;border:none;border-radius:18px;padding:16px 20px;display:flex;align-items:center;justify-content:center;gap:13px;cursor:pointer;position:relative;overflow:hidden;background:var(--primary);user-select:none;-webkit-user-select:none;touch-action:none}
        .thold-btn.off{background:#c5cdd8;cursor:not-allowed}
        .thold-btn.pin-mode{background:linear-gradient(135deg,#d69e2e,#b7791f)}
        .tprog{position:absolute;left:0;top:0;bottom:0;background:rgba(255,255,255,0.18);width:0%;border-radius:18px;pointer-events:none}
        .tic{width:40px;height:40px;background:white;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0}
        .tic i{color:var(--primary);font-size:17px}
        .thold-btn.pin-mode .tic i{color:#d69e2e}
        .ttxt{color:white;font-size:14px;font-weight:600}

        .err{background:#fff5f5;color:#e53e3e;padding:10px 14px;border-radius:10px;font-size:13px;margin-bottom:12px;border-left:3px solid #e53e3e;display:none}
        .loading{text-align:center;padding:30px;color:#aaa}
        .loading i{font-size:22px;display:block;margin-bottom:8px;animation:sp 1s linear infinite}
        .empty-msg{text-align:center;padding:30px;color:#aaa}
        .empty-msg i{font-size:26px;display:block;margin-bottom:8px;color:#ddd}
        @keyframes sp{to{transform:rotate(360deg)}}

        .spin-wrap{display:none;position:fixed;inset:0;background:rgba(255,255,255,0.85);z-index:400;align-items:center;justify-content:center;flex-direction:column;gap:12px}
        .spin-wrap.on{display:flex}
        .spin{width:44px;height:44px;border:4px solid #e8ecf4;border-top-color:var(--primary);border-radius:50%;animation:sp 0.8s linear infinite}
        .spin-txt{color:var(--primary);font-size:14px;font-weight:600}

        /* Popups */
        .pop-ov{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.45);z-index:500;align-items:flex-end;justify-content:center}
        .pop-ov.on{display:flex}
        .pop-box{background:white;border-radius:28px 28px 0 0;padding:26px 22px 36px;width:100%;max-width:480px;animation:su 0.3s ease;position:relative}
        @keyframes su{from{transform:translateY(100%)}to{transform:translateY(0)}}
        .pop-x{position:absolute;top:14px;right:16px;background:none;border:none;font-size:20px;color:#bbb;cursor:pointer}
        .pop-icon-ok{width:60px;height:60px;background:#22c55e;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 14px;box-shadow:0 4px 20px rgba(34,197,94,0.35)}
        .pop-icon-ok i{color:white;font-size:26px}
        .pop-icon-pin{width:60px;height:60px;background:linear-gradient(135deg,#d69e2e,#b7791f);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 14px;box-shadow:0 4px 20px rgba(214,158,46,0.35)}
        .pop-icon-pin i{color:white;font-size:26px}
        .pop-title{text-align:center;font-size:18px;font-weight:700;color:#222;margin-bottom:14px}
        .pop-title span{color:#22c55e}
        .pin-result-box{background:linear-gradient(135deg,#1a3c8f,#2856c8);border-radius:14px;padding:20px;text-align:center;margin-bottom:16px}
        .pin-result-label{color:rgba(255,255,255,0.7);font-size:12px;margin-bottom:8px}
        .pin-result-code{color:white;font-size:28px;font-weight:800;letter-spacing:4px;font-family:monospace;word-break:break-all}
        .copy-pin-btn{width:100%;padding:12px;background:white;color:var(--primary);border:none;border-radius:10px;font-size:14px;font-weight:700;cursor:pointer;margin-top:10px}
        .pop-rows{background:#f8fafc;border-radius:12px;padding:13px;margin-bottom:14px}
        .prow{display:flex;justify-content:space-between;padding:7px 0;border-bottom:1px solid #f0f0f0;font-size:13px}
        .prow:last-child{border:none}
        .prow .pl{color:#888}
        .prow .pv{font-weight:600;text-align:right;max-width:60%}
        .home-btn{width:100%;padding:14px;background:var(--primary);color:white;border:none;border-radius:12px;font-size:15px;font-weight:600;cursor:pointer}
        .pend-icon{font-size:50px;text-align:center;display:block;margin-bottom:12px}
    </style>
</head>
<body>

<div class="hdr">
    <div class="hdr-in">
        <button class="back" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
        <div class="hdr-title">🌍 International</div>
        <span class="bal-badge"><?= number_format($user['balance'],2) ?></span>
    </div>
</div>

<div class="hero">
    <div class="hero-inner">
        <div class="hero-text">Recharge or buy PIN in any country worldwide</div>
        <div class="pills">
            <span class="pill">🌍 150+ Country</span>
            <span class="pill">📱 850+ Operator</span>
            <span class="pill">⚡ Real-time</span>
        </div>
    </div>
</div>

<!-- Tabs - Hero  or, sticky -->
<div class="tab-wrap">
    <div class="main-tabs" style="grid-template-columns:1fr 1fr 1fr">
        <button class="main-tab active" id="tabRecharge" onclick="switchTab('recharge')">
            <i class="fas fa-mobile-alt"></i> Recharge
        </button>
        <button class="main-tab" id="tabPin" onclick="switchTab('pin')">
            <i class="fas fa-key"></i> PIN
        </button>
        <button class="main-tab" id="tabGift" onclick="switchTab('gift')">
            <i class="fas fa-gift"></i> Gift Card
        </button>
    </div>
</div>

<div class="main">
    <div class="err" id="errMsg"></div>

    <!-- ============ RECHARGE TAB ============ -->
    <div id="rechargeSection">
        <!-- Steps: Country → Package → Phone -->
        <div class="steps" id="rSteps">
            <div class="step active" id="rs1"><div class="sc">1</div><div class="sl">Country</div></div>
            <div class="sline" id="rl1"></div>
            <div class="step" id="rs2"><div class="sc">2</div><div class="sl">Package</div></div>
            <div class="sline" id="rl2"></div>
            <div class="step" id="rs3"><div class="sc">3</div><div class="sl">Numb</div></div>
        </div>

        <!-- Step R1: Country -->
        <div id="rStep1">
            <div class="card">
                <div class="card-title"><i class="fas fa-globe"></i> Select Country</div>
                <div class="srch"><i class="fas fa-search"></i><input type="text" id="rCSearch" placeholder="Search country..." oninput="filterRC(this.value)"></div>
                <div class="cgrid" id="rCGrid"><div class="loading"><i class="fas fa-spinner"></i>Loading...</div></div>
            </div>
        </div>

        <!-- Step R2: Package -->
        <div id="rStep2" style="display:none">
            <div class="card">
                <div class="card-title">
                    <button class="back-btn" onclick="rGoStep(1)"><i class="fas fa-arrow-left"></i></button>
                    <span id="rS2Title">Select Package</span>
                </div>
                <div class="op-tabs" id="rOpTabs" style="display:flex;gap:7px;margin-bottom:12px;overflow-x:auto;scrollbar-width:none;padding-bottom:3px"></div>
                <div class="plist" id="rPkgList"><div class="loading"><i class="fas fa-spinner"></i>Loading...</div></div>
            </div>
        </div>

        <!-- Step R3: Phone -->
        <div id="rStep3" style="display:none">
            <div class="card">
                <div class="card-title">
                    <button class="back-btn" onclick="rGoStep(2)"><i class="fas fa-arrow-left"></i></button>
                    Enter Phone Number
                </div>
                <div class="summary">
                    <div class="sum-provider" id="rSumOp">-</div>
                    <div class="sum-pkg" id="rSumPkg">-</div>
                    <div class="sum-row">
                        <span style="font-size:13px;color:#888" id="rSumCountry">-</span>
                        <span class="sum-price" id="rSumPrice">-</span>
                    </div>
                </div>
                <label class="lbl">Phone Number (with country code)</label>
                <div style="display:flex;gap:8px;align-items:center">
                    <div id="rDialBadge" style="padding:10px 12px;background:#f0f4ff;border:2px solid #e8ecf4;border-radius:12px;font-size:14px;font-weight:700;color:#1a3c8f;white-space:nowrap;min-width:60px;text-align:center">+880</div>
                    <input type="tel" id="rPhone" class="ph-in" placeholder="XXXXXXXXXX" oninput="rChkReady()" style="flex:1">
                </div>
                <div style="background:#f8fafc;border-radius:10px;padding:10px 12px;margin-top:8px;font-size:12px;color:#555;line-height:1.8">
                    <div style="font-weight:700;color:#333;margin-bottom:4px">📱 How to enter number:</div>
                    <div>🇧🇩 Bangladesh: <b>01XXXXXXXXX</b> <span style="color:#aaa">(e.g. 01712345678)</span></div>
                    <div>🇮🇳 India: <b>XXXXXXXXXX</b> <span style="color:#aaa">(e.g. 9876543210)</span></div>
                    <div>🇺🇸 USA/Canada: <b>XXXXXXXXXX</b> <span style="color:#aaa">(e.g. 2125551234)</span></div>
                    <div style="color:#aaa;margin-top:4px;font-size:11px">⚠️ Do not include country code — it is added automatically / কান্ট্রি কোড দেবেন না — অটো যোগ হবে</div>
                </div>
                <div class="deduct-note">💡 From your balance <strong id="rDeduct">-</strong> will be deducted</div>
            </div>
        </div>
    </div>

    <!-- ============ VOUCHER TAB ============ -->
    <div id="pinSection" style="display:none">
        <!-- Steps: Country → Voucher -->
        <div class="steps">
            <div class="step active" id="ps1"><div class="sc">1</div><div class="sl">Country</div></div>
            <div class="sline" id="pl1"></div>
            <div class="step" id="ps2"><div class="sc">2</div><div class="sl">Select Voucher</div></div>
        </div>

        <!-- Step P1: Country -->
        <div id="pStep1">
            <div class="card">
                <div class="card-title"><i class="fas fa-gift"></i> Select country for Voucher</div>
                <div class="srch"><i class="fas fa-search"></i><input type="text" id="pCSearch" placeholder="Search country..." oninput="filterPC(this.value)"></div>
                <div class="cgrid" id="pCGrid"><div class="loading"><i class="fas fa-spinner"></i>Loading...</div></div>
            </div>
        </div>

        <!-- Step P2: Voucher List -->
        <div id="pStep2" style="display:none">
            <div class="card">
                <div class="card-title">
                    <button class="back-btn" onclick="pGoStep(1)"><i class="fas fa-arrow-left"></i></button>
                    <span id="pS2Title">Select Voucher</span>
                </div>
                <div id="pOpTabs" style="display:flex;gap:7px;margin-bottom:12px;overflow-x:auto;scrollbar-width:none;padding-bottom:3px"></div>
                <div class="plist" id="pPinList"><div class="loading"><i class="fas fa-spinner"></i>Loading...</div></div>
            </div>

            <!-- Voucher Confirm Box -->
            <div id="pinConfirmCard" style="display:none">
                <div class="card">
                    <div class="pin-confirm-box" style="background:#f0fff4;border-color:#38a169">
                        <i class="fas fa-gift" style="color:#38a169"></i>
                        <h3 style="color:#276749">Voucher Buy</h3>
                        <p style="color:#48bb78">Voucher code will appear after purchase</p>
                    </div>
                    <div class="summary">
                        <div class="sum-provider" id="pSumOp">-</div>
                        <div class="sum-pkg" id="pSumPkg">-</div>
                        <div class="sum-row">
                            <span style="font-size:13px;color:#888" id="pSumCountry">-</span>
                            <span class="sum-price" style="color:#38a169" id="pSumPrice">-</span>
                        </div>
                    </div>
                    <div class="deduct-note">💡 Balance  <strong id="pDeduct">-</strong> will be deducted. Voucher code will appear on screen.</div>
                </div>
            </div>
        </div>
    </div>
    <!-- ============ GIFT CARD TAB ============ -->
    <div id="giftSection" style="display:none">
        <div class="steps">
            <div class="step active" id="gs1"><div class="sc">1</div><div class="sl">Country</div></div>
            <div class="sline" id="gl1"></div>
            <div class="step" id="gs2"><div class="sc">2</div><div class="sl">Gift Card</div></div>
        </div>

        <!-- Step G1: Country -->
        <div id="gStep1">
            <div class="card">
                <div class="card-title"><i class="fas fa-gift"></i> Select Country for Gift Card</div>
                <div class="srch"><i class="fas fa-search"></i><input type="text" id="gCSearch" placeholder="Search country..." oninput="filterGC(this.value)"></div>
                <div class="cgrid" id="gCGrid"><div class="loading"><i class="fas fa-spinner"></i>Loading...</div></div>
            </div>
        </div>

        <!-- Step G2: Gift Card List -->
        <div id="gStep2" style="display:none">
            <div class="card">
                <div class="card-title">
                    <button class="back-btn" onclick="gGoStep(1)"><i class="fas fa-arrow-left"></i></button>
                    <span id="gS2Title">Select Gift Card</span>
                </div>
                <div id="gOpTabs" style="display:flex;gap:7px;margin-bottom:12px;overflow-x:auto;scrollbar-width:none;padding-bottom:3px"></div>
                <div class="plist" id="gCardList"><div class="loading"><i class="fas fa-spinner"></i>Loading...</div></div>
            </div>

            <div id="giftConfirmCard" style="display:none">
                <div class="card">
                    <div class="pin-confirm-box" style="background:#faf5ff;border-color:#805ad5">
                        <i class="fas fa-gift" style="font-size:28px;color:#805ad5;display:block;margin-bottom:8px"></i>
                        <h3 style="color:#553c9a">Buy Gift Card</h3>
                        <p style="color:#805ad5">Gift Card code will appear after purchase</p>
                    </div>
                    <div class="summary">
                        <div class="sum-provider" id="gSumOp">-</div>
                        <div class="sum-pkg" id="gSumPkg">-</div>
                        <div class="sum-row">
                            <span style="font-size:13px;color:#888" id="gSumCountry">-</span>
                            <span class="sum-price" style="color:#805ad5" id="gSumPrice">-</span>
                        </div>
                    </div>
                    <div class="deduct-note">💡 Balance <strong id="gDeduct">-</strong> will be deducted. Gift Card code will show on screen.</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Tap Hold Button -->
<div class="thold-wrap" id="thWrap" style="display:none">
    <div class="thold-inner">
        <div class="thold-btn off" id="thBtn"
             ontouchstart="startH(event)" ontouchend="endH()" ontouchcancel="endH()"
             onmousedown="startH(event)" onmouseup="endH()" onmouseleave="endH()">
            <div class="tprog" id="thProg"></div>
            <div class="tic" id="thIc"><i class="fas fa-globe" id="thIcon"></i></div>
            <span class="ttxt" id="thTxt">Tap and hold</span>
        </div>
    </div>
</div>

<!-- Spinner -->
<div class="spin-wrap" id="spinner"><div class="spin"></div><div class="spin-txt" id="spinTxt">Process happening...</div></div>

<!-- Recharge Success Popup -->
<div class="pop-ov" id="rSucPop">
    <div class="pop-box">
        <button class="pop-x" onclick="document.getElementById('rSucPop').classList.remove('on')"><i class="fas fa-times"></i></button>
        <div class="pop-icon-ok"><i class="fas fa-check"></i></div>
        <div class="pop-title">🌍 International <span>Recharge</span><br>Successful!</div>
        <div class="pop-rows">
            <div class="prow"><span class="pl">Phone</span><span class="pv" id="rpPh">-</span></div>
            <div class="prow"><span class="pl">Operator</span><span class="pv" id="rpOp">-</span></div>
            <div class="prow"><span class="pl">Package</span><span class="pv" id="rpPk">-</span></div>
            <div class="prow"><span class="pl">Amount</span><span class="pv" style="color:#22c55e" id="rpAm">-</span></div>
            <div class="prow"><span class="pl">Ref</span><span class="pv" id="rpRf">-</span></div>
        </div>
        <button class="home-btn" onclick="location.href='dashboard.php'">← Back to Home</button>
    </div>
</div>

<!-- Voucher Success Popup -->
<div class="pop-ov" id="pSucPop">
    <div class="pop-box">
        <button class="pop-x" onclick="document.getElementById('pSucPop').classList.remove('on')"><i class="fas fa-times"></i></button>
        <div class="pop-icon-pin" style="background:linear-gradient(135deg,#38a169,#276749)"><i class="fas fa-gift"></i></div>
        <div class="pop-title">🎁 your <span style="color:#38a169">Voucher Code</span></div>
        <div class="pin-result-box" style="background:linear-gradient(135deg,#276749,#38a169)">
            <div class="pin-result-label">Voucher / Redeem Code</div>
            <div class="pin-result-code" id="ppPin">-</div>
            <button class="copy-pin-btn" onclick="copyPIN()"><i class="fas fa-copy"></i> Code Copy </button>
        </div>
        <div class="pop-rows">
            <div class="prow"><span class="pl">Provider</span><span class="pv" id="ppOp">-</span></div>
            <div class="prow"><span class="pl">Value</span><span class="pv" id="ppVal">-</span></div>
            <div class="prow"><span class="pl">Ref</span><span class="pv" id="ppRf">-</span></div>
        </div>
        <button class="home-btn" onclick="location.href='dashboard.php'">← Back to Home</button>
    </div>
</div>

<!-- Gift Card Success Popup -->
<div class="pop-ov" id="gSucPop">
    <div class="pop-box">
        <button class="pop-x" onclick="document.getElementById('gSucPop').classList.remove('on')"><i class="fas fa-times"></i></button>
        <div class="pop-icon-pin" style="background:linear-gradient(135deg,#805ad5,#553c9a)"><i class="fas fa-gift"></i></div>
        <div class="pop-title">🎁 Your <span style="color:#805ad5">Gift Card Code</span></div>
        <div class="pin-result-box" style="background:linear-gradient(135deg,#553c9a,#805ad5)">
            <div class="pin-result-label">Gift Card / Redeem Code</div>
            <div class="pin-result-code" id="gpPin">-</div>
            <button class="copy-pin-btn" onclick="copyGiftCode()"><i class="fas fa-copy"></i> Copy Code</button>
        </div>
        <div class="pop-rows">
            <div class="prow"><span class="pl">Provider</span><span class="pv" id="gpOp">-</span></div>
            <div class="prow"><span class="pl">Value</span><span class="pv" id="gpVal">-</span></div>
            <div class="prow"><span class="pl">Ref</span><span class="pv" id="gpRf">-</span></div>
        </div>
        <button class="home-btn" onclick="location.href='dashboard.php'">← Back to Home</button>
    </div>
</div>

<!-- Pending Popup -->
<div class="pop-ov" id="pendPop">
    <div class="pop-box">
        <button class="pop-x" onclick="document.getElementById('pendPop').classList.remove('on')"><i class="fas fa-times"></i></button>
        <span class="pend-icon">⏳</span>
        <div class="pop-title">Request submitted!</div>
        <p style="text-align:center;font-size:13px;color:#666;margin-bottom:14px">Admin after approval will be completed।</p>
        <div style="background:#fffaf0;border-radius:10px;padding:10px;text-align:center;font-size:13px;color:#92400e;margin-bottom:14px">Ref: <strong id="pendRef">-</strong></div>
        <button class="home-btn" onclick="location.href='dashboard.php'">← Back to Home</button>
    </div>
</div>

<script>
const USD_RATE = <?php echo getUsdRate(); ?>;
const USER_CUR_RATE = <?php echo $_intl_uc ? floatval($_intl_uc['rate']) : 0; ?>;
const USER_CUR_SYM  = "<?php echo $_intl_uc ? addslashes($_intl_uc['symbol']) : ''; ?>";
const USER_CUR_CODE = "<?php echo $_intl_uc ? $_intl_uc['code'] : ''; ?>";
function dualAmt(bdt) {
    if (!USER_CUR_RATE || !USER_CUR_CODE) return '';
    return ' <span style="color:#b7791f;font-size:11px">≈ '+USER_CUR_SYM+(bdt*USER_CUR_RATE).toFixed(2)+' '+USER_CUR_CODE+'</span>';
}
// ============ STATE ============
let allRC = [], allPC = [], allGC = [];
let rSelC=null, rSelP=null, rAllPkgs=[], rAllProvs={};
let pSelC=null, selectedPin=null, pAllPins=[], pAllProvs={};
let gSelC=null, selectedGift=null, gAllCards=[], gAllProvs={};
let curTab = 'recharge';
let hInt=null, hProg=0;
const HOLD = 2000;

window.onload = function(){ loadRCountries(); };

// ============ TAB SWITCH ============
function switchTab(tab) {
    curTab = tab;
    document.getElementById('tabRecharge').classList.toggle('active', tab==='recharge');
    document.getElementById('tabPin').classList.toggle('active', tab==='pin');
    document.getElementById('tabGift').classList.toggle('active', tab==='gift');
    document.getElementById('rechargeSection').style.display = tab==='recharge' ? 'block' : 'none';
    document.getElementById('pinSection').style.display      = tab==='pin'      ? 'block' : 'none';
    document.getElementById('giftSection').style.display     = tab==='gift'     ? 'block' : 'none';
    document.getElementById('thWrap').style.display = 'none';
    document.getElementById('errMsg').style.display = 'none';
    if (tab==='pin'  && allPC.length===0) loadPCountries();
    if (tab==='gift' && allGC.length===0) loadGCountries();
}

// ISO code  flag emoji create
function isoToFlag(iso) {
    if (!iso || iso.length !== 2) return '🌍';
    try {
        return iso.toUpperCase().replace(/./g, c =>
            String.fromCodePoint(c.charCodeAt(0) + 127397)
        );
    } catch(e) { return '🌍'; }
}

// ============ RECHARGE SECTION ============
function loadRCountries() {
    fetch('api/ding_countries.php')
    .then(r=>r.json())
    .then(d=>{
        if(d.success){ allRC=d.countries; renderRC(allRC); }
        else document.getElementById('rCGrid').innerHTML='<div class="empty-msg"><i class="fas fa-exclamation-circle"></i>'+d.message+'</div>';
    })
    .catch(()=>{ document.getElementById('rCGrid').innerHTML='<div class="empty-msg"><i class="fas fa-wifi"></i>Load failed। Please reload the page.</div>'; });
}
function renderRC(list){
    const g=document.getElementById('rCGrid');
    if(!list.length){g.innerHTML='<div class="empty-msg" style="grid-column:1/-1"><i class="fas fa-search"></i>Not found</div>';return;}
    g.innerHTML=list.map(c=>`
        <div class="ccard" onclick="rSelCountry('${c.iso}','${c.name.replace(/'/g,"\\'")}','${c.dial_code||''}')">
            <span class="cflag">${isoToFlag(c.iso)}</span>
            <div><div class="cname">${c.name}</div><div class="cdial">${c.iso}</div></div>
        </div>`).join('');
}
function filterRC(q){
    const ql = q.toLowerCase();
    // City/region aliases → country mapping
    const aliases = {
        'sylhet':'bangladesh','dhaka':'bangladesh','chittagong':'bangladesh','ctg':'bangladesh',
        'mumbai':'india','delhi':'india','kolkata':'india','chennai':'india',
        'karachi':'pakistan','lahore':'pakistan',
        'riyadh':'saudi','jeddah':'saudi',
        'dubai':'emirates','abu dhabi':'emirates',
        'london':'united kingdom','manchester':'united kingdom',
        'new york':'united states','los angeles':'united states',
        'kuala lumpur':'malaysia','kl':'malaysia',
    };
    // Check if query matches an alias
    const mappedCountry = aliases[ql] || null;
    renderRC(allRC.filter(c=>
        c.name.toLowerCase().includes(ql) ||
        c.iso.toLowerCase().includes(ql) ||
        (mappedCountry && c.name.toLowerCase().includes(mappedCountry))
    ));
}

function rSelCountry(iso,name,dial){
    rSelC={iso,name,dial};
    document.getElementById('rS2Title').textContent=name+'  Package';
    const badge=document.getElementById('rDialBadge');
    if(badge) badge.textContent=dial||'+';
    const phEx=document.getElementById('rPhEx');
    if(phEx) phEx.textContent='XXXXXXXXXX';
    rGoStep(2);
    loadRPkgs(iso);
}

function loadRPkgs(iso){
    document.getElementById('rPkgList').innerHTML='<div class="loading"><i class="fas fa-spinner"></i>Loading...</div>';
    document.getElementById('rOpTabs').innerHTML='';
    fetch('api/ding_packages.php?country='+iso)
    .then(r=>r.json())
    .then(d=>{
        if(d.success && d.packages.length){
            rAllPkgs=d.packages; rAllProvs=d.providers||{};
            renderROpTabs(); renderRPkgs('all');
        } else {
            document.getElementById('rPkgList').innerHTML='<div class="empty-msg"><i class="fas fa-box-open"></i>'+(d.message||'No packages available')+'</div>';
        }
    })
    .catch(()=>{ document.getElementById('rPkgList').innerHTML='<div class="empty-msg"><i class="fas fa-wifi"></i>Load failed</div>'; });
}
function renderROpTabs(){
    let h='<div style="padding:6px 13px;border-radius:20px;border:2px solid var(--primary);background:var(--primary);color:white;font-size:12px;font-weight:600;cursor:pointer;white-space:nowrap;flex-shrink:0" onclick="filterROp(\'all\',this)">All</div>';
    Object.entries(rAllProvs).forEach(([code,name])=>{
        h+=`<div style="padding:6px 13px;border-radius:20px;border:2px solid #e8ecf4;background:white;color:#666;font-size:12px;font-weight:600;cursor:pointer;white-space:nowrap;flex-shrink:0" onclick="filterROp('${code}',this)">${name}</div>`;
    });
    document.getElementById('rOpTabs').innerHTML=h;
}
function filterROp(code,el){
    document.querySelectorAll('#rOpTabs div').forEach(t=>{t.style.background='white';t.style.color='#666';t.style.borderColor='#e8ecf4';});
    el.style.background='var(--primary)';el.style.color='white';el.style.borderColor='var(--primary)';
    const list=code==='all'?rAllPkgs:rAllPkgs.filter(p=>p.provider_code===code);
    renderRPkgs2(list);
}
function renderRPkgs(code){
    const list=code==='all'?rAllPkgs:rAllPkgs.filter(p=>p.provider_code===code);
    renderRPkgs2(list);
}
function renderRPkgs2(list){
    const el=document.getElementById('rPkgList');
    if(!list.length){el.innerHTML='<div class="empty-msg"><i class="fas fa-box-open"></i>No packages available</div>';return;}
    el.innerHTML=list.map(p=>`
        <div class="pitem" onclick="rSelPkg('${p.sku_code}','${p.name.replace(/'/g,"\\'")}',${p.send_value},'${p.currency}','${(p.provider_name||'').replace(/'/g,"\\'")}',${p.recv_value||0},'${p.recv_currency||''}')">
            <div class="pitem-left">
                <div class="pitem-name">${p.provider_name||p.provider_code}</div>
                ${p.recv_value>0?`<div class="pitem-recv">✅ ${p.recv_currency} ${p.recv_value} will receive</div>`:''}
                ${p.description?`<div class="pitem-desc">${p.description}</div>`:''}
            </div>
            <div class="pitem-right">
                <div class="pitem-price">${p.currency} ${p.send_value}</div>
                <div class="pitem-bdt">≈ ৳${p.bdt_price}</div>
                ${USER_CUR_RATE ? `<div class="pitem-bdt" style="color:#b7791f">≈ ${USER_CUR_SYM}${(p.bdt_price*USER_CUR_RATE).toFixed(2)} ${USER_CUR_CODE}</div>` : ''}
            </div>
        </div>`).join('');
}
function rSelPkg(sku,name,price,currency,opName,recvVal,recvCur){
    rSelP={sku,name,price,currency,opName,recvVal,recvCur};
    document.getElementById('rSumOp').textContent='📡 '+opName;
    document.getElementById('rSumPkg').textContent=recvVal>0?recvCur+' '+recvVal+' Recharge':name;
    document.getElementById('rSumCountry').textContent=rSelC.name;
    document.getElementById('rSumPrice').textContent=currency+' '+price;
    const rBdt=Math.round(price*USD_RATE); document.getElementById('rDeduct').innerHTML='≈ ৳'+rBdt+dualAmt(rBdt);
    // Update dial badge with selected country code
    const badge=document.getElementById('rDialBadge');
    if(badge && rSelC && rSelC.dial) badge.textContent=rSelC.dial;
    // Clear phone input
    const phoneEl=document.getElementById('rPhone');
    if(phoneEl){ phoneEl.value=''; }
    rGoStep(3);
    showTapBtn(false);
}
function rGoStep(n){
    [1,2,3].forEach(i=>{
        document.getElementById('rStep'+i).style.display=i===n?'block':'none';
        const sc=document.getElementById('rs'+i);
        if(i<n){sc.classList.add('done');sc.classList.remove('active');}
        else if(i===n){sc.classList.add('active');sc.classList.remove('done');}
        else{sc.classList.remove('active','done');}
        if(i<3)document.getElementById('rl'+i).classList.toggle('done',i<n);
    });
    if(n!==3) hideTapBtn();
    window.scrollTo(0,0);
}
function rChkReady(){
    const ph=document.getElementById('rPhone').value.trim();
    document.getElementById('thBtn').classList.toggle('off', ph.length<6);
}

// ============ PIN SECTION ============
function loadPCountries(){
    fetch('api/ding_countries.php')
    .then(r=>r.json())
    .then(d=>{
        if(d.success){ allPC=d.countries; renderPC(allPC); }
        else document.getElementById('pCGrid').innerHTML='<div class="empty-msg"><i class="fas fa-exclamation-circle"></i>'+d.message+'</div>';
    })
    .catch(()=>{ document.getElementById('pCGrid').innerHTML='<div class="empty-msg"><i class="fas fa-wifi"></i>Load failed। Please reload the page.</div>'; });
}
function renderPC(list){
    const g=document.getElementById('pCGrid');
    if(!list.length){g.innerHTML='<div class="empty-msg" style="grid-column:1/-1"><i class="fas fa-search"></i>Not found</div>';return;}
    g.innerHTML=list.map(c=>`
        <div class="ccard" onclick="pSelCountry('${c.iso}','${c.name.replace(/'/g,"\\'")}','${c.dial_code||''}')">
            <span class="cflag">${isoToFlag(c.iso)}</span>
            <div><div class="cname">${c.name}</div><div class="cdial">${c.iso}</div></div>
        </div>`).join('');
}
function filterPC(q){ renderPC(allPC.filter(c=>c.name.toLowerCase().includes(q.toLowerCase()))); }

function pSelCountry(iso,name,dial){
    pSelC={iso,name,dial};
    document.getElementById('pS2Title').textContent=name+'  Recharge PIN';
    pGoStep(2);
    loadPPins(iso);
}

function loadPPins(iso){
    document.getElementById('pPinList').innerHTML='<div class="loading"><i class="fas fa-spinner"></i>Loading...</div>';
    document.getElementById('pOpTabs').innerHTML='';
    document.getElementById('pinConfirmCard').style.display='none';
    fetch('api/ding_pins.php?country='+iso)
    .then(r=>r.json())
    .then(d=>{
        if(d.success && d.pins.length){
            pAllPins=d.pins; pAllProvs=d.providers||{};
            renderPOpTabs(); renderPPins('all');
        } else {
            document.getElementById('pPinList').innerHTML='<div class="empty-msg"><i class="fas fa-key"></i>'+(d.message||'This country any Recharge PIN not available')+'</div>';
        }
    })
    .catch(()=>{ document.getElementById('pPinList').innerHTML='<div class="empty-msg"><i class="fas fa-wifi"></i>Load failed</div>'; });
}
function renderPOpTabs(){
    let h='<div style="padding:6px 13px;border-radius:20px;border:2px solid #d69e2e;background:#d69e2e;color:white;font-size:12px;font-weight:600;cursor:pointer;white-space:nowrap;flex-shrink:0" onclick="filterPOp(\'all\',this)">All</div>';
    Object.entries(pAllProvs).forEach(([code,name])=>{
        h+=`<div style="padding:6px 13px;border-radius:20px;border:2px solid #e8ecf4;background:white;color:#666;font-size:12px;font-weight:600;cursor:pointer;white-space:nowrap;flex-shrink:0" onclick="filterPOp('${code}',this)">${name}</div>`;
    });
    document.getElementById('pOpTabs').innerHTML=h;
}
function filterPOp(code,el){
    document.querySelectorAll('#pOpTabs div').forEach(t=>{t.style.background='white';t.style.color='#666';t.style.borderColor='#e8ecf4';});
    el.style.background='#d69e2e';el.style.color='white';el.style.borderColor='#d69e2e';
    const list=code==='all'?pAllPins:pAllPins.filter(p=>p.provider_code===code);
    renderPPins2(list);
}
function renderPPins(code){
    const list=code==='all'?pAllPins:pAllPins.filter(p=>p.provider_code===code);
    renderPPins2(list);
}
function renderPPins2(list){
    const el=document.getElementById('pPinList');
    if(!list.length){el.innerHTML='<div class="empty-msg"><i class="fas fa-key"></i>any PIN not available</div>';return;}
    el.innerHTML=list.map(p=>`
        <div class="pin-item" onclick="pSelPin('${p.sku_code}','${p.provider_name.replace(/'/g,"\\'")}','${p.display_text.replace(/'/g,"\\'")}',${p.send_value},'${p.currency}',${p.recv_value||0},'${p.recv_currency||''}','${p.logo||''}')">
            <div class="pin-top">
                ${p.logo?`<img src="${p.logo}" class="pin-logo" onerror="this.style.display='none'">`:``}
                <div class="pin-logo-fallback" style="${p.logo?'display:none':''}">🔢</div>
                <div>
                    <div class="pin-provider">${p.provider_name}</div>
                    <div class="pin-country">${p.country_flag} ${p.country_name} • 🔢 Recharge PIN</div>
                </div>
            </div>
            <div class="pin-bottom">
                <div class="pin-value">${p.display_text}</div>
                <div class="pin-price">
                    <div class="pin-usd">${p.currency} ${p.send_value}</div>
                    <div class="pin-bdt">≈ ৳${p.bdt_price}</div>
                    ${USER_CUR_RATE ? `<div class="pin-bdt" style="color:#b7791f">≈ ${USER_CUR_SYM}${(p.bdt_price*USER_CUR_RATE).toFixed(2)} ${USER_CUR_CODE}</div>` : ''}
                </div>
            </div>
        </div>`).join('');
}

function pSelPin(sku,opName,dispText,price,currency,recvVal,recvCur,logo){
    selectedPin={sku,opName,dispText,price,currency,recvVal,recvCur,logo};
    document.getElementById('pSumOp').textContent='🔢 '+opName;
    document.getElementById('pSumPkg').textContent=dispText;
    document.getElementById('pSumCountry').textContent=pSelC.name;
    document.getElementById('pSumPrice').textContent=currency+' '+price;
    const pBdt=Math.round(price*USD_RATE); document.getElementById('pDeduct').innerHTML='≈ ৳'+pBdt+dualAmt(pBdt);
    document.getElementById('pinConfirmCard').style.display='block';
    showTapBtn(true);
    window.scrollTo(0, document.body.scrollHeight);
}

function pGoStep(n){
    [1,2].forEach(i=>{
        document.getElementById('pStep'+i).style.display=i===n?'block':'none';
        const sc=document.getElementById('ps'+i);
        if(i<n){sc.classList.add('done');sc.classList.remove('active');}
        else if(i===n){sc.classList.add('active');sc.classList.remove('done');}
        else{sc.classList.remove('active','done');}
        if(i<2)document.getElementById('pl'+i).classList.toggle('done',i<n);
    });
    if(n!==2) hideTapBtn();
    window.scrollTo(0,0);
}

// ============ GIFT CARD SECTION ============
function loadGCountries(){
    fetch('api/ding_countries.php')
    .then(r=>r.json())
    .then(d=>{
        if(d.success){ allGC=d.countries; renderGC(allGC); }
        else document.getElementById('gCGrid').innerHTML='<div class="empty-msg"><i class="fas fa-exclamation-circle"></i>'+d.message+'</div>';
    })
    .catch(()=>{ document.getElementById('gCGrid').innerHTML='<div class="empty-msg"><i class="fas fa-wifi"></i>Load failed. Reload page.</div>'; });
}
function renderGC(list){
    const g=document.getElementById('gCGrid');
    if(!list.length){g.innerHTML='<div class="empty-msg" style="grid-column:1/-1"><i class="fas fa-search"></i>Not found</div>';return;}
    g.innerHTML=list.map(c=>`
        <div class="ccard" onclick="gSelCountry('${c.iso}','${c.name.replace(/'/g,"\\'")}','${c.dial_code||''}')">
            <span class="cflag">${isoToFlag(c.iso)}</span>
            <div><div class="cname">${c.name}</div><div class="cdial">${c.iso}</div></div>
        </div>`).join('');
}
function filterGC(q){ renderGC(allGC.filter(c=>c.name.toLowerCase().includes(q.toLowerCase()))); }

function gSelCountry(iso,name,dial){
    gSelC={iso,name,dial};
    document.getElementById('gS2Title').textContent=name+' Gift Cards';
    gGoStep(2);
    loadGCards(iso);
}
function loadGCards(iso){
    document.getElementById('gCardList').innerHTML='<div class="loading"><i class="fas fa-spinner"></i>Loading...</div>';
    document.getElementById('gOpTabs').innerHTML='';
    document.getElementById('giftConfirmCard').style.display='none';
    fetch('api/ding_vouchers.php?country='+iso)
    .then(r=>r.json())
    .then(d=>{
        if(d.success && d.vouchers && d.vouchers.length){
            gAllCards=d.vouchers; gAllProvs=d.providers||{};
            renderGOpTabs(); renderGCards('all');
        } else {
            document.getElementById('gCardList').innerHTML='<div class="empty-msg"><i class="fas fa-gift"></i>'+(d.message||'No Gift Cards available')+'</div>';
        }
    })
    .catch(()=>{ document.getElementById('gCardList').innerHTML='<div class="empty-msg"><i class="fas fa-wifi"></i>Load failed</div>'; });
}
function renderGOpTabs(){
    let h='<div style="padding:6px 13px;border-radius:20px;border:2px solid #805ad5;background:#805ad5;color:white;font-size:12px;font-weight:600;cursor:pointer;white-space:nowrap;flex-shrink:0" onclick="filterGOp(\'all\',this)">All</div>';
    Object.entries(gAllProvs).forEach(([code,name])=>{
        h+=`<div style="padding:6px 13px;border-radius:20px;border:2px solid #e8ecf4;background:white;color:#666;font-size:12px;font-weight:600;cursor:pointer;white-space:nowrap;flex-shrink:0" onclick="filterGOp('${code}',this)">${name}</div>`;
    });
    document.getElementById('gOpTabs').innerHTML=h;
}
function filterGOp(code,el){
    document.querySelectorAll('#gOpTabs div').forEach(t=>{t.style.background='white';t.style.color='#666';t.style.borderColor='#e8ecf4';});
    el.style.background='#805ad5';el.style.color='white';el.style.borderColor='#805ad5';
    renderGCards(code);
}
function renderGCards(code){
    const list=code==='all'?gAllCards:gAllCards.filter(p=>p.provider_code===code);
    const el=document.getElementById('gCardList');
    if(!list.length){el.innerHTML='<div class="empty-msg"><i class="fas fa-gift"></i>No gift cards</div>';return;}
    el.innerHTML=list.map(p=>`
        <div class="pin-item" style="border-color:#e8ecf4" onclick="gSelCard('${p.sku_code}','${p.provider_name.replace(/'/g,"\\'")}','${p.display_text.replace(/'/g,"\\'")}',${p.send_value},'${p.currency}',${p.recv_value||0},'${p.recv_currency||''}')">
            <div class="pin-top">
                ${p.logo?`<img src="${p.logo}" class="pin-logo" onerror="this.style.display='none'">`:``}
                <div class="pin-logo-fallback" style="background:linear-gradient(135deg,#805ad5,#553c9a)">🎁</div>
                <div>
                    <div class="pin-provider">${p.provider_name}</div>
                    <div class="pin-country">${p.country_flag} ${p.country_name} • 🎁 Gift Card</div>
                </div>
            </div>
            <div class="pin-bottom">
                <div class="pin-value">${p.display_text}</div>
                <div class="pin-price">
                    <div class="pin-usd" style="color:#805ad5">${p.currency} ${p.send_value}</div>
                    <div class="pin-bdt">≈ ৳${p.bdt_price}</div>
                    ${USER_CUR_RATE ? `<div class="pin-bdt" style="color:#b7791f">≈ ${USER_CUR_SYM}${(p.bdt_price*USER_CUR_RATE).toFixed(2)} ${USER_CUR_CODE}</div>` : ''}
                </div>
            </div>
        </div>`).join('');
}
function gSelCard(sku,opName,dispText,price,currency,recvVal,recvCur){
    selectedGift={sku,opName,dispText,price,currency,recvVal,recvCur};
    document.getElementById('gSumOp').textContent='🎁 '+opName;
    document.getElementById('gSumPkg').textContent=dispText;
    document.getElementById('gSumCountry').textContent=gSelC.name;
    document.getElementById('gSumPrice').textContent=currency+' '+price;
    const gBdt=Math.round(price*USD_RATE); document.getElementById('gDeduct').innerHTML='≈ ৳'+gBdt+dualAmt(gBdt);
    document.getElementById('giftConfirmCard').style.display='block';
    showTapBtn('gift');
    window.scrollTo(0, document.body.scrollHeight);
}
function gGoStep(n){
    [1,2].forEach(i=>{
        document.getElementById('gStep'+i).style.display=i===n?'block':'none';
        const sc=document.getElementById('gs'+i);
        if(i<n){sc.classList.add('done');sc.classList.remove('active');}
        else if(i===n){sc.classList.add('active');sc.classList.remove('done');}
        else{sc.classList.remove('active','done');}
        if(i<2)document.getElementById('gl'+i).classList.toggle('done',i<n);
    });
    if(n!==2) hideTapBtn();
    window.scrollTo(0,0);
}
function copyGiftCode(){
    const code=document.getElementById('gpPin').textContent;
    navigator.clipboard?.writeText(code).then(()=>{
        const b=event.target; const orig=b.innerHTML;
        b.innerHTML='<i class="fas fa-check"></i> Copied!'; b.style.background='#38a169'; b.style.color='white';
        setTimeout(()=>{b.innerHTML=orig;b.style.background='';b.style.color='';},2000);
    });
}

// ============ TAP HOLD ============
function showTapBtn(mode){
    const wrap=document.getElementById('thWrap');
    const btn=document.getElementById('thBtn');
    const icon=document.getElementById('thIcon');
    const txt=document.getElementById('thTxt');
    wrap.style.display='block';
    btn.classList.remove('off','pin-mode');
    btn.style.background='';
    if(mode===true||mode==='pin'){
        btn.classList.add('pin-mode');
        icon.className='fas fa-key';
        txt.textContent='Tap and hold to Buy PIN';
    } else if(mode==='gift'){
        btn.style.background='linear-gradient(135deg,#805ad5,#553c9a)';
        icon.className='fas fa-gift';
        txt.textContent='Tap and hold to Buy Gift Card';
    } else {
        btn.classList.add('off');
        icon.className='fas fa-globe';
        txt.textContent='Tap and hold to Recharge';
    }
}
function hideTapBtn(){ document.getElementById('thWrap').style.display='none'; }

function startH(e){
    e.preventDefault();
    const btn=document.getElementById('thBtn');
    if(btn.classList.contains('off')) return;
    document.getElementById('errMsg').style.display='none';
    hProg=0;
    const pr=document.getElementById('thProg');
    pr.style.transition='none'; pr.style.width='0%';
    hInt=setInterval(()=>{
        hProg+=(50/HOLD)*100;
        pr.style.width=Math.min(hProg,100)+'%';
        if(hProg>=100){
            clearInterval(hInt);
            if(curTab==='recharge') doRecharge();
            else if(curTab==='pin') doBuyPin();
            else if(curTab==='gift') doBuyGift();
        }
    },50);
}
function endH(){
    if(hInt){clearInterval(hInt);hInt=null;}
    const pr=document.getElementById('thProg');
    pr.style.transition='width 0.3s ease'; pr.style.width='0%';
}

// ============ RECHARGE API ============
function doRecharge(){
    const phoneInput = document.getElementById('rPhone').value.trim();
    const dial = (rSelC && rSelC.dial) ? rSelC.dial.replace(/[^0-9]/g,'') : '880';
    // Remove non-digits, remove leading 0, add dial code
    let numOnly = phoneInput.replace(/[^0-9]/g,'');
    if(!numOnly.startsWith(dial)){
        numOnly = numOnly.replace(/^0+/,'');
        numOnly = dial + numOnly;
    }
    const phone = numOnly; // Server adds + if needed based on product regex
    document.getElementById('spinner').classList.add('on');
    document.getElementById('spinTxt').textContent='Recharging...';
    fetch('api/intl_recharge.php',{
        method:'POST',headers:{'Content-Type':'application/json'},
        body:JSON.stringify({phone,country:rSelC.iso,sku_code:rSelP.sku,amount:rSelP.price,currency:rSelP.currency})
    }).then(r=>r.json()).then(d=>{
        document.getElementById('spinner').classList.remove('on');
        if(d.success){
            if(d.status==='success'){
                document.getElementById('rpPh').textContent=phone;
                document.getElementById('rpOp').textContent=rSelP.opName;
                document.getElementById('rpPk').textContent=rSelP.name;
                document.getElementById('rpAm').textContent=rSelP.currency+' '+rSelP.price;
                document.getElementById('rpRf').textContent=d.reference||'-';
                document.getElementById('rSucPop').classList.add('on');
            } else {
                document.getElementById('pendRef').textContent=d.reference||'-';
                document.getElementById('pendPop').classList.add('on');
            }
        } else { showErr(d.message); }
    }).catch(()=>{ document.getElementById('spinner').classList.remove('on'); showErr('❌ Connection error!'); });
}

// ============ PIN BUY API ============
function doBuyPin(){
    document.getElementById('spinner').classList.add('on');
    document.getElementById('spinTxt').textContent='Purchasing PIN...';
    fetch('api/buy_pin.php',{
        method:'POST',headers:{'Content-Type':'application/json'},
        body:JSON.stringify({
            sku_code: selectedPin.sku,
            amount:   selectedPin.price,
            currency: selectedPin.currency,
            pin_name: selectedPin.opName+' '+selectedPin.dispText,
            country:  pSelC.iso,
        })
    }).then(r=>r.json()).then(d=>{
        document.getElementById('spinner').classList.remove('on');
        if(d.success){
            if(d.pin_code){
                document.getElementById('ppPin').textContent=d.pin_code;
                document.getElementById('ppOp').textContent=selectedPin.opName;
                document.getElementById('ppVal').textContent=selectedPin.dispText;
                document.getElementById('ppRf').textContent=d.reference||'-';
                document.getElementById('pSucPop').classList.add('on');
            } else {
                document.getElementById('pendRef').textContent=d.reference||'-';
                document.getElementById('pendPop').classList.add('on');
            }
        } else { showErr(d.message); }
    }).catch(()=>{ document.getElementById('spinner').classList.remove('on'); showErr('❌ Connection error!'); });
}

function doBuyGift(){
    document.getElementById('spinner').classList.add('on');
    document.getElementById('spinTxt').textContent='Purchasing Gift Card...';
    fetch('api/buy_pin.php',{
        method:'POST',headers:{'Content-Type':'application/json'},
        body:JSON.stringify({
            sku_code:  selectedGift.sku,
            amount:    selectedGift.price,
            currency:  selectedGift.currency,
            pin_name:  selectedGift.opName+' '+selectedGift.dispText,
            country:   gSelC.iso,
            card_type: 'gift',
        })
    }).then(r=>r.json()).then(d=>{
        document.getElementById('spinner').classList.remove('on');
        if(d.success){
            if(d.pin_code){
                document.getElementById('gpPin').textContent=d.pin_code;
                document.getElementById('gpOp').textContent=selectedGift.opName;
                document.getElementById('gpVal').textContent=selectedGift.dispText;
                document.getElementById('gpRf').textContent=d.reference||'-';
                document.getElementById('gSucPop').classList.add('on');
            } else {
                document.getElementById('pendRef').textContent=d.reference||'-';
                document.getElementById('pendPop').classList.add('on');
            }
        } else { showErr(d.message); }
    }).catch(()=>{ document.getElementById('spinner').classList.remove('on'); showErr('❌ Connection error!'); });
}

function showErr(msg){
    const em=document.getElementById('errMsg');
    em.textContent=msg; em.style.display='block'; window.scrollTo(0,0);
}
function copyPIN(){
    const pin=document.getElementById('ppPin').textContent;
    navigator.clipboard?.writeText(pin).then(()=>{
        const b=event.target; const orig=b.innerHTML;
        b.innerHTML='<i class="fas fa-check"></i> Copied!';
        b.style.background='#38a169'; b.style.color='white';
        setTimeout(()=>{b.innerHTML=orig;b.style.background='';b.style.color='';},2000);
    });
}
</script>
<?php include 'includes/bottom_nav.php'; ?>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
