<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('header.php');
$page_title  = WEB_NAME . " | Virtual Numbers";
$page_title2 = "Virtual Numbers";

$priority_countries = [
    'United States','United Kingdom','Germany','France','Spain','Italy','Netherlands','Belgium',
    'Sweden','Switzerland','Norway','Poland','Denmark','Finland','Austria','Ireland',
    'Portugal','Greece','Czech Republic','Slovakia','Hungary','Romania','Bulgaria','Croatia',
    'Slovenia','Estonia','Latvia','Lithuania'
];

try {
    $servers_stmt = $pdo->query(
        "SELECT os.*, ad.api_type AS provider
           FROM otp_server os
           JOIN api_detail ad ON ad.id = os.api_id
          WHERE os.status='1'
          ORDER BY os.server_name ASC"
    );
    $all_servers = $servers_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $all_servers = [];
}

$servers_s1 = []; $servers_s2 = [];
$servers_priority_s1 = []; $servers_other_s1 = [];
$servers_priority_s2 = []; $servers_other_s2 = [];

foreach ($all_servers as $server) {
    $is_s1 = (($server['provider'] ?? 'smscodes') === 'smspva');
    if ($is_s1) {
        if (in_array($server['server_name'], $priority_countries)) $servers_priority_s1[] = $server;
        else $servers_other_s1[] = $server;
    } else {
        if (in_array($server['server_name'], $priority_countries)) $servers_priority_s2[] = $server;
        else $servers_other_s2[] = $server;
    }
}
usort($servers_priority_s1, function($a,$b) use ($priority_countries){ return array_search($a['server_name'],$priority_countries)-array_search($b['server_name'],$priority_countries); });
usort($servers_priority_s2, function($a,$b) use ($priority_countries){ return array_search($a['server_name'],$priority_countries)-array_search($b['server_name'],$priority_countries); });
$servers_s1 = array_merge($servers_priority_s1, $servers_other_s1);
$servers_s2 = array_merge($servers_priority_s2, $servers_other_s2);
$servers    = $servers_s2; // kept for any existing reference

// -- Read ALL enabled flags + tokens in one query -------------
$smspva_enabled_flag   = 1;
$smscodes_enabled_flag = 1;
$fivesim_enabled_flag  = 1;
$smsbus_enabled_flag   = 1;
$fivesim_token_val     = '';
$smsbus_token_val      = '';

try {
    // Ensure all enabled columns exist
    $pdo->exec("ALTER TABLE settings
        ADD COLUMN IF NOT EXISTS smspva_enabled   TINYINT(1) NOT NULL DEFAULT 1,
        ADD COLUMN IF NOT EXISTS smscodes_enabled TINYINT(1) NOT NULL DEFAULT 1,
        ADD COLUMN IF NOT EXISTS fivesim_enabled  TINYINT(1) NOT NULL DEFAULT 1,
        ADD COLUMN IF NOT EXISTS smsbus_enabled   TINYINT(1) NOT NULL DEFAULT 1");
} catch (PDOException $e) {}

try {
    $all_flags = $pdo->query("SELECT
        smspva_enabled, smscodes_enabled, fivesim_enabled, smsbus_enabled,
        fivesim_api_token, smsbus_api_token,
        fivesim_api_url, smsbus_api_url
        FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    if ($all_flags) {
        $smspva_enabled_flag   = (int)($all_flags['smspva_enabled']   ?? 1);
        $smscodes_enabled_flag = (int)($all_flags['smscodes_enabled'] ?? 1);
        $fivesim_enabled_flag  = (int)($all_flags['fivesim_enabled']  ?? 1);
        $smsbus_enabled_flag   = (int)($all_flags['smsbus_enabled']   ?? 1);
        $fivesim_token_val     = trim($all_flags['fivesim_api_token'] ?? '');
        $smsbus_token_val      = trim($all_flags['smsbus_api_token']  ?? '');
    }
} catch (PDOException $e) {}

// Apply S1/S2 flags
if (!$smspva_enabled_flag)   $servers_s1 = [];
if (!$smscodes_enabled_flag) $servers_s2 = [];

// -- 5SIM (S3) --------------------------------------------------
$fivesim_enabled = false;
$fivesim_countries_list = [];
if (!empty($fivesim_token_val) && $fivesim_enabled_flag === 1) {
    $fivesim_enabled = true;
    try {
        $fs_q = $pdo->query("SELECT country_key, title FROM fivesim_countries ORDER BY title ASC");
        $fivesim_countries_list = $fs_q ? $fs_q->fetchAll(PDO::FETCH_ASSOC) : [];
    } catch (PDOException $e) {}
}

// -- SMS-Bus (S4) -----------------------------------------------
$smsbus_enabled = false;
$smsbus_countries_list = [];
if (!empty($smsbus_token_val) && $smsbus_enabled_flag === 1) {
    $smsbus_enabled = true;
    try {
        $sb_q = $pdo->query("SELECT id, title, code FROM smsbus_countries ORDER BY title ASC");
        $smsbus_countries_list = $sb_q ? $sb_q->fetchAll(PDO::FETCH_ASSOC) : [];
    } catch (PDOException $e) {}
}

$user_balance = (float)$user['main_balance'];
$user_token   = (string)$user['id'];
?>
<title><?php echo htmlspecialchars($page_title); ?></title>

<style>
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.anim{opacity:0;animation:fadeUp .45s ease-out forwards}
.anim-1{animation-delay:.05s}.anim-2{animation-delay:.12s}.anim-3{animation-delay:.19s}
.vn-hero{background:linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 40%,#4D148C 80%,#4D148C 100%);border:1px solid rgba(245,158,11,.15);border-radius:20px;padding:20px;position:relative;overflow:hidden;margin-bottom:14px}
.vn-hero::before{content:'';position:absolute;inset:0;background:repeating-linear-gradient(45deg,transparent,transparent 40px,rgba(245,158,11,.012) 40px,rgba(245,158,11,.012) 41px);pointer-events:none}
.vn-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:16px;padding:20px;margin-bottom:14px}
.order-card{background:var(--card-bg);border:1px solid var(--card-border);border-radius:14px;padding:14px;margin-bottom:8px}
.order-card:hover{border-color:rgba(77,20,140,.25)}
.info-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:13px;padding:14px;display:flex;align-items:center;gap:12px}
@keyframes spin{to{transform:rotate(360deg)}}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.5}}
.srv-toggle{display:flex;background:var(--btn-bg);border:1.5px solid var(--card-border);border-radius:12px;padding:4px;gap:4px;margin-bottom:12px;}
.srv-tab{flex:1;text-align:center;padding:9px 4px;border-radius:9px;font-size:.75rem;font-weight:700;cursor:pointer;transition:all .2s;color:var(--text-muted);border:none;background:none;}
.srv-tab.s2-active{background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;box-shadow:0 3px 10px rgba(77,20,140,.3);}
.srv-tab.s1-active{background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;box-shadow:0 3px 10px rgba(99,102,241,.3);}
.srv-tab.s3-active{background:linear-gradient(135deg,#059669,#10b981);color:white;box-shadow:0 3px 10px rgba(16,185,129,.3);}
.srv-tab.s4-active{background:linear-gradient(135deg,#d97706,#f59e0b);color:white;box-shadow:0 3px 10px rgba(217,119,6,.3);}
.hidden-srv{display:none !important;}
.srv-tab.s4-active{background:linear-gradient(135deg,#d97706,#f59e0b);color:white;box-shadow:0 3px 10px rgba(217,119,6,.3);}
.prov-s1{display:none !important;}
.prov-s2{display:none !important;}
.prov-s3{display:none !important;}
.prov-s4{display:none !important;}
</style>

<div class="max-w-3xl mx-auto">

<!-- Hero -->
<div class="vn-hero anim anim-1">
    <div style="position:absolute;width:160px;height:160px;border-radius:50%;filter:blur(50px);background:radial-gradient(circle,rgba(77,20,140,.25),transparent);top:-40px;right:-40px;pointer-events:none;"></div>
    <div style="position:relative;z-index:1;display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:14px;">
        <div>
            <h2 style="font-size:1.1rem;font-weight:800;color:white;margin-bottom:4px;display:flex;align-items:center;gap:8px;">
                <i class="fas fa-sim-card text-emerald-300 text-base"></i>Virtual Numbers
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem;">Buy disposable phone numbers for OTP verification across 100+ apps.</p>
        </div>
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
            <div style="background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.15);border-radius:10px;padding:10px 16px;text-align:center;">
                <p style="font-size:.6rem;color:rgba(255,255,255,.55);font-weight:700;text-transform:uppercase;letter-spacing:.06em;">Balance</p>
                <p id="heroBalance" style="font-weight:800;color:white;font-size:.95rem;font-family:monospace;">&#8358;<?php echo number_format($user_balance,2); ?></p>
            </div>
            <a href="fund-wallet" style="background:white;color:#4D148C;font-weight:700;font-size:.78rem;padding:10px 16px;border-radius:10px;text-decoration:none;display:inline-flex;align-items:center;gap:6px;transition:all .2s;">
                <i class="fas fa-plus text-xs"></i>Add Funds
            </a>
            <a href="my-number" style="background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);color:white;font-weight:600;font-size:.78rem;padding:10px 16px;border-radius:10px;text-decoration:none;transition:all .2s;">
                <i class="fas fa-clock-rotate-left mr-1 text-xs"></i>My Numbers
            </a>
        </div>
    </div>
</div>

<!-- IP Notice -->
<div class="anim anim-2" style="background:linear-gradient(135deg,rgba(245,158,11,.08),rgba(217,119,6,.05));border:1px solid rgba(245,158,11,.25);border-radius:14px;padding:12px 16px;margin-bottom:14px;display:flex;align-items:flex-start;gap:12px;">
    <div style="flex-shrink:0;width:32px;height:32px;border-radius:9px;background:rgba(245,158,11,.15);display:flex;align-items:center;justify-content:center;">
        <i class="fas fa-shield-halved" style="color:#d97706;font-size:.85rem;"></i>
    </div>
    <div style="flex:1;min-width:0;">
        <p style="font-size:.75rem;font-weight:700;color:#d97706;margin-bottom:3px;display:flex;align-items:center;gap:6px;">
            <i class="fas fa-circle-info" style="font-size:.65rem;"></i>Pro Tip � IP Match Recommended
        </p>
        <p style="font-size:.75rem;color:var(--text-muted);line-height:1.55;">
            We recommend matching your IP address to the country of the phone number you're purchasing. This helps alleviate many common issues and improves delivery success. For the best experience, use a <strong style="color:var(--text-primary);font-weight:600;">VPN or proxy service</strong>.
        </p>
    </div>
    <button onclick="this.closest('div.anim').remove()" style="flex-shrink:0;background:none;border:none;cursor:pointer;color:var(--text-muted);padding:2px;font-size:.78rem;opacity:.6;transition:opacity .2s;" title="Dismiss">
        <i class="fas fa-xmark"></i>
    </button>
</div>

<!-- Active Orders -->
<div id="activeOrdersPanel" class="hidden anim anim-2">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;">
        <h3 style="font-weight:700;font-size:.88rem;color:var(--text-primary);display:flex;align-items:center;gap:8px;">
            <span style="width:4px;height:18px;background:linear-gradient(#6b23c2,#4D148C);border-radius:2px;display:inline-block;"></span>
            Active Numbers <span id="activeCountBadge" style="background:rgba(77,20,140,.1);color:#4D148C;font-size:.72rem;font-weight:700;padding:2px 8px;border-radius:99px;"></span>
        </h3>
        <button onclick="loadActiveOrders()" style="font-size:.72rem;color:#4D148C;font-weight:600;background:none;border:none;cursor:pointer;display:flex;align-items:center;gap:4px;">
            <i class="fas fa-rotate-right text-xs"></i>Refresh
        </button>
    </div>
    <div id="activeOrdersList" style="display:flex;flex-direction:column;gap:8px;margin-bottom:14px;"></div>
</div>

<!-- Purchase Card -->
<div class="vn-card anim anim-2">
    <h3 style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:18px;display:flex;align-items:center;gap:8px;">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(77,20,140,.1);display:inline-flex;align-items:center;justify-content:center;">
            <i class="fas fa-cart-plus" style="font-size:.72rem;color:#4D148C;"></i>
        </span>
        Buy a New Number
    </h3>

    <div style="display:flex;flex-direction:column;gap:14px;">
        <!-- Step 1: Server toggle + Country -->
        <div>
            <label style="display:block;font-size:.8rem;font-weight:600;color:var(--text-primary);margin-bottom:8px;">
                <span style="display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;background:linear-gradient(135deg,#6b23c2,#4D148C);color:white;font-size:.62rem;font-weight:700;margin-right:4px;">1</span>
                Select <?php
                    $active_server_count = (!empty($servers_s1) ? 1 : 0) + (!empty($servers_s2) ? 1 : 0) + ($fivesim_enabled ? 1 : 0) + ($smsbus_enabled ? 1 : 0);
                    echo $active_server_count > 1 ? 'Server &amp; Country' : 'Country';
                ?>
            </label>
            <?php if ($active_server_count > 1): ?>
            <!-- Show only active servers as generic numbered tabs -->
            <?php
                $active_tabs = [];
                $tab_num = 1;
                if (!empty($servers_s2)) { $active_tabs[] = ['key' => 's2', 'num' => $tab_num]; $tab_num++; }
                if (!empty($servers_s1)) { $active_tabs[] = ['key' => 's1', 'num' => $tab_num]; $tab_num++; }
                if ($fivesim_enabled)    { $active_tabs[] = ['key' => 's3', 'num' => $tab_num]; $tab_num++; }
                if ($smsbus_enabled)     { $active_tabs[] = ['key' => 's4', 'num' => $tab_num]; $tab_num++; }
            ?>
            <div class="srv-toggle">
                <?php foreach ($active_tabs as $tab): ?>
                <button class="srv-tab" id="tab<?php echo ucfirst($tab['key']); ?>" onclick="switchServer('<?php echo $tab['key']; ?>')">
                    <i class="fas fa-server mr-1"></i>Server <?php echo $tab['num']; ?>
                </button>
                <?php endforeach; ?>
            </div>
            <!-- Hidden stubs for disabled servers (JS needs these IDs) -->
            <div style="display:none;" aria-hidden="true">
                <?php if (empty($servers_s1)): ?><button id="tabS1" class="hidden-srv"></button><?php endif; ?>
                <?php if (empty($servers_s2)): ?><button id="tabS2" class="hidden-srv"></button><?php endif; ?>
                <?php if (!$fivesim_enabled): ?><button id="tabS3" class="hidden-srv"></button><?php endif; ?>
                <?php if (!$smsbus_enabled): ?><button id="tabS4" class="hidden-srv"></button><?php endif; ?>
            </div>
            <?php else: ?>
            <!-- Only one server active - no toggle needed -->
            <div style="display:none;" aria-hidden="true">
                <button id="tabS1" class="hidden-srv"></button>
                <button id="tabS2" class="hidden-srv"></button>
                <button id="tabS3" class="hidden-srv"></button>
                <button id="tabS4" class="hidden-srv"></button>
            </div>
            <?php endif; ?>
            <!-- Server 2 select -->
            <select id="server-select" style="width:100%;padding:12px 14px;background:var(--btn-bg);color:var(--hd-title);border-radius:10px;border:1.5px solid var(--card-border);outline:none;font-size:.85rem;<?php echo empty($servers_s2) ? 'display:none;' : ''; ?>"
                    onfocus="this.style.borderColor='#6b23c2'" onblur="this.style.borderColor=''">
                <option value=""> Choose a country </option>
                <?php foreach ($servers_s2 as $server): ?>
                <option value="<?php echo htmlspecialchars($server['id']); ?>"><?php echo htmlspecialchars($server['server_name']); ?></option>
                <?php endforeach; ?>
            </select>
            <!-- Server 1 select (hidden � only shows when smspva servers exist) -->
            <select id="server-select-s1" style="width:100%;padding:12px 14px;background:var(--btn-bg);color:var(--hd-title);border-radius:10px;border:1.5px solid rgba(99,102,241,.3);outline:none;font-size:.85rem;display:none;"
                    onfocus="this.style.borderColor='#6366f1'" onblur="this.style.borderColor='rgba(99,102,241,.3)'">
                <option value=""> Choose a country </option>
                <?php if (empty($servers_s1)): ?>
                <option value="" disabled>No Server1 Countries configured</option>
                <?php else: foreach ($servers_s1 as $server): ?>
                <option value="<?php echo htmlspecialchars($server['id']); ?>"><?php echo htmlspecialchars($server['server_name']); ?></option>
                <?php endforeach; endif; ?>
            </select>
            <!-- Server 3 select (5SIM � hidden by default) -->
            <?php if ($fivesim_enabled): ?>
            <select id="server-select-s3" style="width:100%;padding:12px 14px;background:var(--btn-bg);color:var(--hd-title);border-radius:10px;border:1.5px solid rgba(16,185,129,.3);outline:none;font-size:.85rem;display:none;"
                    onfocus="this.style.borderColor='#10b981'" onblur="this.style.borderColor='rgba(16,185,129,.3)'">
                <option value="">Choose a country</option>
                <?php foreach ($fivesim_countries_list as $fc): ?>
                <option value="<?php echo htmlspecialchars($fc['country_key']); ?>"><?php echo htmlspecialchars($fc['title']); ?></option>
                <?php endforeach; ?>
            </select>
            <?php endif; ?>
            <?php if ($smsbus_enabled): ?>
            <select id="server-select-s4" style="width:100%;padding:12px 14px;background:var(--btn-bg);color:var(--hd-title);border-radius:10px;border:1.5px solid rgba(217,119,6,.3);outline:none;font-size:.85rem;display:none;"
                    onfocus="this.style.borderColor='#f59e0b'" onblur="this.style.borderColor='rgba(217,119,6,.3)'">
                <option value="">Choose a country</option>
                <?php foreach ($smsbus_countries_list as $sc): ?>
                <option value="<?php echo htmlspecialchars($sc['id']); ?>"><?php echo htmlspecialchars($sc['title']); ?></option>
                <?php endforeach; ?>
            </select>
            <?php endif; ?>
        </div>

        <!-- Step 2: Service -->
        <div>
            <label style="display:block;font-size:.8rem;font-weight:600;color:var(--text-primary);margin-bottom:6px;">
                <span style="display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;background:linear-gradient(135deg,#6b23c2,#4D148C);color:white;font-size:.62rem;font-weight:700;margin-right:4px;">2</span>
                Select Service / App
            </label>
            <div style="position:relative;margin-bottom:8px;">
                <i class="fas fa-magnifying-glass" style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:var(--text-muted);font-size:.8rem;"></i>
                <input type="text" id="search_op" placeholder="Search service..." disabled
                       style="width:100%;padding:11px 14px 11px 38px;background:var(--btn-bg);color:var(--hd-title);border-radius:10px;border:1.5px solid var(--card-border);outline:none;font-size:.85rem;transition:border-color .2s;"
                       onfocus="this.style.borderColor='#6b23c2'" onblur="this.style.borderColor=''">
            </div>
            <!-- Skeleton -->
            <div id="service-skeleton" class="hidden" style="flex-direction:column;gap:6px;">
                <?php for($i=0;$i<4;$i++): ?>
                <div style="display:flex;align-items:center;gap:10px;padding:10px;border-radius:10px;background:var(--btn-bg);animation:pulse 1.5s ease-in-out infinite;">
                    <div style="width:36px;height:36px;border-radius:9px;background:var(--card-border);flex-shrink:0;"></div>
                    <div style="flex:1;"><div style="height:10px;background:var(--card-border);border-radius:4px;width:40%;margin-bottom:5px;"></div><div style="height:8px;background:var(--card-border);border-radius:4px;width:25%;"></div></div>
                </div>
                <?php endfor; ?>
            </div>
            <!-- Service list -->
            <div id="service-container" class="hidden" style="border:1.5px solid var(--card-border);border-radius:12px;overflow:hidden;">
                <ul id="list" style="list-style:none;margin:0;padding:0;max-height:280px;overflow-y:auto;" class="scrollbar-thin"></ul>
            </div>
            <div id="load-more-container" class="hidden" style="text-align:center;margin-top:8px;">
                <button id="load-more-btn" onclick="loadMoreServices()" style="width:100%;padding:9px;background:rgba(77,20,140,.07);border:1px solid rgba(77,20,140,.15);color:#4D148C;font-weight:700;font-size:.78rem;border-radius:10px;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:6px;">
                    <i class="fas fa-chevron-down text-xs"></i>Load More Services
                </button>
            </div>
            <div id="service-empty" class="hidden" style="text-align:center;padding:32px;border:1.5px dashed var(--card-border);border-radius:12px;">
                <i class="fas fa-globe" style="font-size:2rem;color:var(--text-muted);margin-bottom:8px;display:block;"></i>
                <p style="color:var(--text-muted);font-size:.82rem;">Select a country to see available services</p>
            </div>
            <input type="hidden" id="service_code" value="">
            <input type="hidden" id="server_no" value="">
        </div>

        <!-- Step 2.5: Operator (Server 1 / smspva only) -->
        <div id="operator-step" style="display:none;">
            <label style="display:block;font-size:.8rem;font-weight:600;color:var(--text-primary);margin-bottom:8px;">
                <span style="display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;background:linear-gradient(135deg,#6b23c2,#4D148C);color:white;font-size:.62rem;font-weight:700;margin-right:4px;">3</span>
                Select Network Operator
                <span style="font-size:.65rem;font-weight:600;color:var(--text-muted);margin-left:6px;">(prices vary by carrier)</span>
            </label>
            <div id="operator-list" style="border:1.5px solid rgba(77,20,140,.15);border-radius:12px;overflow:hidden;"></div>
            <input type="hidden" id="selected_operator" value="">
        </div>

        <!-- Step 3: Summary & Buy -->
        <div style="background:var(--btn-bg);border:1.5px solid var(--card-border);border-radius:12px;padding:14px;">
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;">
                <div style="display:flex;align-items:center;gap:10px;">
                    <div style="width:38px;height:38px;border-radius:9px;background:var(--card-bg);border:1px solid var(--card-border);display:flex;align-items:center;justify-content:center;color:var(--text-muted);" id="selected-icon">
                        <i class="fas fa-mobile-screen-button text-sm"></i>
                    </div>
                    <div>
                        <p style="font-size:.68rem;color:var(--text-muted);font-weight:500;">Selected Service</p>
                        <p id="show_name" style="font-weight:700;font-size:.85rem;color:var(--text-primary);">Not Selected</p>
                    </div>
                </div>
                <div style="text-align:right;">
                    <p style="font-size:.68rem;color:var(--text-muted);font-weight:500;">Price</p>
                    <p id="show_amount" style="font-weight:800;font-size:1.1rem;color:#4D148C;font-family:monospace;">&#8358;??</p>
                </div>
            </div>
            <button id="buy-numbers" style="width:100%;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;padding:13px;border-radius:10px;border:none;cursor:pointer;font-size:.88rem;display:flex;align-items:center;justify-content:center;gap:8px;box-shadow:0 4px 14px rgba(77,20,140,.28);transition:all .2s;">
                <i class="fas fa-cart-shopping"></i>Buy Number Now
            </button>
        </div>
    </div>
</div>

</div><!-- /max-w -->

<!-- SMS Received Toast -->
<div id="smsToast" class="fixed top-6 left-1/2 -translate-x-1/2 z-[200] hidden">
    <div style="background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;padding:12px 20px;border-radius:14px;box-shadow:0 8px 32px rgba(77,20,140,.4);display:flex;align-items:center;gap:10px;">
        <i class="fas fa-check-circle text-xl"></i>
        <div><p style="font-weight:700;font-size:.85rem;">SMS Received!</p><p id="smsToastCode" style="font-family:monospace;font-size:1.2rem;font-weight:800;"></p></div>
    </div>
</div>

<script>
const USER_TOKEN = "<?php echo htmlspecialchars($user_token); ?>";
let activePollingIntervals = {};
let allServices = [], topServices = [], currentPage = 1, totalServices = 0, hasMore = false, selectedServer = null, loadingMore = false;

// -- 5SIM (S3) state -----------------------------------------------------------
let s3SelectedCountry = '';
let s3Products = [];
let s3ActiveOrders = {};  // orderId -> interval

// -- SMS-Bus (S4) state --------------------------------------------------------
let s4SelectedCountry = 0;
let s4Projects = {};
let s4ActiveOrders = {};  // orderId -> interval

// -- Server toggle -------------------------------------------------------------
let currentServerMode = 's2'; // updated on DOMContentLoaded to whichever server is active

function switchServer(type) {
    currentServerMode = type;
    const s1 = document.getElementById('server-select-s1');
    const s2 = document.getElementById('server-select');
    const s3 = document.getElementById('server-select-s3');
    const s4 = document.getElementById('server-select-s4');
    const t1 = document.getElementById('tabS1');
    const t2 = document.getElementById('tabS2');
    const t3 = document.getElementById('tabS3');
    const t4 = document.getElementById('tabS4');

    // Hide all selects first
    s1.style.display = 'none'; s2.style.display = 'none';
    if (s3) s3.style.display = 'none';
    if (s4) s4.style.display = 'none';
    s1.value = ''; s2.value = '';
    if (s3) s3.value = '';
    if (s4) s4.value = '';

    // Reset tab styles
    t1.className = 'srv-tab'; t2.className = 'srv-tab';
    if (t3) t3.className = 'srv-tab';
    if (t4) t4.className = 'srv-tab';

    if (type === 's1') {
        t1.className = 'srv-tab s1-active';
        s1.style.display = 'block';
    } else if (type === 's2') {
        t2.className = 'srv-tab s2-active';
        s2.style.display = 'block';
    } else if (type === 's3' && s3) {
        t3.className = 'srv-tab s3-active';
        s3.style.display = 'block';
    } else if (type === 's4' && s4) {
        t4.className = 'srv-tab s4-active';
        s4.style.display = 'block';
    }

    // Reset everything
    selectedServer = null; currentPage = 1; totalServices = 0; hasMore = false;
    allServices = []; topServices = [];
    s3SelectedCountry = ''; s3Products = [];
    s4SelectedCountry = 0; s4Projects = {};
    document.getElementById('server_no').value = '';
    document.getElementById('service_code').value = '';
    document.getElementById('selected_operator').value = '';
    document.getElementById('show_name').innerText = 'Not Selected';
    document.getElementById('show_amount').innerText = '\u20A6??';
    document.getElementById('selected-icon').innerHTML = '<i class="fas fa-mobile-screen-button text-sm"></i>';
    document.getElementById('service-container').classList.add('hidden');
    document.getElementById('service-empty').classList.add('hidden');
    document.getElementById('load-more-container').classList.add('hidden');
    document.getElementById('operator-step').style.display = 'none';
    document.getElementById('operator-list').innerHTML = '';
    document.getElementById('list').innerHTML = '';
    const sk = document.getElementById('service-skeleton');
    sk.classList.add('hidden'); sk.style.display = 'none';
    document.getElementById('search_op').setAttribute('disabled', true);
    document.getElementById('search_op').value = '';
}

// Wire Server1 select to the same handler as Server2
document.getElementById('server-select-s1').addEventListener('change', function () {
    const server = this.value;
    if (!server) return;
    // Trigger the same flow as the original server-select change
    selectedServer = server;
    document.getElementById('server_no').value = server;
    document.getElementById('service_code').value = '';
    document.getElementById('selected_operator').value = '';
    document.getElementById('show_name').innerText = 'Not Selected';
    document.getElementById('show_amount').innerText = '\u20A6??';
    document.getElementById('selected-icon').innerHTML = '<i class="fas fa-mobile-screen-button text-sm"></i>';
    document.getElementById('service-container').classList.add('hidden');
    document.getElementById('service-empty').classList.add('hidden');
    document.getElementById('load-more-container').classList.add('hidden');
    document.getElementById('operator-step').style.display = 'none';
    document.getElementById('operator-list').innerHTML = '';
    const skel = document.getElementById('service-skeleton');
    skel.classList.remove('hidden'); skel.style.display = 'flex';
    document.getElementById('search_op').setAttribute('disabled', true);
    document.getElementById('search_op').value = '';
    currentPage = 1; totalServices = 0; hasMore = false; allServices = []; topServices = [];
    loadServices(1);
});

// -- Country selection (Server2 � original, untouched) -------------------------
document.getElementById('server-select').addEventListener('change', function () {
    const server = this.value;
    if (!server) return;

    selectedServer = server;
    currentPage = 1;
    totalServices = 0;
    hasMore = false;
    allServices = [];
    topServices = [];

    document.getElementById('server_no').value = server;
    document.getElementById('service_code').value = '';
    document.getElementById('show_name').innerText = 'Not Selected';
    document.getElementById('show_amount').innerText = '\u20A6??';
    document.getElementById('selected-icon').innerHTML = '<i class="fas fa-mobile-screen-button text-sm"></i>';

    document.getElementById('service-container').classList.add('hidden');
    document.getElementById('service-empty').classList.add('hidden');
    document.getElementById('load-more-container').classList.add('hidden');

    const skel = document.getElementById('service-skeleton');
    skel.classList.remove('hidden');
    skel.style.display = 'flex';

    document.getElementById('search_op').setAttribute('disabled', true);
    document.getElementById('search_op').value = '';

    loadServices(1);
});

// -- Load services from API ---------------------------------------------------
function loadServices(page) {
    page = page || 1;
    fetch(`../api/service/getService?token=${USER_TOKEN}&server=${selectedServer}&page=${page}&limit=50`)
        .then(r => r.json())
        .then(data => {
            const skel = document.getElementById('service-skeleton');
            skel.classList.add('hidden');
            skel.style.display = 'none';

            if (data.status !== '200') {
                document.getElementById('service-empty').classList.remove('hidden');
                document.getElementById('service-empty').querySelector('p').innerText = data.message || 'No services available.';
                return;
            }

            if (page === 1) {
                topServices = data.top_services || [];
                allServices = data.service || [];
                totalServices = data.pagination ? data.pagination.total : 0;
                hasMore = data.pagination ? data.pagination.has_more : false;
            } else {
                allServices = allServices.concat(data.service || []);
                hasMore = data.pagination ? data.pagination.has_more : false;
            }

            renderServices();
            document.getElementById('load-more-container').classList[hasMore ? 'remove' : 'add']('hidden');

            if (topServices.length === 0 && allServices.length === 0) {
                document.getElementById('service-empty').classList.remove('hidden');
                return;
            }

            document.getElementById('service-container').classList.remove('hidden');
            document.getElementById('search_op').removeAttribute('disabled');
        })
        .catch(() => {
            const skel = document.getElementById('service-skeleton');
            skel.classList.add('hidden');
            skel.style.display = 'none';
            document.getElementById('service-empty').classList.remove('hidden');
            showNotification('Failed to load services. Please try again.', 'error');
        });
}

// -- Render service list ------------------------------------------------------
function renderServices() {
    const list = document.getElementById('list');
    if (currentPage === 1) list.innerHTML = '';

    // Popular services header + items
    if (currentPage === 1 && topServices.length > 0) {
        const h = document.createElement('li');
        h.style.cssText = 'padding:7px 14px;font-size:.65rem;font-weight:700;color:#4D148C;text-transform:uppercase;letter-spacing:.1em;background:rgba(77,20,140,.05);display:flex;align-items:center;gap:6px;';
        h.innerHTML = '<i class="fas fa-star text-yellow-500"></i>Popular Services';
        list.appendChild(h);
        topServices.forEach(svc => list.appendChild(createServiceItem(svc)));
    }

    // All services header + items
    if (currentPage === 1 && allServices.length > 0) {
        const h = document.createElement('li');
        h.style.cssText = 'padding:7px 14px;font-size:.65rem;font-weight:700;color:var(--text-muted);text-transform:uppercase;letter-spacing:.1em;background:var(--btn-bg);margin-top:4px;';
        h.innerHTML = '<i class="fas fa-list mr-1"></i>All Services';
        list.appendChild(h);
    }
    allServices.forEach(svc => list.appendChild(createServiceItem(svc)));
}

// -- Load more services -------------------------------------------------------
function loadMoreServices() {
    if (loadingMore || !hasMore) return;
    loadingMore = true;
    const btn = document.getElementById('load-more-btn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin text-xs"></i>Loading...';
    currentPage++;

    const searchVal = document.getElementById('search_op').value.trim();
    const searchParam = searchVal ? `&search=${encodeURIComponent(searchVal)}` : '';

    fetch(`../api/service/getService?token=${USER_TOKEN}&server=${selectedServer}&page=${currentPage}&limit=50${searchParam}`)
        .then(r => r.json())
        .then(data => {
            if (data.status === '200') {
                allServices = allServices.concat(data.service || []);
                hasMore = data.pagination ? data.pagination.has_more : false;
                renderServices();
                document.getElementById('load-more-container').classList[hasMore ? 'remove' : 'add']('hidden');
            }
        })
        .catch(() => {
            showNotification('Failed to load more services.', 'error');
        })
        .finally(() => {
            loadingMore = false;
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-chevron-down text-xs"></i>Load More Services';
        });
}

// -- Create a single service list item ----------------------------------------
function createServiceItem(svc) {
    const li = document.createElement('li');
    li.className = 'service-item';
    li.setAttribute('data-service-id', svc.id);
    li.setAttribute('data-service-name', svc.service_name);
    li.setAttribute('data-service-price', svc.service_price);
    li.setAttribute('data-service-logo', svc.logo_url);
    li.setAttribute('data-provider', svc.provider || 'smscodes');
    li.setAttribute('data-operators', JSON.stringify(svc.operators || []));
    li.style.cssText = 'display:flex;align-items:center;gap:10px;padding:10px 14px;cursor:pointer;transition:background .15s;border-bottom:1px solid var(--card-border);';

    li.innerHTML = `
        <img src="${svc.logo_url}" alt="${svc.service_name}" 
             style="width:34px;height:34px;border-radius:8px;object-fit:contain;border:1px solid var(--card-border);background:white;padding:2px;flex-shrink:0;"
             onerror="this.src='https://i.ibb.co/ySRhxqh/default.png'">
        <div style="flex:1;min-width:0;">
            <p class="svc-name" style="font-weight:600;font-size:.8rem;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${svc.service_name}</p>
        </div>
        <span style="font-weight:700;font-size:.82rem;color:#4D148C;font-family:monospace;flex-shrink:0;">&#8358;${svc.service_price}</span>
    `;

    // Hover effects
    li.addEventListener('mouseenter', () => li.style.background = 'var(--btn-bg)');
    li.addEventListener('mouseleave', () => {
        if (!li.classList.contains('selected')) li.style.background = '';
    });

    // Click to select
    li.addEventListener('click', function () {
        // Deselect all
        document.querySelectorAll('.service-item').forEach(i => {
            i.classList.remove('selected');
            i.style.background = '';
            i.style.borderLeft = '';
        });

        // Select this one
        this.classList.add('selected');
        this.style.background = 'rgba(77,20,140,.05)';
        this.style.borderLeft = '3px solid #4D148C';

        const name     = this.getAttribute('data-service-name');
        const price    = this.getAttribute('data-service-price');
        const svcId    = this.getAttribute('data-service-id');
        const logo     = this.getAttribute('data-service-logo');
        const provider = this.getAttribute('data-provider') || 'smscodes';
        const opsRaw   = this.getAttribute('data-operators') || '[]';
        let   operators = [];
        try { operators = JSON.parse(opsRaw); } catch(e) {}

        document.getElementById('show_name').innerText = name;
        document.getElementById('show_amount').innerText = '\u20A6' + price;
        document.getElementById('service_code').value = svcId;
        document.getElementById('selected_operator').value = '';

        const icon = document.getElementById('selected-icon');
        icon.innerHTML = `<img src="${logo}" style="width:26px;height:26px;border-radius:7px;object-fit:contain;" onerror="this.parentNode.innerHTML='<i class=\\'fas fa-mobile-screen-button text-sm\\'></i>'">`;

        // -- Operator panel (Server 1 only) ----------------------------------
        const opStep = document.getElementById('operator-step');
        const opList = document.getElementById('operator-list');
        opList.innerHTML = '';
        document.getElementById('selected_operator').value = '';

        if (provider === 'smspva' && operators.length > 0) {
            opStep.style.display = 'block';

            // Strip trailing country suffix like _UK, _US, _NG etc. � display only
            const formatOperatorName = (raw) => {
                if (!raw || raw === 'any') return 'Any Available';
                // Remove _XX or _XXX suffix where X is uppercase letter
                return raw.replace(/_[A-Z]{2,3}$/, '').replace(/_/g, ' ');
            };

            operators.forEach((op, idx) => {
                const row = document.createElement('div');
                row.className = 'operator-row';
                row.setAttribute('data-op', op.operator);
                row.setAttribute('data-op-price', op.ngn_price);
                row.style.cssText = 'display:flex;align-items:center;justify-content:space-between;padding:10px 14px;cursor:pointer;border-bottom:1px solid var(--card-border);transition:background .15s;';
                const displayName = formatOperatorName(op.operator);

                // Count badge � colour by stock level
                const count = parseInt(op.count_available) || 0;
                let countColor, countBg, countLabel;
                if (count >= 999) {
                    countColor = '#4D148C'; countBg = 'rgba(77,20,140,.1)'; countLabel = '999+';
                } else if (count >= 20) {
                    countColor = '#4D148C'; countBg = 'rgba(77,20,140,.1)'; countLabel = count;
                } else if (count >= 5) {
                    countColor = '#d97706'; countBg = 'rgba(217,119,6,.1)';  countLabel = count;
                } else {
                    countColor = '#dc2626'; countBg = 'rgba(220,38,38,.08)'; countLabel = count;
                }
                const countBadge = `<span style="font-size:.62rem;font-weight:700;padding:1px 6px;border-radius:99px;background:${countBg};color:${countColor};border:1px solid ${countColor}33;margin-left:4px;">${countLabel} left</span>`;

                row.innerHTML = `
                    <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
                        <span style="width:16px;height:16px;border-radius:50%;border:2px solid var(--card-border);display:inline-block;flex-shrink:0;" class="op-radio"></span>
                        <span style="font-size:.82rem;font-weight:600;color:var(--text-primary);">${displayName}</span>
                        ${idx === 0 ? '<span style="font-size:.6rem;font-weight:700;padding:1px 6px;border-radius:99px;background:rgba(77,20,140,.1);color:#4D148C;border:1px solid rgba(77,20,140,.2);">Cheapest</span>' : ''}
                        ${countBadge}
                    </div>
                    <span style="font-weight:800;font-size:.88rem;color:#4D148C;font-family:monospace;flex-shrink:0;margin-left:8px;">&#8358;${op.ngn_price}</span>
                `;

                row.addEventListener('click', () => {
                    // Deselect all operator rows
                    document.querySelectorAll('.operator-row').forEach(r => {
                        r.style.background = '';
                        r.querySelector('.op-radio').style.cssText = 'width:16px;height:16px;border-radius:50%;border:2px solid var(--card-border);display:inline-block;flex-shrink:0;';
                    });
                    // Select this one
                    row.style.background = 'rgba(77,20,140,.05)';
                    row.querySelector('.op-radio').style.cssText = 'width:16px;height:16px;border-radius:50%;border:5px solid #4D148C;display:inline-block;flex-shrink:0;background:#d1fae5;';
                    document.getElementById('selected_operator').value = op.operator === 'any' ? '' : op.operator;
                    document.getElementById('show_amount').innerText = '\u20A6' + op.ngn_price;
                });

                opList.appendChild(row);
            });

            // Auto-select the cheapest (first) operator
            if (opList.firstChild) opList.firstChild.click();

        } else if (provider === 'smspva' && operators.length === 0) {
            // smspva service but no operator data in cache � show a note
            opStep.style.display = 'block';
            opList.innerHTML = '<div style="padding:10px 14px;font-size:.78rem;color:var(--text-muted);"><i class="fas fa-circle-info mr-1"></i>Operator data not yet synced. The cheapest available will be selected automatically.</div>';
        } else {
            // smscodes: hide operator panel
            opStep.style.display = 'none';
        }
        // -- End operator panel -----------------------------------------------
    });

    return li;
}

// -- Search filter ------------------------------------------------------------
// -- Search filter (replaces old client-side-only filter) ---------------------
let searchDebounceTimer = null;

document.getElementById('search_op').addEventListener('input', function () {
    const q = this.value.trim();

    clearTimeout(searchDebounceTimer);

    // If search is cleared, reload the full list
    if (q === '') {
        currentPage = 1;
        allServices = [];
        topServices = [];
        if (currentServerMode === 's3') {
            renderS3Services(s3Products, '');
        } else {
            loadServices(1);
        }
        return;
    }

    // Debounce: wait 400ms after the user stops typing before hitting the API
    searchDebounceTimer = setTimeout(() => {
        if (currentServerMode === 's3') {
            renderS3Services(s3Products, q);
            return;
        }
        if (currentServerMode === 's4') {
            renderS4Services(s4Projects, q);
            return;
        }
        currentPage = 1;
        allServices = [];
        topServices = [];

        const list = document.getElementById('list');
        list.innerHTML = '';

        // Show skeleton while loading
        const skel = document.getElementById('service-skeleton');
        skel.classList.remove('hidden');
        skel.style.display = 'flex';
        document.getElementById('service-container').classList.add('hidden');
        document.getElementById('load-more-container').classList.add('hidden');

        fetch(`../api/service/getService?token=${USER_TOKEN}&server=${selectedServer}&page=1&limit=50&search=${encodeURIComponent(q)}`)
            .then(r => r.json())
            .then(data => {
                skel.classList.add('hidden');
                skel.style.display = 'none';

                if (data.status !== '200') {
                    document.getElementById('service-empty').classList.remove('hidden');
                    document.getElementById('service-empty').querySelector('p').innerText = data.message || 'No services found.';
                    document.getElementById('service-container').classList.add('hidden');
                    return;
                }

                topServices = data.top_services || [];
                allServices = data.service || [];
                totalServices = data.pagination ? data.pagination.total : 0;
                hasMore = data.pagination ? data.pagination.has_more : false;

                if (topServices.length === 0 && allServices.length === 0) {
                    document.getElementById('service-empty').classList.remove('hidden');
                    document.getElementById('service-empty').querySelector('p').innerText = 'No services match your search.';
                    document.getElementById('service-container').classList.add('hidden');
                    return;
                }

                document.getElementById('service-empty').classList.add('hidden');
                document.getElementById('service-container').classList.remove('hidden');
                renderServices();
                document.getElementById('load-more-container').classList[hasMore ? 'remove' : 'add']('hidden');
            })
            .catch(() => {
                skel.classList.add('hidden');
                skel.style.display = 'none';
                showNotification('Search failed. Please try again.', 'error');
            });
    }, 400);
});

// -- Buy Number ---------------------------------------------------------------
document.getElementById('buy-numbers').addEventListener('click', function () {
    // -- S3 (5SIM) buy flow ----------------------------------------------------
    if (currentServerMode === 's3') {
        const product = document.getElementById('service_code').value;
        if (!s3SelectedCountry) { showNotification('Please select a country first.', 'error'); return; }
        if (!product) { showNotification('Please select a service.', 'error'); return; }

        const btn = this;
        btn.disabled = true;
        btn.innerHTML = '<span style="display:inline-block;width:14px;height:14px;border:2px solid white;border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite;"></span> Finding Number...';

        fetch('../ajax/fivesim_handler.php', {
            method: 'POST',
            headers: {'Content-Type':'application/x-www-form-urlencoded'},
            body: 'action=buy_number&country_key=' + encodeURIComponent(s3SelectedCountry) + '&product=' + encodeURIComponent(product)
        })
        .then(r => r.json())
        .then(data => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-cart-shopping"></i>Buy Number Now';
            if (data.status === '1') {
                showNotification('Number purchased! Waiting for SMS...', 'success');
                if (data.new_balance !== undefined) {
                    document.getElementById('heroBalance').innerText = '\u20A6' + data.new_balance;
                }
                loadS3ActiveOrders();
            } else {
                showNotification(data.msg || 'Purchase failed.', 'error');
            }
        })
        .catch(() => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-cart-shopping"></i>Buy Number Now';
            showNotification('An error occurred. Please try again.', 'error');
        });
        return;
    }

    // -- S4 (SMS-Bus) buy flow -------------------------------------------------
    if (currentServerMode === 's4') {
        const projectId = document.getElementById('service_code').value;
        if (!s4SelectedCountry) { showNotification('Please select a country first.', 'error'); return; }
        if (!projectId) { showNotification('Please select a service.', 'error'); return; }

        const btn = this;
        btn.disabled = true;
        btn.innerHTML = '<span style="display:inline-block;width:14px;height:14px;border:2px solid white;border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite;"></span> Finding Number...';

        fetch('../ajax/smsbus_handler.php', {
            method: 'POST',
            headers: {'Content-Type':'application/x-www-form-urlencoded'},
            body: 'action=buy_number&country_id=' + encodeURIComponent(s4SelectedCountry) + '&project_id=' + encodeURIComponent(projectId)
        })
        .then(r => r.json())
        .then(data => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-cart-shopping"></i>Buy Number Now';
            if (data.status === '1') {
                showNotification('Number purchased! Waiting for SMS...', 'success');
                if (data.new_balance !== undefined) {
                    document.getElementById('heroBalance').innerText = '\u20A6' + data.new_balance;
                }
                loadS4ActiveOrders();
            } else {
                showNotification(data.msg || 'Purchase failed.', 'error');
            }
        })
        .catch(() => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-cart-shopping"></i>Buy Number Now';
            showNotification('An error occurred. Please try again.', 'error');
        });
        return;
    }

    // -- Original S1/S2 buy flow -----------------------------------------------
    const server   = document.getElementById('server_no').value;
    const service  = document.getElementById('service_code').value;
    const operator = document.getElementById('selected_operator').value;

    if (!server) { showNotification('Please select a country first.', 'error'); return; }
    if (!service) { showNotification('Please select a service.', 'error'); return; }

    // For Server 1 (smspva), require operator selection if operator panel is visible
    const opStep = document.getElementById('operator-step');
    const opList = document.getElementById('operator-list');
    if (opStep.style.display !== 'none' && opList.children.length > 1 && !operator) {
        showNotification('Please select a network operator.', 'error'); return;
    }

    const btn = this;
    btn.disabled = true;
    btn.innerHTML = '<span style="display:inline-block;width:14px;height:14px;border:2px solid white;border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite;"></span> Finding Number...';

    const opParam = operator ? `&operator=${encodeURIComponent(operator)}` : '';
    fetch(`../api/service/buynumber?token=${USER_TOKEN}&server=${server}&service=${service}${opParam}`)
        .then(r => {
            // Read raw text first so we can diagnose non-JSON errors
            return r.text().then(text => {
                try {
                    return JSON.parse(text);
                } catch (e) {
                    // PHP returned non-JSON � surface it
                    throw new Error('Server error: ' + text.substring(0, 200));
                }
            });
        })
        .then(data => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-cart-shopping"></i>Buy Number Now';

            if (data.status === '200') {
                showNotification(data.message, 'success');
                loadActiveOrders();
            } else {
                showNotification(data.message || 'Purchase failed.', 'error');
            }
        })
        .catch((err) => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-cart-shopping"></i>Buy Number Now';
            showNotification(err.message || 'An error occurred. Please try again.', 'error');
        });
});

// -- Load Active Orders -------------------------------------------------------
function loadActiveOrders() {
    fetch(`../api/service/ActiveNumber?token=${USER_TOKEN}`)
        .then(r => r.json())
        .then(data => {
            const panel = document.getElementById('activeOrdersPanel');
            const list  = document.getElementById('activeOrdersList');
            const badge = document.getElementById('activeCountBadge');

            if (data.status === '200' && data.data && data.data.length > 0) {
                // Filter out orders that already have SMS (shouldn't be active)
                const waitingOrders = data.data.filter(o => !o.sms_text || o.sms_text === '');
                
                if (waitingOrders.length > 0) {
                    panel.classList.remove('hidden');
                    // Remove old S1/S2 cards only
                    document.querySelectorAll('[id^="order-card-"]:not([id^="order-card-s3-"]):not([id^="order-card-s4-"])').forEach(c => c.remove());

                    waitingOrders.forEach(order => {
                        const card = buildOrderCard(order);
                        list.appendChild(card);

                        // Start polling for SMS if not already
                        if (!activePollingIntervals[order.order_id]) {
                            activePollingIntervals[order.order_id] = setInterval(() => pollSMS(order.order_id), 5000);
                        }

                        // Start countdown timer
                        startCountdown(order.order_id, order.left_time);

                        // Disable cancel button after 1 minute from purchase
                        // left_time = ms remaining. If provider is smspva total=10min, else 20min
                        // We use a safe approach: cancel allowed if left_time > total - 60s
                        if (order.left_time) {
                            const leftMs = parseInt(order.left_time);
                            const providerTotal = 300000; // 5 minutes
                            const orderElapsed = providerTotal - leftMs;
                            const cancelBtn = document.getElementById('cancel-btn-' + order.order_id);
                            if (orderElapsed >= 60000) {
                                if (cancelBtn) { cancelBtn.disabled = true; cancelBtn.style.opacity = '0.4'; cancelBtn.style.cursor = 'not-allowed'; cancelBtn.title = 'Cancel window expired'; }
                            } else {
                                setTimeout(() => {
                                    const btn = document.getElementById('cancel-btn-' + order.order_id);
                                    if (btn) { btn.disabled = true; btn.style.opacity = '0.4'; btn.style.cursor = 'not-allowed'; btn.title = 'Cancel window expired'; }
                                }, 60000 - orderElapsed);
                            }
                        }
                    });
                } else {
                    // No waiting orders ? remove S1/S2 cards
                    document.querySelectorAll('[id^="order-card-"]:not([id^="order-card-s3-"]):not([id^="order-card-s4-"])').forEach(c => c.remove());
                    Object.keys(activePollingIntervals).forEach(id => {
                        clearInterval(activePollingIntervals[id]);
                        delete activePollingIntervals[id];
                    });
                    // Hide panel if no S3/S4 cards either
                    if (!document.querySelectorAll('[id^="order-card-s3-"], [id^="order-card-s4-"]').length) {
                        panel.classList.add('hidden');
                    }
                }
            } else {
                // Remove S1/S2 cards
                document.querySelectorAll('[id^="order-card-"]:not([id^="order-card-s3-"]):not([id^="order-card-s4-"])').forEach(c => c.remove());
                // Clear all S1/S2 polling intervals
                Object.keys(activePollingIntervals).forEach(id => {
                    clearInterval(activePollingIntervals[id]);
                    delete activePollingIntervals[id];
                });
                // Hide panel if no S3/S4 cards either
                if (!document.querySelectorAll('[id^="order-card-s3-"], [id^="order-card-s4-"]').length) {
                    panel.classList.add('hidden');
                }
            }
        })
        .catch(() => {});
}

// -- Build Order Card ---------------------------------------------------------
function buildOrderCard(order) {
    const div = document.createElement('div');
    div.id = 'order-card-' + order.order_id;
    div.className = 'order-card';

    const hasSms = order.sms_text && order.sms_text !== '';
    const logo   = order.service_logo || 'https://i.ibb.co/ySRhxqh/default.png';
    const pBadge = '';

    div.innerHTML = `
        <div style="display:flex;align-items:flex-start;gap:10px;">
            <img src="${logo}" alt="${order.service_name}" 
                 style="width:38px;height:38px;border-radius:9px;object-fit:contain;border:1px solid var(--card-border);background:white;padding:2px;flex-shrink:0;"
                 onerror="this.src='https://i.ibb.co/ySRhxqh/default.png'">
            <div style="flex:1;min-width:0;">
                <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:8px;">
                    <div>
                        <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);">${order.service_name}${pBadge}</p>
                        <p style="font-size:.72rem;color:var(--text-muted);font-family:monospace;">${order.number}</p>
                    </div>
                    <div style="text-align:right;">
                        <p style="font-size:.68rem;color:var(--text-muted);">Cost</p>
                        <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);font-family:monospace;">&#8358;${parseFloat(order.service_price).toLocaleString('en-NG', {minimumFractionDigits:2})}</p>
                    </div>
                </div>
                ${hasSms
                    ? `<div style="background:rgba(77,20,140,.07);border:1px solid rgba(77,20,140,.2);border-radius:10px;padding:10px;display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                        <i class="fas fa-envelope-open-text text-emerald-500 text-base"></i>
                        <div><p style="font-size:.7rem;color:#4D148C;font-weight:600;">OTP Received</p><p style="font-weight:800;font-size:1.2rem;color:#4D148C;font-family:monospace;letter-spacing:.1em;">${order.sms_text}</p></div>
                      </div>`
                    : `<div style="background:var(--btn-bg);border:1px solid var(--card-border);border-radius:10px;padding:10px;display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                        <div style="width:16px;height:16px;border:2px solid #4D148C;border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite;flex-shrink:0;"></div>
                        <div style="flex:1;"><p style="font-size:.72rem;color:var(--text-muted);">Waiting for SMS...</p></div>
                        <span id="timer-${order.order_id}" style="font-family:monospace;font-size:.82rem;font-weight:700;color:#d97706;flex-shrink:0;">--:--</span>
                      </div>`}
                <div style="display:flex;gap:6px;flex-wrap:wrap;">
                    <button onclick="copyNumber('${order.number}')" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:var(--btn-bg);border:1px solid var(--card-border);color:var(--text-primary);cursor:pointer;display:flex;align-items:center;gap:5px;">
                        <i class="fa-regular fa-copy text-xs"></i>Copy Number
                    </button>
                    ${hasSms
                        ? `<button onclick="copySms('${order.sms_text}')" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:rgba(77,20,140,.07);border:1px solid rgba(77,20,140,.2);color:#4D148C;cursor:pointer;display:flex;align-items:center;gap:5px;"><i class="fa-regular fa-copy text-xs"></i>Copy OTP</button>`
                        : `<button onclick="cancelNumber('${order.order_id}')" id="cancel-btn-${order.order_id}" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:rgba(239,68,68,.07);border:1px solid rgba(239,68,68,.18);color:#dc2626;cursor:pointer;display:flex;align-items:center;gap:5px;"><i class="fas fa-xmark text-xs"></i>Cancel & Refund</button>`}
                </div>
            </div>
        </div>
    `;
    return div;
}

// -- Poll SMS -----------------------------------------------------------------
function pollSMS(orderId) {
    fetch(`../api/service/getMessage?token=${USER_TOKEN}&order_id=${orderId}`)
        .then(r => r.json())
        .then(data => {
            if (data.status === '200' && data.sms) {
                // SMS received!
                clearInterval(activePollingIntervals[orderId]);
                delete activePollingIntervals[orderId];
                showSmsToast(data.sms);
                
                // Update card in place to show OTP
                const card = document.getElementById('order-card-' + orderId);
                if (card) {
                    // Find the waiting div and replace with OTP
                    const waitingDiv = card.querySelector('[style*="animation:spin"]');
                    if (waitingDiv) {
                        const container = waitingDiv.closest('div[style*="border-radius:10px"]');
                        if (container) {
                            container.style.background = 'rgba(77,20,140,.07)';
                            container.style.border = '1px solid rgba(77,20,140,.2)';
                            container.innerHTML = `<i class="fas fa-envelope-open-text text-emerald-500 text-base"></i>
                                <div><p style="font-size:.7rem;color:#4D148C;font-weight:600;">OTP Received</p><p style="font-weight:800;font-size:1.2rem;color:#4D148C;font-family:monospace;letter-spacing:.1em;">${data.sms}</p></div>`;
                        }
                    }
                    // Replace cancel button with copy button
                    const cancelBtn = document.getElementById('cancel-btn-' + orderId);
                    if (cancelBtn) {
                        cancelBtn.outerHTML = `<button onclick="copySms('${data.sms}')" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:rgba(77,20,140,.07);border:1px solid rgba(77,20,140,.2);color:#4D148C;cursor:pointer;display:flex;align-items:center;gap:5px;"><i class="fa-regular fa-copy text-xs"></i>Copy OTP</button>`;
                    }
                }
                
                // Show OTP for 1 minute then redirect to My Numbers
                setTimeout(() => {
                    window.location.href = 'my-number';
                }, 60000);
            } else if (data.status === '500') {
                // Error or expired
                clearInterval(activePollingIntervals[orderId]);
                delete activePollingIntervals[orderId];
                showNotification(data.message || 'Order expired.', 'error');
                const card = document.getElementById('order-card-' + orderId);
                if (card) card.remove();
            }
            // status 300 = still waiting, do nothing
        })
        .catch(() => {});
}

// -- Countdown Timer ----------------------------------------------------------
function startCountdown(orderId, leftMs) {
    const el = document.getElementById('timer-' + orderId);
    if (!el || !leftMs) return;

    let ms = parseInt(leftMs);
    if (isNaN(ms) || ms <= 0) { if (el) el.innerText = '00:00'; return; }

    const tick = setInterval(() => {
        ms -= 1000;
        if (ms <= 0) {
            clearInterval(tick);
            if (el) el.innerText = '00:00';
            // Trigger a refresh to handle expiry
            setTimeout(() => loadActiveOrders(), 2000);
            return;
        }
        const totalSec = Math.floor(ms / 1000);
        const m = Math.floor(totalSec / 60).toString().padStart(2, '0');
        const s = (totalSec % 60).toString().padStart(2, '0');
        if (el) el.innerText = m + ':' + s;
    }, 1000);
}

// -- Cancel Number ------------------------------------------------------------
function cancelNumber(orderId) {
    const btn = document.getElementById('cancel-btn-' + orderId);
    if (btn) {
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin text-xs"></i>Cancelling...';
    }

    fetch(`../api/service/cancelNumber?token=${USER_TOKEN}&order_id=${orderId}`)
        .then(r => r.json())
        .then(data => {
            if (data.status === '200') {
                showNotification(data.message || 'Cancelled & refunded.', 'success');
                clearInterval(activePollingIntervals[orderId]);
                delete activePollingIntervals[orderId];
                loadActiveOrders();
            } else {
                showNotification(data.message || 'Could not cancel.', 'error');
                if (btn) {
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-xmark text-xs"></i>Cancel & Refund';
                }
            }
        })
        .catch(() => {
            showNotification('An error occurred.', 'error');
            if (btn) {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-xmark text-xs"></i>Cancel & Refund';
            }
        });
}

// -- Helpers -----------------------??------------------------------------------
function copyNumber(num) {
    navigator.clipboard.writeText(num).then(() => showNotification('Number copied!', 'success'));
}
function copySms(code) {
    navigator.clipboard.writeText(code).then(() => showNotification('OTP copied!', 'success'));
}

function showSmsToast(code) {
    const toast = document.getElementById('smsToast');
    document.getElementById('smsToastCode').innerText = code;
    toast.classList.remove('hidden');
    setTimeout(() => toast.classList.add('hidden'), 6000);
}

function showNotification(message, type) {
    const colors = {
        success: 'linear-gradient(135deg,#4D148C,#6b23c2)',
        error: 'linear-gradient(135deg,#dc2626,#ef4444)',
        info: 'linear-gradient(135deg,#0ea5e9,#0284c7)'
    };
    const icons = {
        success: 'fa-check-circle',
        error: 'fa-circle-exclamation',
        info: 'fa-circle-info'
    };
    const el = document.createElement('div');
    el.style.cssText = `position:fixed;bottom:6rem;left:50%;transform:translateX(-50%);z-index:9999;background:${colors[type] || colors.info};color:white;padding:10px 18px;border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.2);display:flex;align-items:center;gap:8px;font-size:.82rem;font-weight:600;white-space:nowrap;max-width:90vw;`;
    el.innerHTML = `<i class="fas ${icons[type] || icons.info}"></i>${message}`;
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 4000);
}

// -- S3 (5SIM) Country select --------------------------------------------------
const s3Select = document.getElementById('server-select-s3');
if (s3Select) {
    s3Select.addEventListener('change', function () {
        s3SelectedCountry = this.value;
        if (!s3SelectedCountry) return;

        document.getElementById('service_code').value = '';
        document.getElementById('show_name').innerText = 'Not Selected';
        document.getElementById('show_amount').innerText = '\u20A6??';
        document.getElementById('selected-icon').innerHTML = '<i class="fas fa-mobile-screen-button text-sm"></i>';
        document.getElementById('service-container').classList.add('hidden');
        document.getElementById('service-empty').classList.add('hidden');
        document.getElementById('operator-step').style.display = 'none';
        document.getElementById('list').innerHTML = '';
        document.getElementById('search_op').setAttribute('disabled', true);
        document.getElementById('search_op').value = '';

        const skel = document.getElementById('service-skeleton');
        skel.classList.remove('hidden'); skel.style.display = 'flex';

        // Load products from 5SIM handler
        fetch('../ajax/fivesim_handler.php', {
            method: 'POST',
            headers: {'Content-Type':'application/x-www-form-urlencoded'},
            body: 'action=get_country_products&country_key=' + encodeURIComponent(s3SelectedCountry)
        })
        .then(r => r.json())
        .then(data => {
            skel.classList.add('hidden'); skel.style.display = 'none';
            if (data.status !== '1' || !data.products || Object.keys(data.products).length === 0) {
                document.getElementById('service-empty').classList.remove('hidden');
                document.getElementById('service-empty').querySelector('p').innerText = 'No products available for this country.';
                return;
            }
            s3Products = data.products;
            renderS3Services(s3Products, '');
            document.getElementById('service-container').classList.remove('hidden');
            document.getElementById('search_op').removeAttribute('disabled');
        })
        .catch(() => {
            skel.classList.add('hidden'); skel.style.display = 'none';
            document.getElementById('service-empty').classList.remove('hidden');
            showNotification('Failed to load services.', 'error');
        });
    });
}

// -- Render 5SIM service list --------------------------------------------------
function renderS3Services(products, filter) {
    const list = document.getElementById('list');
    list.innerHTML = '';
    const q = filter.toLowerCase();

    const entries = Object.entries(products)
        .filter(([key]) => !q || key.toLowerCase().includes(q))
        .sort((a, b) => a[0].localeCompare(b[0]));

    if (entries.length === 0) {
        document.getElementById('service-empty').classList.remove('hidden');
        document.getElementById('service-container').classList.add('hidden');
        return;
    }
    document.getElementById('service-empty').classList.add('hidden');
    document.getElementById('service-container').classList.remove('hidden');

    entries.forEach(([product, info]) => {
        const li = document.createElement('li');
        li.className = 'service-item';
        li.setAttribute('data-s3-product', product);
        li.setAttribute('data-s3-price', info.our_price);
        li.setAttribute('data-s3-qty', info.qty);
        li.style.cssText = 'display:flex;align-items:center;gap:10px;padding:10px 14px;cursor:pointer;transition:background .15s;border-bottom:1px solid var(--card-border);';

        const qtyColor = info.qty > 100 ? '#059669' : info.qty > 10 ? '#d97706' : '#dc2626';
        const displayName = product.charAt(0).toUpperCase() + product.slice(1);

        li.innerHTML = `
            <div style="width:34px;height:34px;border-radius:8px;background:rgba(16,185,129,.1);border:1px solid rgba(16,185,129,.2);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="fas fa-mobile-alt" style="color:#059669;font-size:.78rem;"></i>
            </div>
            <div style="flex:1;min-width:0;">
                <p style="font-weight:600;font-size:.8rem;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${displayName}</p>
                <p style="font-size:.7rem;color:var(--text-muted);">
                    <span style="color:${qtyColor};font-weight:600;">${info.qty > 999 ? '999+' : info.qty}</span> available
                    
                </p>
            </div>
            <span style="font-weight:700;font-size:.82rem;color:#059669;font-family:monospace;flex-shrink:0;">&#8358;${parseFloat(info.our_price).toLocaleString('en-NG',{minimumFractionDigits:2})}</span>
        `;

        li.addEventListener('mouseenter', () => li.style.background = 'var(--btn-bg)');
        li.addEventListener('mouseleave', () => { if (!li.classList.contains('selected')) li.style.background = ''; });

        li.addEventListener('click', function () {
            document.querySelectorAll('.service-item').forEach(i => {
                i.classList.remove('selected'); i.style.background = ''; i.style.borderLeft = '';
            });
            this.classList.add('selected');
            this.style.background = 'rgba(16,185,129,.05)';
            this.style.borderLeft = '3px solid #059669';

            document.getElementById('service_code').value = product;
            document.getElementById('show_name').innerText = displayName;
            document.getElementById('show_amount').innerText = '\u20A6' + parseFloat(info.our_price).toLocaleString('en-NG', {minimumFractionDigits:2});
            document.getElementById('selected-icon').innerHTML = `<div style="width:26px;height:26px;border-radius:7px;background:rgba(16,185,129,.1);display:flex;align-items:center;justify-content:center;"><i class="fas fa-mobile-alt" style="color:#059669;font-size:.7rem;"></i></div>`;
            document.getElementById('operator-step').style.display = 'none';
        });

        list.appendChild(li);
    });
}

// -- S4 (SMS-Bus) Country select -----------------------------------------------
const s4Select = document.getElementById('server-select-s4');
if (s4Select) {
    s4Select.addEventListener('change', function () {
        s4SelectedCountry = parseInt(this.value) || 0;
        if (!s4SelectedCountry) return;

        document.getElementById('service_code').value = '';
        document.getElementById('show_name').innerText = 'Not Selected';
        document.getElementById('show_amount').innerText = '\u20A6??';
        document.getElementById('selected-icon').innerHTML = '<i class="fas fa-mobile-screen-button text-sm"></i>';
        document.getElementById('service-container').classList.add('hidden');
        document.getElementById('service-empty').classList.add('hidden');
        document.getElementById('operator-step').style.display = 'none';
        document.getElementById('list').innerHTML = '';
        document.getElementById('search_op').setAttribute('disabled', true);
        document.getElementById('search_op').value = '';

        const skel = document.getElementById('service-skeleton');
        skel.classList.remove('hidden'); skel.style.display = 'flex';

        fetch('../ajax/smsbus_handler.php', {
            method: 'POST',
            headers: {'Content-Type':'application/x-www-form-urlencoded'},
            body: 'action=get_country_projects&country_id=' + encodeURIComponent(s4SelectedCountry)
        })
        .then(r => r.json())
        .then(data => {
            skel.classList.add('hidden'); skel.style.display = 'none';
            if (data.status !== '1' || !data.projects || Object.keys(data.projects).length === 0) {
                document.getElementById('service-empty').classList.remove('hidden');
                document.getElementById('service-empty').querySelector('p').innerText = 'No projects available for this country.';
                return;
            }
            s4Projects = data.projects;
            renderS4Services(s4Projects, '');
            document.getElementById('service-container').classList.remove('hidden');
            document.getElementById('search_op').removeAttribute('disabled');
        })
        .catch(() => {
            skel.classList.add('hidden'); skel.style.display = 'none';
            document.getElementById('service-empty').classList.remove('hidden');
            showNotification('Failed to load services.', 'error');
        });
    });
}

// -- Render SMS-Bus (S4) service list ------------------------------------------
function renderS4Services(projects, filter) {
    const list = document.getElementById('list');
    list.innerHTML = '';
    const q = filter.toLowerCase();

    const entries = Object.entries(projects)
        .filter(([, info]) => !q || (info.title || '').toLowerCase().includes(q))
        .sort((a, b) => (a[1].title || '').localeCompare(b[1].title || ''));

    if (entries.length === 0) {
        document.getElementById('service-empty').classList.remove('hidden');
        document.getElementById('service-container').classList.add('hidden');
        return;
    }
    document.getElementById('service-empty').classList.add('hidden');
    document.getElementById('service-container').classList.remove('hidden');

    entries.forEach(([pid, info]) => {
        const li = document.createElement('li');
        li.className = 'service-item';
        li.setAttribute('data-s4-project-id', pid);
        li.setAttribute('data-s4-price', info.our_price);
        li.setAttribute('data-s4-count', info.total_count);
        li.style.cssText = 'display:flex;align-items:center;gap:10px;padding:10px 14px;cursor:pointer;transition:background .15s;border-bottom:1px solid var(--card-border);';

        const countColor = info.total_count > 100 ? '#059669' : info.total_count > 10 ? '#d97706' : '#dc2626';
        const displayName = info.title || ('Project ' + pid);

        li.innerHTML = `
            <div style="width:34px;height:34px;border-radius:8px;background:rgba(217,119,6,.1);border:1px solid rgba(217,119,6,.2);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="fas fa-bus" style="color:#d97706;font-size:.78rem;"></i>
            </div>
            <div style="flex:1;min-width:0;">
                <p style="font-weight:600;font-size:.8rem;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${displayName}</p>
                <p style="font-size:.7rem;color:var(--text-muted);">
                    <span style="color:${countColor};font-weight:600;">${info.total_count > 999 ? '999+' : info.total_count}</span> available
                    
                </p>
            </div>
            <span style="font-weight:700;font-size:.82rem;color:#d97706;font-family:monospace;flex-shrink:0;">&#8358;${parseFloat(info.our_price).toLocaleString('en-NG',{minimumFractionDigits:2})}</span>
        `;

        li.addEventListener('mouseenter', () => li.style.background = 'var(--btn-bg)');
        li.addEventListener('mouseleave', () => { if (!li.classList.contains('selected')) li.style.background = ''; });

        li.addEventListener('click', function () {
            document.querySelectorAll('.service-item').forEach(i => {
                i.classList.remove('selected'); i.style.background = ''; i.style.borderLeft = '';
            });
            this.classList.add('selected');
            this.style.background = 'rgba(217,119,6,.05)';
            this.style.borderLeft = '3px solid #d97706';

            document.getElementById('service_code').value = pid;
            document.getElementById('show_name').innerText = displayName;
            document.getElementById('show_amount').innerText = '\u20A6' + parseFloat(info.our_price).toLocaleString('en-NG', {minimumFractionDigits:2});
            document.getElementById('selected-icon').innerHTML = `<div style="width:26px;height:26px;border-radius:7px;background:rgba(217,119,6,.1);display:flex;align-items:center;justify-content:center;"><i class="fas fa-bus" style="color:#d97706;font-size:.7rem;"></i></div>`;
            document.getElementById('operator-step').style.display = 'none';
        });

        list.appendChild(li);
    });
}

// -- S4 active orders & polling ------------------------------------------------
function loadS4ActiveOrders() {
    fetch('../ajax/smsbus_handler.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'action=get_active_orders'
    })
    .then(r => r.json())
    .then(data => {
        const panel = document.getElementById('activeOrdersPanel');
        const list  = document.getElementById('activeOrdersList');
        const badge = document.getElementById('activeCountBadge');

        // Remove S4 cards that are no longer active
        const activeS4Ids = (data.status === '1' && data.orders) ? data.orders.map(o => 'order-card-s4-' + o.id) : [];
        document.querySelectorAll('[id^="order-card-s4-"]').forEach(card => {
            if (!activeS4Ids.includes(card.id)) {
                clearInterval(s4ActiveOrders[card.id.replace('order-card-s4-', '')]);
                delete s4ActiveOrders[card.id.replace('order-card-s4-', '')];
                card.remove();
            }
        });

        if (data.status !== '1' || !data.orders || data.orders.length === 0) return;

        panel.classList.remove('hidden');

        data.orders.forEach(order => {
            if (document.getElementById('order-card-s4-' + order.id)) return;

            const card = buildS4OrderCard(order);
            list.appendChild(card);

            if (!s4ActiveOrders[order.id]) {
                s4ActiveOrders[order.id] = setInterval(() => pollS4SMS(order.id), 5000);
            }
            const s4TimeLeft = new Date(order.expires_at.replace(' ', 'T') + 'Z') - new Date();
            startCountdown('s4-' + order.id, s4TimeLeft);

            // Disable cancel button after 1 minute from purchase
            const s4Elapsed = (5 * 60 * 1000) - Math.max(0, s4TimeLeft);
            const cancelBtn = document.getElementById('s4-cancel-' + order.id);
            if (s4Elapsed >= 60000) {
                if (cancelBtn) { cancelBtn.disabled = true; cancelBtn.style.opacity = '0.4'; cancelBtn.style.cursor = 'not-allowed'; cancelBtn.title = 'Cancel window expired'; }
            } else {
                setTimeout(() => {
                    const btn = document.getElementById('s4-cancel-' + order.id);
                    if (btn) { btn.disabled = true; btn.style.opacity = '0.4'; btn.style.cursor = 'not-allowed'; btn.title = 'Cancel window expired'; }
                }, 60000 - s4Elapsed);
            }
        });

        // Update badge count
        const totalActive = document.querySelectorAll('[id^="order-card-s3-"], [id^="order-card-s4-"], [id^="order-card-"]').length;
        badge.innerText = totalActive || '';
        if (totalActive === 0) panel.classList.add('hidden');
    })
    .catch(() => {});
}

function buildS4OrderCard(order) {
    const div = document.createElement('div');
    div.id = 'order-card-s4-' + order.id;
    div.className = 'order-card';

    const hasSms = order.sms_code && order.sms_code !== '';
    const displayName = order.project_title || ('Project ' + order.project_id);
    const price = parseFloat(order.our_price).toLocaleString('en-NG', {minimumFractionDigits:2});

    div.innerHTML = `
        <div style="display:flex;align-items:flex-start;gap:10px;">
            <div style="width:38px;height:38px;border-radius:9px;background:rgba(217,119,6,.1);border:1px solid rgba(217,119,6,.2);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="fas fa-bus" style="color:#d97706;"></i>
            </div>
            <div style="flex:1;min-width:0;">
                <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:8px;">
                    <div>
                        <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);">
                            ${displayName}
                        </p>
                        <p style="font-size:.72rem;color:var(--text-muted);font-family:monospace;">${order.phone}</p>
                    </div>
                    <div style="text-align:right;">
                        <p style="font-size:.68rem;color:var(--text-muted);">Cost</p>
                        <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);font-family:monospace;">&#8358;${price}</p>
                    </div>
                </div>
                ${hasSms
                    ? `<div style="background:rgba(217,119,6,.07);border:1px solid rgba(217,119,6,.2);border-radius:10px;padding:10px;display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                        <i class="fas fa-envelope-open-text" style="color:#d97706;font-size:1rem;"></i>
                        <div>
                            <p style="font-size:.7rem;color:#d97706;font-weight:600;">OTP Received</p>
                            <p style="font-weight:800;font-size:1.2rem;color:#d97706;font-family:monospace;letter-spacing:.1em;" id="s4-sms-${order.id}">${order.sms_code}</p>
                        </div>
                      </div>`
                    : `<div style="background:var(--btn-bg);border:1px solid var(--card-border);border-radius:10px;padding:10px;display:flex;align-items:center;gap:8px;margin-bottom:8px;" id="s4-waiting-${order.id}">
                        <div style="width:16px;height:16px;border:2px solid #d97706;border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite;flex-shrink:0;"></div>
                        <div style="flex:1;"><p style="font-size:.72rem;color:var(--text-muted);">Waiting for SMS...</p></div>
                        <span id="timer-s4-${order.id}" style="font-family:monospace;font-size:.82rem;font-weight:700;color:#d97706;flex-shrink:0;">--:--</span>
                      </div>`}
                <div style="display:flex;gap:6px;flex-wrap:wrap;">
                    <button onclick="copyNumber('${order.phone}')" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:var(--btn-bg);border:1px solid var(--card-border);color:var(--text-primary);cursor:pointer;display:flex;align-items:center;gap:5px;">
                        <i class="fa-regular fa-copy text-xs"></i>Copy Number
                    </button>
                    ${hasSms
                        ? `<button onclick="copySms('${order.sms_code}')" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:rgba(217,119,6,.07);border:1px solid rgba(217,119,6,.2);color:#d97706;cursor:pointer;display:flex;align-items:center;gap:5px;"><i class="fa-regular fa-copy text-xs"></i>Copy OTP</button>`
                        : `<button onclick="cancelS4Number(${order.id})" id="s4-cancel-${order.id}" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:rgba(239,68,68,.07);border:1px solid rgba(239,68,68,.18);color:#dc2626;cursor:pointer;display:flex;align-items:center;gap:5px;"><i class="fas fa-xmark text-xs"></i>Cancel & Refund</button>`}
                </div>
            </div>
        </div>
    `;
    return div;
}

function pollS4SMS(localOrderId) {
    fetch('../ajax/smsbus_handler.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'action=check_sms&order_id=' + localOrderId
    })
    .then(r => r.json())
    .then(data => {
        if (data.status === '1') {
            clearInterval(s4ActiveOrders[localOrderId]);
            delete s4ActiveOrders[localOrderId];
            showSmsToast(data.sms_code || '');

            const waitDiv = document.getElementById('s4-waiting-' + localOrderId);
            if (waitDiv) {
                waitDiv.style.background = 'rgba(217,119,6,.07)';
                waitDiv.style.border = '1px solid rgba(217,119,6,.2)';
                waitDiv.innerHTML = `<i class="fas fa-envelope-open-text" style="color:#d97706;font-size:1rem;"></i>
                    <div>
                        <p style="font-size:.7rem;color:#d97706;font-weight:600;">OTP Received</p>
                        <p style="font-weight:800;font-size:1.2rem;color:#d97706;font-family:monospace;letter-spacing:.1em;">${data.sms_code}</p>
                    </div>`;
                const cancelBtn = document.getElementById('s4-cancel-' + localOrderId);
                if (cancelBtn) {
                    cancelBtn.outerHTML = `<button onclick="copySms('${data.sms_code}')" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:rgba(217,119,6,.07);border:1px solid rgba(217,119,6,.2);color:#d97706;cursor:pointer;display:flex;align-items:center;gap:5px;"><i class="fa-regular fa-copy text-xs"></i>Copy OTP</button>`;
                }
            }
            // Show OTP for 1 minute then redirect to My Numbers
            setTimeout(() => {
                window.location.href = 'my-number';
            }, 60000);
        } else if (data.status === '0') {
            clearInterval(s4ActiveOrders[localOrderId]);
            delete s4ActiveOrders[localOrderId];
            const card = document.getElementById('order-card-s4-' + localOrderId);
            if (card) card.remove();
        }
    })
    .catch(() => {});
}

function cancelS4Number(localOrderId) {
    const btn = document.getElementById('s4-cancel-' + localOrderId);
    if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin text-xs"></i>Cancelling...'; }

    fetch('../ajax/smsbus_handler.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'action=cancel_number&order_id=' + localOrderId
    })
    .then(r => r.json())
    .then(data => {
        if (data.status === '1') {
            showNotification(data.msg || 'Cancelled & refunded.', 'success');
            clearInterval(s4ActiveOrders[localOrderId]);
            delete s4ActiveOrders[localOrderId];
            const card = document.getElementById('order-card-s4-' + localOrderId);
            if (card) card.remove();
            if (data.new_balance) document.getElementById('heroBalance').innerText = '\u20A6' + data.new_balance;
        } else {
            showNotification(data.msg || 'Could not cancel.', 'error');
            if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-xmark text-xs"></i>Cancel & Refund'; }
        }
    })
    .catch(() => {
        showNotification('An error occurred.', 'error');
        if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-xmark text-xs"></i>Cancel & Refund'; }
    });
}

// -- S3 search -----------------------------------------------------------------
// (Hooked into the existing search_op input � see search handler below)

// -- S3 active orders & polling ------------------------------------------------
function loadS3ActiveOrders() {
    fetch('../ajax/fivesim_handler.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'action=get_active_orders'
    })
    .then(r => r.json())
    .then(data => {
        const panel = document.getElementById('activeOrdersPanel');
        const list  = document.getElementById('activeOrdersList');
        const badge = document.getElementById('activeCountBadge');

        // Remove S3 cards that are no longer active
        const activeS3Ids = (data.status === '1' && data.orders) ? data.orders.map(o => 'order-card-s3-' + o.id) : [];
        document.querySelectorAll('[id^="order-card-s3-"]').forEach(card => {
            if (!activeS3Ids.includes(card.id)) {
                clearInterval(s3ActiveOrders[card.id.replace('order-card-s3-', '')]);
                delete s3ActiveOrders[card.id.replace('order-card-s3-', '')];
                card.remove();
            }
        });

        if (data.status !== '1' || !data.orders || data.orders.length === 0) return;

        panel.classList.remove('hidden');

        data.orders.forEach(order => {
            // Don't duplicate cards already shown
            if (document.getElementById('order-card-s3-' + order.id)) return;

            const card = buildS3OrderCard(order);
            list.appendChild(card);

            if (!s3ActiveOrders[order.id]) {
                s3ActiveOrders[order.id] = setInterval(() => pollS3SMS(order.id), 5000);
            }
            const s3TimeLeft = new Date(order.expires_at.replace(' ', 'T') + 'Z') - new Date();
            startCountdown('s3-' + order.id, s3TimeLeft);

            // Disable cancel button after 1 minute from purchase
            const s3Elapsed = (5 * 60 * 1000) - Math.max(0, s3TimeLeft);
            const cancelBtn = document.getElementById('s3-cancel-' + order.id);
            if (s3Elapsed >= 60000) {
                if (cancelBtn) { cancelBtn.disabled = true; cancelBtn.style.opacity = '0.4'; cancelBtn.style.cursor = 'not-allowed'; cancelBtn.title = 'Cancel window expired'; }
            } else {
                setTimeout(() => {
                    const btn = document.getElementById('s3-cancel-' + order.id);
                    if (btn) { btn.disabled = true; btn.style.opacity = '0.4'; btn.style.cursor = 'not-allowed'; btn.title = 'Cancel window expired'; }
                }, 60000 - s3Elapsed);
            }
        });

        // Update badge count
        const totalActive = document.querySelectorAll('[id^="order-card-s3-"], [id^="order-card-s4-"], [id^="order-card-"]').length;
        badge.innerText = totalActive || '';
        if (totalActive === 0) panel.classList.add('hidden');
    })
    .catch(() => {});
}

function buildS3OrderCard(order) {
    const div = document.createElement('div');
    div.id = 'order-card-s3-' + order.id;
    div.className = 'order-card';

    const hasSms = order.sms_code && order.sms_code !== '';
    const displayName = order.product.charAt(0).toUpperCase() + order.product.slice(1);
    const price = parseFloat(order.our_price).toLocaleString('en-NG', {minimumFractionDigits:2});

    div.innerHTML = `
        <div style="display:flex;align-items:flex-start;gap:10px;">
            <div style="width:38px;height:38px;border-radius:9px;background:rgba(16,185,129,.1);border:1px solid rgba(16,185,129,.2);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="fas fa-mobile-alt" style="color:#059669;"></i>
            </div>
            <div style="flex:1;min-width:0;">
                <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:8px;">
                    <div>
                        <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);">
                            ${displayName}
                        </p>
                        <p style="font-size:.72rem;color:var(--text-muted);font-family:monospace;">${order.phone}</p>
                    </div>
                    <div style="text-align:right;">
                        <p style="font-size:.68rem;color:var(--text-muted);">Cost</p>
                        <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);font-family:monospace;">&#8358;${price}</p>
                    </div>
                </div>
                ${hasSms
                    ? `<div style="background:rgba(16,185,129,.07);border:1px solid rgba(16,185,129,.2);border-radius:10px;padding:10px;display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                        <i class="fas fa-envelope-open-text text-emerald-500 text-base"></i>
                        <div>
                            <p style="font-size:.7rem;color:#059669;font-weight:600;">OTP Received</p>
                            <p style="font-weight:800;font-size:1.2rem;color:#059669;font-family:monospace;letter-spacing:.1em;" id="s3-sms-${order.id}">${order.sms_code}</p>
                        </div>
                      </div>`
                    : `<div style="background:var(--btn-bg);border:1px solid var(--card-border);border-radius:10px;padding:10px;display:flex;align-items:center;gap:8px;margin-bottom:8px;" id="s3-waiting-${order.id}">
                        <div style="width:16px;height:16px;border:2px solid #059669;border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite;flex-shrink:0;"></div>
                        <div style="flex:1;"><p style="font-size:.72rem;color:var(--text-muted);">Waiting for SMS...</p></div>
                        <span id="timer-s3-${order.id}" style="font-family:monospace;font-size:.82rem;font-weight:700;color:#d97706;flex-shrink:0;">--:--</span>
                      </div>`}
                <div style="display:flex;gap:6px;flex-wrap:wrap;">
                    <button onclick="copyNumber('${order.phone}')" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:var(--btn-bg);border:1px solid var(--card-border);color:var(--text-primary);cursor:pointer;display:flex;align-items:center;gap:5px;">
                        <i class="fa-regular fa-copy text-xs"></i>Copy Number
                    </button>
                    ${hasSms
                        ? `<button onclick="copySms('${order.sms_code}')" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:rgba(16,185,129,.07);border:1px solid rgba(16,185,129,.2);color:#059669;cursor:pointer;display:flex;align-items:center;gap:5px;"><i class="fa-regular fa-copy text-xs"></i>Copy OTP</button>`
                        : `<button onclick="cancelS3Number(${order.id})" id="s3-cancel-${order.id}" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:rgba(239,68,68,.07);border:1px solid rgba(239,68,68,.18);color:#dc2626;cursor:pointer;display:flex;align-items:center;gap:5px;"><i class="fas fa-xmark text-xs"></i>Cancel & Refund</button>`}
                </div>
            </div>
        </div>
    `;
    return div;
}

function pollS3SMS(localOrderId) {
    fetch('../ajax/fivesim_handler.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'action=check_sms&order_id=' + localOrderId
    })
    .then(r => r.json())
    .then(data => {
        if (data.status === '1') {
            // SMS received
            clearInterval(s3ActiveOrders[localOrderId]);
            delete s3ActiveOrders[localOrderId];
            showSmsToast(data.sms_code || data.sms_text);

            // Update card in place without full reload
            const waitDiv = document.getElementById('s3-waiting-' + localOrderId);
            if (waitDiv) {
                waitDiv.style.background = 'rgba(16,185,129,.07)';
                waitDiv.style.border = '1px solid rgba(16,185,129,.2)';
                waitDiv.innerHTML = `<i class="fas fa-envelope-open-text text-emerald-500 text-base"></i>
                    <div>
                        <p style="font-size:.7rem;color:#059669;font-weight:600;">OTP Received</p>
                        <p style="font-weight:800;font-size:1.2rem;color:#059669;font-family:monospace;letter-spacing:.1em;">${data.sms_code}</p>
                    </div>`;
                // Replace cancel button with copy button
                const cancelBtn = document.getElementById('s3-cancel-' + localOrderId);
                if (cancelBtn) {
                    cancelBtn.outerHTML = `<button onclick="copySms('${data.sms_code}')" style="font-size:.72rem;font-weight:600;padding:6px 10px;border-radius:8px;background:rgba(16,185,129,.07);border:1px solid rgba(16,185,129,.2);color:#059669;cursor:pointer;display:flex;align-items:center;gap:5px;"><i class="fa-regular fa-copy text-xs"></i>Copy OTP</button>`;
                }
            }
            // Show OTP for 1 minute then redirect to My Numbers
            setTimeout(() => {
                window.location.href = 'my-number';
            }, 60000);
        } else if (data.status === '0') {
            // Expired/cancelled
            clearInterval(s3ActiveOrders[localOrderId]);
            delete s3ActiveOrders[localOrderId];
            const card = document.getElementById('order-card-s3-' + localOrderId);
            if (card) card.remove();
            // Show refund message if balance was returned
            var msg = data.msg || 'Order cancelled.';
            showNotification(msg, data.refunded ? 'success' : 'error');
            if (data.new_balance !== undefined) {
                document.getElementById('heroBalance').innerText = '\u20A6' + data.new_balance;
            }
        }
        // 'waiting' status � do nothing
    })
    .catch(() => {});
}

function cancelS3Number(localOrderId) {
    const btn = document.getElementById('s3-cancel-' + localOrderId);
    if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin text-xs"></i>Cancelling...'; }

    fetch('../ajax/fivesim_handler.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'action=cancel_number&order_id=' + localOrderId
    })
    .then(r => r.json())
    .then(data => {
        if (data.status === '1') {
            showNotification(data.msg || 'Cancelled & refunded.', 'success');
            clearInterval(s3ActiveOrders[localOrderId]);
            delete s3ActiveOrders[localOrderId];
            const card = document.getElementById('order-card-s3-' + localOrderId);
            if (card) card.remove();
            if (data.new_balance) document.getElementById('heroBalance').innerText = '\u20A6' + data.new_balance;
        } else {
            showNotification(data.msg || 'Could not cancel.', 'error');
            if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-xmark text-xs"></i>Cancel & Refund'; }
        }
    })
    .catch(() => {
        showNotification('An error occurred.', 'error');
        if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-xmark text-xs"></i>Cancel & Refund'; }
    });
}

// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
// -- Init ---------------------------------------------------------------------
document.addEventListener('DOMContentLoaded', () => {
    // PHP tells us the first active server directly ? no DOM inspection needed
    var defaultServer = '<?php
        if (!empty($servers_s2))      echo "s2";
        elseif (!empty($servers_s1))  echo "s1";
        elseif ($fivesim_enabled)     echo "s3";
        elseif ($smsbus_enabled)      echo "s4";
        else                          echo "s2"; // fallback
    ?>';

    switchServer(defaultServer);

    loadActiveOrders();
    loadS3ActiveOrders();
    loadS4ActiveOrders();
    setInterval(loadActiveOrders, 30000);
    setInterval(loadS3ActiveOrders, 30000);
    setInterval(loadS4ActiveOrders, 30000);
});
</script>

<?php include('footer.php'); ?>
