/**
 * Buy Numbers Page — Complete Functionality
 ** Developer: core tech web design
 * Whatsapp: +234 9162671360
 * Telegram: @jeditech
 ** Adapted for current project:
 *   AJAX → ajax/smsman_handler.php
 *   Tables → smsman_prices, smsman_orders, users, transactions
 *   Currency → NGN (₦)
 */

// ── Global State ────────────────────────────────────────────────
let activeOrders      = new Map();
let orderTimers       = new Map();
let smsCheckIntervals = new Map();
let allServices       = [];
let filteredServices  = [];
let currentFilter     = 'all';

// ── Utility: Copy to clipboard ──────────────────────────────────
function copyToClipboard(text) {
    if (!text) { showNotification('Nothing to copy', 'error'); return; }
    const ta = document.createElement('textarea');
    ta.value = text;
    ta.style.position = 'fixed';
    ta.style.left = '-9999px';
    document.body.appendChild(ta);
    ta.select();
    try {
        document.execCommand('copy');
        showNotification('Copied to clipboard!', 'success');
    } catch (e) {
        showNotification('Copy failed', 'error');
    }
    document.body.removeChild(ta);
}

// ── Utility: Notifications ──────────────────────────────────────
function showNotification(message, type) {
    type = type || 'info';
    if (typeof Notiflix !== 'undefined') {
        if (type === 'success') Notiflix.Notify.success(message);
        else if (type === 'error') Notiflix.Notify.failure(message);
        else Notiflix.Notify.info(message);
    } else {
        console.log(type.toUpperCase() + ': ' + message);
    }
}

// ── Utility: Notification sound ─────────────────────────────────
function playNotificationSound() {
    try {
        var a = new Audio('assets/sounds/bell.mp3');
        a.play().catch(function(){});
    } catch(e){}
}

// ── Utility: Format ms to MM:SS ─────────────────────────────────
function formatTime(ms) {
    var s = Math.max(0, Math.floor(ms / 1000));
    var m = Math.floor(s / 60);
    var sec = s % 60;
    return String(m).padStart(2,'0') + ':' + String(sec).padStart(2,'0');
}

// ── Cookie helpers ───────────────────────────────────────────────
function getCookie(name) {
    var v = '; ' + document.cookie;
    var parts = v.split('; ' + name + '=');
    if (parts.length === 2) return parts.pop().split(';').shift();
    return null;
}
function setCookie(name, value, minutes) {
    minutes = minutes || 20;
    var d = new Date();
    d.setTime(d.getTime() + minutes * 60000);
    document.cookie = name + '=' + value + '; expires=' + d.toUTCString() + '; path=/';
}
function deleteCookie(name) {
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/';
}

// ── Format NGN ──────────────────────────────────────────────────
function formatNGN(amount) {
    return '₦' + parseFloat(amount).toLocaleString('en-NG', {minimumFractionDigits:2, maximumFractionDigits:2});
}

// ── Update wallet balance display ────────────────────────────────
function updateUserBalance() {
    $.ajax({
        type: 'POST',
        url: 'ajax/smsman_handler.php',
        data: { action: 'get_balance' },
        dataType: 'json',
        success: function(res) {
            if (res.status === '1') {
                $('#walletBalanceDisplay').text(formatNGN(res.balance));
                $('#headerBalance').text('₦ ' + parseFloat(res.balance).toLocaleString('en-NG',{minimumFractionDigits:2}));
            }
        }
    });
}

// ════════════════════════════════════════════════════════════════
// DOCUMENT READY — Country + Service selection
// ════════════════════════════════════════════════════════════════
$(document).ready(function() {

    // ── View All Countries toggle ────────────────────────────────
    $('#view-all-btn').on('click', function() {
        var container = $('#all-countries-container');
        if (container.is(':visible')) {
            container.slideUp(250);
            $('#view-all-label').text('View All Countries');
        } else {
            container.slideDown(250);
            $('#view-all-label').text('Hide All Countries');
        }
    });

    // ── Country card click ───────────────────────────────────────
    $(document).on('click', '.country-card', function() {
        $('.country-card').removeClass('selected');
        $(this).addClass('selected');

        var serverId    = $(this).data('country-id');
        var countryName = $(this).data('country-name');

        $('#selected-country-name').text(countryName);
        $('#selected-country-display').slideDown(250);
        $('#server_no').val(serverId);

        loadServices(serverId);

        $('html,body').animate({ scrollTop: $('#list').offset().top - 80 }, 400);
    });

    // ── Country search ───────────────────────────────────────────
    $('#country-search').on('input', function() {
        var term = $(this).val().toLowerCase();
        $('.country-card').each(function() {
            $(this).toggle($(this).data('country-name').toLowerCase().indexOf(term) !== -1);
        });
        if (term.length > 0 && !$('#all-countries-container').is(':visible')) {
            $('#view-all-btn').trigger('click');
        }
    });

    // ── Reset country selection ──────────────────────────────────
    window.resetCountrySelection = function() {
        $('.country-card').removeClass('selected');
        $('#selected-country-display').slideUp(250);
        $('#server_no').val('');
        $('#list').html(
            '<div style="text-align:center;padding:2.5rem 1rem;color:#94a3b8;">' +
            '<i class="fas fa-mobile-alt" style="font-size:2rem;opacity:.3;display:block;margin-bottom:.6rem;"></i>' +
            '<h6 style="font-weight:600;margin:0 0 .25rem;color:#475569;">Select a Country First</h6>' +
            '<p style="font-size:.8rem;margin:0;">Choose a country above to see available services</p>' +
            '</div>'
        );
        $('#search_op').val('').prop('disabled', true);
        $('#show_amount').html('₦??');
        $('#show_name').html('Not Selected');
        $('#service_code').val('');
        $('#filter-options').hide();
        $('#services-count-badge').text('0 Services');
        allServices = [];
        filteredServices = [];
    };

    // ════════════════════════════════════════════════════════════
    // LOAD SERVICES FROM smsman_prices VIA AJAX
    // ════════════════════════════════════════════════════════════
    function loadServices(serverId) {
        $('#services-loading').show();
        $('#list').hide();
        $('#no-results-state').hide();
        $('#filter-options').hide();

        if (typeof Notiflix !== 'undefined') {
            Notiflix.Block.standard('#radiumsahil', 'Loading services...');
        }

        $.ajax({
            type: 'POST',
            url: 'ajax/smsman_handler.php',
            data: { action: 'get_country_services', country_id: serverId },
            dataType: 'json',
            error: function() {
                if (typeof Notiflix !== 'undefined') Notiflix.Block.remove('#radiumsahil');
                $('#services-loading').hide();
                $('#list').show();
                showNotification('Failed to load services. Please try again.', 'error');
            },
            success: function(res) {
                if (typeof Notiflix !== 'undefined') Notiflix.Block.remove('#radiumsahil');
                $('#services-loading').hide();
                $('#list').show();

                if (res.status !== '1') {
                    showNotification(res.msg || 'Failed to load services', 'error');
                    return;
                }

                // Convert keyed object to array
                allServices = [];
                $.each(res.services, function(id, s) {
                    allServices.push({
                        id:            id,
                        service_name:  s.name,
                        service_price: s.our_price,
                        stock:         s.available,
                        logo_url:      s.logo_url || 'https://i.ibb.co/ySRhxqh/default.png'
                    });
                });

                filteredServices = allServices.slice();
                renderServices(filteredServices);
                updateServicesCount(filteredServices.length);

                $('#search_op').prop('disabled', false);
                $('#filter-options').css('display','flex');

                showNotification(allServices.length + ' services loaded!', 'success');
            }
        });
    }

    // ─── Render services list ────────────────────────────────────
    function renderServices(services) {
        var list = $('#list');
        list.empty();

        if (services.length === 0) {
            $('#no-results-state').show();
            list.hide();
            return;
        }

        $('#no-results-state').hide();
        list.show();

        $.each(services, function(i, service) {
            var stockColor = service.stock ? (service.stock < 10 ? 'red' : 'green') : '#94a3b8';
            var stockText  = service.stock ? service.stock.toLocaleString() + ' in stock' : 'Out of stock';
            var priceNGN   = formatNGN(service.service_price);

            var item = $(
                '<li class="service-item"' +
                ' data-service-id="' + service.id + '"' +
                ' data-service-name="' + service.service_name.toLowerCase() + '"' +
                ' data-price="' + service.service_price + '"' +
                ' data-stock="' + (service.stock || 0) + '">' +

                '<div style="display:flex;align-items:center;gap:.75rem;flex:1;">' +
                '<img class="user-image" src="' + service.logo_url + '"' +
                ' alt="' + service.service_name + '"' +
                ' onerror="this.src=\'https://i.ibb.co/ySRhxqh/default.png\'">' +
                '<div class="about">' +
                '<div class="name">' + service.service_name + '</div>' +
                '<div class="status" style="color:' + stockColor + '">' + stockText + '</div>' +
                '</div></div>' +

                '<input type="hidden" class="service_id" value="' + service.id + '">' +
                '<div class="amount">' + priceNGN + '</div>' +
                '</li>'
            );

            list.append(item);
        });

        setupServiceSelection();
    }

    // ─── Service click handler ───────────────────────────────────
    function setupServiceSelection() {
        $('.service-item').off('click').on('click', function() {
            $('.service-item').removeClass('selected');
            $(this).addClass('selected');

            var name      = $(this).find('.name').text();
            var amount    = $(this).find('.amount').text();
            var serviceId = $(this).find('.service_id').val();

            $('#show_amount').html(amount);
            $('#show_name').html(name);
            $('#service_code').val(serviceId);

            showNotification(name + ' selected!', 'success');
        });
    }

    // ─── Service search ──────────────────────────────────────────
    $('#search_op').on('input', function() {
        var term = $(this).val().toLowerCase().trim();
        $('#clear-search-btn').toggle(term.length > 0);

        if (term === '') {
            filteredServices = applyCurrentFilter(allServices);
        } else {
            filteredServices = $.grep(allServices, function(s) {
                return s.service_name.toLowerCase().indexOf(term) !== -1;
            });
            filteredServices = applyCurrentFilter(filteredServices);
        }

        renderServices(filteredServices);
        highlightSearchTerm(term);
        updateServicesCount(filteredServices.length);

        if (filteredServices.length === 0) {
            $('#no-results-message').text(term ? 'No services found for "' + term + '"' : 'No services available');
        }
    });

    $('#clear-search-btn').on('click', function() {
        $('#search_op').val('').trigger('input').focus();
    });

    function highlightSearchTerm(term) {
        if (!term) return;
        $('.service-item .name').each(function() {
            var text = $(this).text();
            var re = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + ')', 'gi');
            $(this).html(text.replace(re, '<span class="highlight-match">$1</span>'));
        });
    }

    // ─── Filter chips ────────────────────────────────────────────
    $(document).on('click', '.filter-chip', function() {
        $('.filter-chip').removeClass('active');
        $(this).addClass('active');
        currentFilter = $(this).data('filter');

        var term = $('#search_op').val().toLowerCase().trim();
        filteredServices = term
            ? $.grep(allServices, function(s){ return s.service_name.toLowerCase().indexOf(term) !== -1; })
            : allServices.slice();

        filteredServices = applyCurrentFilter(filteredServices);
        renderServices(filteredServices);
        updateServicesCount(filteredServices.length);
    });

    function applyCurrentFilter(services) {
        var r = services.slice();
        if (currentFilter === 'in-stock') {
            r = $.grep(r, function(s){ return s.stock && s.stock >= 10; });
        } else if (currentFilter === 'price-low') {
            r.sort(function(a,b){ return parseFloat(a.service_price) - parseFloat(b.service_price); });
        } else if (currentFilter === 'price-high') {
            r.sort(function(a,b){ return parseFloat(b.service_price) - parseFloat(a.service_price); });
        }
        return r;
    }

    function updateServicesCount(count) {
        $('#services-count-badge').text(count + ' Service' + (count !== 1 ? 's' : ''));
    }

    window.resetSearch = function() {
        $('#search_op').val('');
        $('.filter-chip[data-filter="all"]').trigger('click');
        $('#clear-search-btn').hide();
    };

    // ════════════════════════════════════════════════════════════
    // BUY NUMBER
    // ════════════════════════════════════════════════════════════
    $('#buy-numbers').off('click').on('click', function() {
        var server  = $('#server_no').val();
        var service = $('#service_code').val();

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

        var btn = $(this);
        btn.prop('disabled', true)
           .html('<span class="spinner-border spinner-border-sm me-2" role="status"></span>Finding Number...');

        $.ajax({
            type: 'POST',
            url: 'ajax/smsman_handler.php',
            data: { action: 'buy_number', country_id: server, application_id: service },
            dataType: 'json',
            error: function() {
                btn.prop('disabled', false)
                   .html('<i class="fas fa-shopping-cart me-1"></i> Buy Number Now');
                showNotification('An error occurred. Please try again.', 'error');
            },
            success: function(res) {
                btn.prop('disabled', false)
                   .html('<i class="fas fa-shopping-cart me-1"></i> Buy Number Now');

                if (res.status === '1') {
                    showNotification(res.msg || 'Number purchased successfully!', 'success');
                    if (res.new_balance) {
                        $('#walletBalanceDisplay').text(formatNGN(res.new_balance));
                        $('#headerBalance').text('₦ ' + parseFloat(res.new_balance).toLocaleString('en-NG',{minimumFractionDigits:2}));
                    }
                    loadActiveNumbers();
                } else {
                    showNotification(res.msg || 'Purchase failed. Please try again.', 'error');
                }
            }
        });
    });

    // Load active numbers on page load
    loadActiveNumbers();

    // Refresh balance every 30s
    setInterval(updateUserBalance, 30000);

    $(window).on('beforeunload', clearAllIntervals);
});

// ════════════════════════════════════════════════════════════════
// LOAD ACTIVE NUMBERS (called on page load + after buy)
// ════════════════════════════════════════════════════════════════
function loadActiveNumbers() {
    var container = $('#card-container');
    clearAllIntervals();

    container.html(
        '<div class="text-center py-4">' +
        '<div class="loading-wave">' +
        '<div class="loading-bar"></div><div class="loading-bar"></div>' +
        '<div class="loading-bar"></div><div class="loading-bar"></div>' +
        '</div>' +
        '<p style="color:#94a3b8;font-size:.875rem;margin:.75rem 0 0;">Loading active numbers...</p>' +
        '</div>'
    );

    $.ajax({
        type: 'POST',
        url: 'ajax/smsman_handler.php',
        data: { action: 'get_active_orders' },
        dataType: 'json',
        success: function(res) {
            if (res.status === '1' && res.orders && res.orders.length > 0) {
                renderActiveNumbers(res.orders);
            } else {
                container.html('');
            }
        },
        error: function() {
            container.html(
                '<div style="background:#fee2e2;border:1px solid #fca5a5;border-radius:10px;padding:1rem;color:#991b1b;">' +
                '<i class="fas fa-exclamation-triangle me-2"></i>' +
                'Failed to load active numbers. Please refresh the page.' +
                '</div>'
            );
        }
    });
}

// ════════════════════════════════════════════════════════════════
// RENDER ACTIVE NUMBERS
// ════════════════════════════════════════════════════════════════
function renderActiveNumbers(numbers) {
    var container = $('#card-container');
    container.empty();

    if (!numbers || numbers.length === 0) { container.html(''); return; }

    $.each(numbers, function(i, number) {
        var orderId     = number.id;
        var phoneNumber = number.number;
        var serviceName = number.app_name;
        var servicePrice= number.our_price;
        var smsText     = number.sms_full_msg || number.sms_code || '';
        var expiresAt   = number.expires_at;

        // Calculate ms left from expires_at (stored as UTC datetime)
        var expiry = new Date(expiresAt.replace(' ', 'T') + '+00:00');
        var msLeft = Math.max(0, expiry.getTime() - Date.now());

        var card = createNumberCard(orderId, phoneNumber, serviceName, servicePrice, smsText, msLeft);
        container.append(card);

        startCountdownTimer(orderId, msLeft);

        if (number.status === 'waiting') {
            startSMSChecking(orderId, phoneNumber);
        } else if (number.status === 'received') {
            $('#sms_' + orderId).val(smsText).addClass('received');
            $('#card_' + orderId + ' .sms-status-badge').html('<i class="fas fa-check-circle" style="color:#10b981;"></i> Received');
            $('#card_' + orderId).addClass('completed');
        }
    });
}

// ════════════════════════════════════════════════════════════════
// CREATE NUMBER CARD HTML
// ════════════════════════════════════════════════════════════════
function createNumberCard(orderId, phoneNumber, serviceName, servicePrice, smsText, msLeft) {
    var timeStr      = formatTime(msLeft);
    var smsFill      = smsText || '';
    var priceFormatted = formatNGN(servicePrice);

    return '' +
        '<div class="bn-card number-order-card" id="card_' + orderId + '" data-order-id="' + orderId + '">' +
        '<div style="padding:1.1rem 1.25rem;">' +

        // Header row
        '<div style="display:flex;align-items:center;margin-bottom:.9rem;">' +
        '<div style="width:42px;height:42px;border-radius:10px;background:rgba(64,224,208,.12);display:flex;align-items:center;justify-content:center;margin-right:.75rem;flex-shrink:0;">' +
        '<i class="fas fa-comment-sms" style="color:#056e66;font-size:1.05rem;"></i>' +
        '</div>' +
        '<div style="flex:1;">' +
        '<h6 style="margin:0 0 .1rem;font-weight:700;font-size:.9rem;">' + serviceName + '</h6>' +
        '<p style="margin:0;font-size:.75rem;color:#64748b;">Amount: ' + priceFormatted + '</p>' +
        '</div>' +
        '<span class="timer-badge" id="timer_' + orderId + '">' +
        '<i class="fas fa-clock me-1"></i>' + timeStr +
        '</span>' +
        '</div>' +

        // Phone number
        '<div style="margin-bottom:.85rem;">' +
        '<label style="font-size:.73rem;color:#94a3b8;font-weight:600;display:block;margin-bottom:.3rem;">Phone Number</label>' +
        '<div style="display:flex;gap:.5rem;">' +
        '<input type="text" style="flex:1;padding:.55rem .75rem;border-radius:8px;border:1.5px solid #e2e8f0;font-family:\'Courier New\',monospace;font-weight:700;font-size:1rem;color:#056e66;background:#f8fafc;" value="+' + phoneNumber + '" readonly>' +
        '<button onclick="copyToClipboard(\'+' + phoneNumber + '\')" ' +
        'style="padding:.55rem .9rem;border:1.5px solid #e2e8f0;border-radius:8px;background:#f8fafc;cursor:pointer;color:#475569;">' +
        '<i class="far fa-copy"></i>' +
        '</button>' +
        '</div>' +
        '</div>' +

        // SMS textarea
        '<div style="margin-bottom:.85rem;">' +
        '<label style="font-size:.73rem;color:#94a3b8;font-weight:600;display:block;margin-bottom:.3rem;">Message</label>' +
        '<div style="position:relative;">' +
        '<textarea id="sms_' + orderId + '" class="sms-textarea" rows="3" readonly placeholder="Waiting for message...">' + smsFill + '</textarea>' +
        '<span class="sms-status-badge" id="smsbadge_' + orderId + '">' +
        '<i class="fas fa-clock" style="color:#f59e0b;"></i>' +
        '</span>' +
        '</div>' +
        '</div>' +

        // Buttons
        '<div style="display:flex;gap:.5rem;flex-wrap:wrap;">' +
        '<button id="next_' + orderId + '" class="btn-action btn-primary-action" onclick="buyNumber()" ' +
        'style="flex:1;padding:.6rem;border:none;border-radius:8px;background:linear-gradient(135deg,#40e0d0,#056e66);color:#fff;font-weight:600;cursor:pointer;font-size:.83rem;">' +
        '<i class="fas fa-redo me-1"></i>Next' +
        '</button>' +
        '<button id="copy_' + orderId + '" onclick="copySMS(\'' + orderId + '\')" ' +
        'style="flex:1;padding:.6rem;border:1.5px solid #0ea5e9;border-radius:8px;background:transparent;color:#0ea5e9;font-weight:600;cursor:pointer;font-size:.83rem;">' +
        '<i class="far fa-copy me-1"></i>Copy' +
        '</button>' +
        '<button id="cancel_' + orderId + '" onclick="cancelNumber(\'' + orderId + '\', \'+' + phoneNumber + '\')" ' +
        'style="flex:1;padding:.6rem;border:1.5px solid #ef4444;border-radius:8px;background:transparent;color:#ef4444;font-weight:600;cursor:pointer;font-size:.83rem;">' +
        '<i class="fas fa-times me-1"></i>Cancel' +
        '</button>' +
        '</div>' +

        '</div>' +
        '</div>';
}

// ════════════════════════════════════════════════════════════════
// COUNTDOWN TIMER
// ════════════════════════════════════════════════════════════════
function startCountdownTimer(orderId, initialMs) {
    var timeLeft = initialMs;

    var interval = setInterval(function() {
        timeLeft -= 1000;
        var badge = $('#timer_' + orderId);

        if (timeLeft <= 0) {
            clearInterval(interval);
            orderTimers.delete(orderId);
            badge.html('<i class="fas fa-clock me-1"></i>00:00').addClass('urgent');
            autoExpireOrder(orderId);
        } else {
            badge.html('<i class="fas fa-clock me-1"></i>' + formatTime(timeLeft));
            if (timeLeft < 120000) badge.addClass('urgent');
        }
    }, 1000);

    orderTimers.set(orderId, interval);
}

// ════════════════════════════════════════════════════════════════
// SMS CHECKING (polls every 2s like original)
// ════════════════════════════════════════════════════════════════
function startSMSChecking(orderId, phoneNumber) {
    var lastSMS = getCookie('sms_' + orderId) || '';

    var interval = setInterval(function() {
        $.ajax({
            type: 'POST',
            url: 'ajax/smsman_handler.php',
            data: { action: 'check_sms', order_id: orderId },
            dataType: 'json',
            success: function(res) {
                var ta = $('#sms_' + orderId);

                if (res.status === '1') {
                    // SMS received
                    var newSMS = res.sms_full_msg || res.sms_code || '';
                    ta.val(newSMS).removeClass('waiting').addClass('received');

                    if (newSMS !== lastSMS) {
                        lastSMS = newSMS;
                        setCookie('sms_' + orderId, newSMS, 20);
                        playNotificationSound();
                        showNotification('SMS received for +' + phoneNumber + '!', 'success');
                        $('#smsbadge_' + orderId).html('<i class="fas fa-check-circle" style="color:#10b981;"></i> Received');
                        $('#card_' + orderId).addClass('completed');
                    }

                    clearInterval(interval);
                    smsCheckIntervals.delete(orderId);

                } else if (res.status === 'waiting') {
                    ta.val('Waiting for SMS...');

                } else if (res.status === '0') {
                    ta.val(res.msg || 'Expired');
                    if (res.msg && (res.msg.toLowerCase().indexOf('cancel') !== -1 ||
                                   res.msg.toLowerCase().indexOf('expir') !== -1)) {
                        clearInterval(interval);
                        smsCheckIntervals.delete(orderId);
                        setTimeout(function() {
                            $('#card_' + orderId).fadeOut(300, function(){ $(this).remove(); updateUserBalance(); });
                        }, 2000);
                    }
                }
            },
            error: function() {
                $('#sms_' + orderId).val('Error checking message');
            }
        });
    }, 2000); // every 2 seconds, matching original buy-number.js

    smsCheckIntervals.set(orderId, interval);
}

// ════════════════════════════════════════════════════════════════
// COPY SMS
// ════════════════════════════════════════════════════════════════
window.copySMS = function(orderId) {
    var text = $('#sms_' + orderId).val();
    if (!text || text.indexOf('Waiting') !== -1 || text.indexOf('Error') !== -1) {
        showNotification('No message to copy yet', 'error');
        return;
    }
    copyToClipboard(text);
};

// ════════════════════════════════════════════════════════════════
// CANCEL NUMBER
// ════════════════════════════════════════════════════════════════
window.cancelNumber = function(orderId, phoneNumber) {
    Notiflix.Confirm.show(
        'Cancel Number',
        'Cancel ' + phoneNumber + '? You will get a full refund.',
        'Yes, Cancel',
        'No',
        function() { doCancelNumber(orderId); },
        function() {}
    );
};

function doCancelNumber(orderId) {
    var btn = $('#cancel_' + orderId);
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>Cancelling...');

    $.ajax({
        type: 'POST',
        url: 'ajax/smsman_handler.php',
        data: { action: 'cancel_number', order_id: orderId },
        dataType: 'json',
        success: function(res) {
            if (res.status === '1') {
                showNotification(res.msg || 'Number cancelled and refunded.', 'success');
                clearOrderIntervals(orderId);
                deleteCookie('sms_' + orderId);
                $('#card_' + orderId).fadeOut(300, function(){ $(this).remove(); });
                if (res.new_balance) {
                    $('#walletBalanceDisplay').text(formatNGN(res.new_balance));
                    $('#headerBalance').text('₦ ' + parseFloat(res.new_balance).toLocaleString('en-NG',{minimumFractionDigits:2}));
                }
                updateUserBalance();
            } else {
                showNotification(res.msg || 'Cancellation failed.', 'error');
                btn.prop('disabled', false).html('<i class="fas fa-times me-1"></i>Cancel');
            }
        },
        error: function() {
            showNotification('Cancellation failed. Please try again.', 'error');
            btn.prop('disabled', false).html('<i class="fas fa-times me-1"></i>Cancel');
        }
    });
}

// ════════════════════════════════════════════════════════════════
// AUTO EXPIRE (timer hits 00:00 and no SMS)
// ════════════════════════════════════════════════════════════════
function autoExpireOrder(orderId) {
    var smsVal = $('#sms_' + orderId).val();
    if (smsVal && smsVal.indexOf('Waiting') === -1 && smsVal !== '') {
        // SMS already received — just mark done
        $('#card_' + orderId).addClass('completed');
        clearOrderIntervals(orderId);
        return;
    }

    $.ajax({
        type: 'POST',
        url: 'ajax/smsman_handler.php',
        data: { action: 'cancel_number', order_id: orderId },
        dataType: 'json',
        success: function(res) {
            showNotification('Number expired and refunded.', 'info');
            clearOrderIntervals(orderId);
            deleteCookie('sms_' + orderId);
            $('#card_' + orderId).fadeOut(300, function(){ $(this).remove(); });
            if (res.new_balance) {
                $('#walletBalanceDisplay').text(formatNGN(res.new_balance));
                $('#headerBalance').text('₦ ' + parseFloat(res.new_balance).toLocaleString('en-NG',{minimumFractionDigits:2}));
            }
            updateUserBalance();
        }
    });
}

// Allow buy again from active card
window.buyNumber = function() {
    $('html,body').animate({ scrollTop: 0 }, 400);
    showNotification('Select a country and service to buy another number', 'info');
};

// ── Interval cleanup ─────────────────────────────────────────────
function clearOrderIntervals(orderId) {
    if (orderTimers.has(orderId))       { clearInterval(orderTimers.get(orderId));       orderTimers.delete(orderId); }
    if (smsCheckIntervals.has(orderId)) { clearInterval(smsCheckIntervals.get(orderId)); smsCheckIntervals.delete(orderId); }
}
function clearAllIntervals() {
    orderTimers.forEach(function(i){ clearInterval(i); });       orderTimers.clear();
    smsCheckIntervals.forEach(function(i){ clearInterval(i); }); smsCheckIntervals.clear();
}

// Expose globally
window.loadActiveNumbers  = loadActiveNumbers;
window.updateUserBalance  = updateUserBalance;
window.copyToClipboard    = copyToClipboard;