

<?php $__env->startSection('content'); ?>
    <?php echo $__env->make('frontend.components.accordion', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

    <div class="server-card card mp-20" id="radiumsahil">
        <h2 class="title">Buy Number</h2>
        <p class="desc">Select country and service below</p>

        <input type="hidden" id="server_no" value="">
        <input type="hidden" id="service_code" value="">

        <div class="form-grid">
            <div class="form-group">
                <label class="form-label">
                    Select Country <span class="required">*</span>
                    <div class="tooltip-wrapper">
                        <i class="ti ti-info-circle"></i>
                        <span class="tooltip">Choose the country (server) for the number.</span>
                    </div>
                </label>
                <div class="select" id="select-server">
                    <button type="button" class="select-preview">
                        <span>Choose Country</span>
                        <i class="ti ti-chevron-down select-icon"></i>
                    </button>
                    <div class="select-dropdown">
                        <div class="select-search">
                            <input type="search" placeholder="Search..." class="form-control">
                        </div>
                        <div class="select-list">
                            <?php $__currentLoopData = $servers ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div class="select-item" data-server-id="<?php echo e($s->id); ?>"><?php echo e($s->server_name); ?></div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            <?php if(empty($servers ?? [])): ?>
                            <div class="select-item">No servers</div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">
                    Select Service <span class="required">*</span>
                    <div class="tooltip-wrapper">
                        <i class="ti ti-info-circle"></i>
                        <span class="tooltip">Select a service after choosing country.</span>
                    </div>
                </label>
                <div class="select" id="select-service">
                    <button type="button" class="select-preview">
                        <span>Please select country first</span>
                        <i class="ti ti-chevron-down select-icon"></i>
                    </button>
                    <div class="select-dropdown">
                        <div class="select-list select-price" id="service-list">
                            <div class="select-item">Please select country first</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="form-footer mp-20">
            <div class="summary">
                <span id="show_name">??</span><br>
                <strong id="show_amount"><?php echo e($currency ?? 'NGN'); ?>??</strong>
            </div>
            <button type="button" class="btn btn-primary" id="buy-numbers"><i class="ti ti-shopping-cart"></i> Buy Number</button>
        </div>
    </div>

    <div id="card-container" class="activation-grid mp-20"></div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('script'); ?>
<script>
(function() {
    const baseUrl = '<?php echo e(url("/")); ?>';
    const currency = '<?php echo e($currency ?? "NGN"); ?>';
    const TIMER_SECONDS = 20 * 60;
    const defaultLogo = 'https://i.ibb.co/ySRhxqh/default.png';

    function fmtTime(sec) {
        if (sec <= 0) return '00:00';
        var m = Math.floor(sec / 60);
        var s = sec % 60;
        return (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
    }

    function remainingSeconds(buyTimeIso) {
        var buy = new Date(buyTimeIso).getTime();
        var now = Date.now();
        var elapsed = Math.floor((now - buy) / 1000);
        return Math.max(0, TIMER_SECONDS - elapsed);
    }

    function addCard(order) {
        var orderId = order.order_id;
        var fullNumber = '+' + (order.number || '');
        var serviceName = order.service_name || 'Service';
        var serviceAmount = order.service_price != null ? currency + order.service_price : currency + '0';
        var logoUrl = order.logo_url || defaultLogo;
        var statusText = order.sms_text ? ('Code: ' + order.sms_text) : 'Waiting for SMS.';
        var isCode = !!order.sms_text;
        var remaining = remainingSeconds(order.buy_time || new Date().toISOString());
        var safeId = orderId.replace(/[^a-zA-Z0-9-_]/g, '_');
        var statusId = 'act-sms-' + safeId;
        var timerId = 'act-timer-' + safeId;

        var container = document.getElementById('card-container');
        var cardHtml =
            '<div class="activation-card card" data-order-id="' + orderId.replace(/"/g, '&quot;') + '">' +
            '  <div class="activation-card__head">' +
            '    <div class="activation-card__icon"><img src="' + logoUrl.replace(/"/g, '&quot;') + '" alt=""></div>' +
            '    <div class="activation-card__info">' +
            '      <div class="activation-card__number">' +
            '        <span>' + fullNumber.replace(/</g, '&lt;') + '</span>' +
            '        <button type="button" class="copy-number" title="Copy number"><i class="ti ti-copy"></i></button>' +
            '      </div>' +
            '      <div class="activation-card__meta">' + serviceName.replace(/</g, '&lt;') + ' – ' + serviceAmount.replace(/</g, '&lt;') + '</div>' +
            '    </div>' +
            '  </div>' +
            '  <div class="activation-card__status">' +
            '    <p class="activation-card__status-text ' + (isCode ? 'code-received' : '') + '" id="' + statusId + '">' + statusText.replace(/</g, '&lt;') + '</p>' +
            '    <span class="activation-card__timer" id="' + timerId + '"><i class="ti ti-clock"></i> <span class="timer-value">' + fmtTime(remaining) + '</span></span>' +
            '  </div>' +
            '  <div class="activation-card__actions">' +
            '    <button type="button" class="btn btn--next next-btn"><i class="ti ti-arrow-right"></i> Next</button>' +
            '    <button type="button" class="btn btn--copy copy-btn"><i class="ti ti-copy"></i> Copy</button>' +
            '    <button type="button" class="btn btn--cancel cancel-btn"><i class="ti ti-trash"></i> Cancel</button>' +
            '  </div>' +
            '</div>';
        container.insertAdjacentHTML('beforeend', cardHtml);
        var card = container.lastElementChild;

        var statusEl = document.getElementById(statusId);
        var timerValEl = document.getElementById(timerId) && document.getElementById(timerId).querySelector('.timer-value');
        var pollInterval = null;
        var timerInterval = null;

        function stopCard() {
            if (pollInterval) clearInterval(pollInterval);
            if (timerInterval) clearInterval(timerInterval);
            pollInterval = null;
            timerInterval = null;
        }

        if (remaining <= 0 || isCode) {
            if (timerValEl) timerValEl.textContent = '00:00';
        } else {
            timerInterval = setInterval(function() {
                remaining--;
                if (timerValEl) timerValEl.textContent = fmtTime(remaining);
                if (remaining <= 0) stopCard();
            }, 1000);
            pollInterval = setInterval(function() {
                fetch(baseUrl + '/number/message?order_id=' + encodeURIComponent(orderId))
                    .then(r => r.json())
                    .then(function(msg) {
                        if (msg.status === '200' && msg.sms) {
                            if (statusEl) {
                                statusEl.textContent = 'Code: ' + msg.sms;
                                statusEl.classList.add('code-received');
                            }
                            stopCard();
                        } else if (msg.status === '500') stopCard();
                    });
            }, 3000);
        }
        card._pollInterval = pollInterval;
        card._timerInterval = timerInterval;

        function copyCard() {
            var text = (statusEl && statusEl.classList.contains('code-received')) ? statusEl.textContent.replace(/^Code:\s*/, '') : fullNumber;
            navigator.clipboard.writeText(text).then(function() { iziToast.success({ message: 'Copied', position: 'topRight' }); });
        }
        card.querySelector('.copy-number').addEventListener('click', copyCard);
        card.querySelector('.copy-btn').addEventListener('click', copyCard);
        card.querySelector('.next-btn').addEventListener('click', function() {
            stopCard();
            if (card._pollInterval) clearInterval(card._pollInterval);
            if (card._timerInterval) clearInterval(card._timerInterval);
            card.remove();
            iziToast.info({ message: 'You can buy another number', position: 'topRight' });
        });
        card.querySelector('.cancel-btn').addEventListener('click', function() {
            var cancelBtn = this;
            cancelBtn.disabled = true;
            fetch(baseUrl + '/number/cancel', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ order_id: orderId })
            })
            .then(r => r.json())
            .then(function(res) {
                stopCard();
                if (card._pollInterval) clearInterval(card._pollInterval);
                if (card._timerInterval) clearInterval(card._timerInterval);
                card.remove();
                if (res.status === '200') iziToast.success({ message: res.message, position: 'topRight' });
                else iziToast.error({ message: res.message || 'Cancel failed', position: 'topRight' });
            })
            .catch(function() {
                cancelBtn.disabled = false;
                iziToast.error({ message: 'Request failed', position: 'topRight' });
            });
        });
    }

    // Load active orders on page load (restore after refresh)
    fetch(baseUrl + '/number/active-orders')
        .then(r => r.json())
        .then(function(res) {
            if (res.status === '200' && res.data && res.data.length) {
                res.data.forEach(function(order) { addCard(order); });
            }
        })
        .catch(function() {});

    document.getElementById('select-server')?.querySelector('.select-list')?.addEventListener('click', function(e) {
        const item = e.target.closest('.select-item');
        if (!item || !item.dataset.serverId) return;
        document.getElementById('server_no').value = item.dataset.serverId;
        const servicePreview = document.querySelector('#select-service .select-preview span');
        const serviceList = document.getElementById('service-list');
        if (servicePreview) servicePreview.textContent = 'Choose Service';
        document.getElementById('service_code').value = '';
        document.getElementById('show_name').textContent = '??';
        document.getElementById('show_amount').textContent = currency + '??';
        serviceList.innerHTML = '<div class="select-item">Loading...</div>';
        var serviceSearchInput = document.querySelector('#select-service .select-search input');
        if (serviceSearchInput) serviceSearchInput.value = '';
        fetch(baseUrl + '/number/services?server=' + encodeURIComponent(item.dataset.serverId))
            .then(r => r.json())
            .then(data => {
                serviceList.innerHTML = '';
                (data.service || []).forEach(function(s) {
                    const div = document.createElement('div');
                    div.className = 'select-item';
                    div.dataset.serviceId = s.id;
                    div.dataset.name = s.service_name;
                    div.dataset.amount = currency + s.service_price;
                    div.dataset.logoUrl = s.logo_url || defaultLogo;
                    div.innerHTML = s.service_name + ' <span class="price">' + currency + s.service_price + '</span>';
                    serviceList.appendChild(div);
                });
                if (serviceList.children.length === 0) {
                    serviceList.innerHTML = '<div class="select-item">No services</div>';
                }
                filterServiceList();
            })
            .catch(function() {
                serviceList.innerHTML = '<div class="select-item">Error loading services</div>';
            });
    });

    function filterServiceList() {
        var input = document.getElementById('service-search-input');
        var list = document.getElementById('service-list');
        if (!input || !list) return;
        var q = (input.value || '').trim().toLowerCase();
        var items = list.querySelectorAll('.select-item');
        items.forEach(function(item) {
            var hasId = item.hasAttribute('data-service-id');
            var text = (item.getAttribute('data-name') || item.textContent || '').trim().toLowerCase();
            var show = q === '' ? true : (hasId && text.indexOf(q) !== -1);
            item.classList.toggle('hidden', !show);
        });
    }

    var serviceSearchEl = document.getElementById('service-search-input');
    if (serviceSearchEl) {
        serviceSearchEl.addEventListener('input', filterServiceList);
        serviceSearchEl.addEventListener('keyup', filterServiceList);
    }

    document.getElementById('select-service')?.querySelector('.select-list')?.addEventListener('click', function(e) {
        const item = e.target.closest('.select-item');
        if (!item || !item.dataset.serviceId) return;
        document.getElementById('service_code').value = item.dataset.serviceId;
        document.getElementById('show_name').textContent = item.dataset.name || '??';
        document.getElementById('show_amount').textContent = item.dataset.amount || (currency + '??');
    });

    document.getElementById('buy-numbers')?.addEventListener('click', function() {
        const server = document.getElementById('server_no').value;
        const service = document.getElementById('service_code').value;
        if (!server) {
            iziToast.error({ message: 'Please select country', position: 'topRight' });
            return;
        }
        if (!service) {
            iziToast.error({ message: 'Please select service', position: 'topRight' });
            return;
        }
        const btn = this;
        btn.disabled = true;
        fetch(baseUrl + '/number/buy', {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({ server: server, service: service })
        })
        .then(r => r.json())
        .then(function(data) {
            btn.disabled = false;
            if (data.status === '200') {
                const parts = (data.res || '').split(':');
                const orderId = parts[1];
                const number = parts[2] || '';
                const selectedItem = document.querySelector('.select-item[data-service-id="' + service + '"]');
                const serviceName = selectedItem ? (selectedItem.dataset.name || 'Service') : 'Service';
                const serviceAmount = selectedItem ? (selectedItem.dataset.amount || currency + '0') : currency + '0';
                const logoUrl = selectedItem ? (selectedItem.dataset.logoUrl || defaultLogo) : defaultLogo;
                addCard({
                    order_id: orderId,
                    number: number,
                    service_name: serviceName,
                    service_price: (selectedItem && selectedItem.dataset.amount ? selectedItem.dataset.amount.replace(currency, '').trim() : '0') || '0',
                    logo_url: logoUrl,
                    buy_time: new Date().toISOString(),
                    sms_text: ''
                });
                iziToast.success({ message: data.message, position: 'topRight' });
            } else {
                iziToast.error({ message: data.message || 'Error', position: 'topRight' });
            }
        })
        .catch(function() {
            btn.disabled = false;
            iziToast.error({ message: 'Request failed', position: 'topRight' });
        });
    });
})();
</script>
<?php $__env->stopPush(); ?>
<?php echo $__env->make('frontend.layout.dash', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\HP\Desktop\product\smsflow\core\resources\views/frontend/user/servers/index.blade.php ENDPATH**/ ?>