// Global variables
// Main function to load and display all devices
function allcommandsSet(onlineFilter = 'all') {
    $(".crud_section").html("");

    // Modern loading skeleton
    var loadingHTML = `
        <div class="devices-container" style="padding: 24px; background: #ffffff; min-height: 100vh;">
            <div class="loading-skeleton">
                <div style="height: 60px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 12px; margin-bottom: 20px;"></div>
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px;">
                    ${Array(4).fill().map(() => '<div style="height: 100px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>').join('')}
                </div>
                <div style="height: 400px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>
            </div>
        </div>
        <style>
            @keyframes loading {
                0% { background-position: 200% 0; }
                100% { background-position: -200% 0; }
            }
        </style>
    `;

    $(".tab_devices").html(loadingHTML);

    // Determine which API endpoint to use based on filter
    let url;
    if (onlineFilter === 'online') {
        url = serverURL + "devices/online?status=true&size=1000";
    } else if (onlineFilter === 'offline') {
        url = serverURL + "devices/online?status=false&size=1000";
    } else {
        url = serverURL + "devices/all";
    }

    $.ajax({
        url: url,
        type: 'GET',
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json",
        },
        async: true,
        success: function(res) {
            var data = res.content || res || [];
            
            // Calculate statistics
            const totalDevices = data.length;
            const onlineDevices = data.filter(d => d.isOnline === true).length;
            const offlineDevices = totalDevices - onlineDevices;
            const activeDevices = data.filter(d => d.active === true).length;
            const inactiveDevices = totalDevices - activeDevices;
            const assignedDevices = data.filter(d => d.vehicle !== null).length;
            const unassignedDevices = totalDevices - assignedDevices;

            var html = `
            <div class="devices-container" style="padding: 24px; background: #ffffff; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
                
                <!-- Header Section -->
                <div style="background: #ffffff; border-radius: 16px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2;">
                    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                        <div style="display: flex; align-items: center; gap: 16px;">
                            <h1 style="margin: 0; font-size: 28px; font-weight: 600; color: #1a1f36; display: flex; align-items: center; gap: 12px;">
                                <i class="fas fa-microchip" style="color: #000;"></i>
                                Commands Management
                            </h1>
                            <span style="background: #f0f2f5; color: #1a1f36; padding: 6px 14px; border-radius: 40px; font-size: 14px; font-weight: 500;">
                                ${totalDevices} Total
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Search and Controls -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-bottom: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                    <div style="position: relative; flex: 1; max-width: 400px;">
                        <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8;"></i>
                        <input type="text" id="deviceSearch" placeholder="Search by name, serial, IMEI..." style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid #eaeef2; border-radius: 40px; font-size: 14px; outline: none; transition: all 0.2s;">
                    </div>
                    <div style="display: flex; gap: 12px;">
                        <select id="pageSize" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; font-size: 14px; outline: none;">
                            <option value="10">10 per page</option>
                            <option value="25">25 per page</option>
                            <option value="50">50 per page</option>
                            <option value="100">100 per page</option>
                        </select>
                        <button onclick="allDevices('${onlineFilter}')" style="width: 40px; height: 40px; border: 1px solid #eaeef2; border-radius: 50%; background: white; cursor: pointer; transition: all 0.2s;">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                    </div>
                </div>

                <!-- Devices Table -->
                <div style="background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: inherit; box-shadow: 0 2px 8px rgba(0,0,0,0.04);">
                    <table class="devices-table" id="devicetableview" style="width: 100%; border-collapse: collapse; min-width: 1400px;">
                        <thead>
                            <tr style="background: #f8fafc; border-bottom: 2px solid #eaeef2;">
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36; width: 40px;">
                                    <input type="checkbox" id="selectAll" style="width: 18px; height: 18px; cursor: pointer;">
                                </th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">#</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Device Info</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Serial & IMEI</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">SIM Cards</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Status</th>
                                <th style="padding: 16px; text-align: center; font-weight: 600; color: #1a1f36;">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="deviceTableBody">
            `;

            data.forEach((item, i) => {
                const deviceId = item.deviceId || i + 1;
                const serialNo = item.serialNo || item.serialNumber || 'N/A';
                
                html += `
                <tr data-device-id="${serialNo}" 
                    data-online="${item.isOnline}" 
                    data-active="${item.active}"
                    style="border-bottom: 1px solid #eaeef2; transition: background 0.2s;">
                    
                    <td style="padding: 16px;">
                        <input type="checkbox" class="row-checkbox" data-id="${serialNo}" style="width: 18px; height: 18px; cursor: pointer;">
                    </td>

                    <td style="padding: 16px; color: #5b677c;">${i + 1}</td>

                    <td style="padding: 16px;">
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 40px; height: 40px; background: #f0f2f5; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                                <i class="fas fa-microchip" style="color: #000;"></i>
                            </div>
                            <div>
                                <div style="font-weight: 600; color: #1a1f36;">${item.deviceSn || 'Unnamed'}</div>
                                <div style="font-size: 12px; color: #5b677c;">${item.make || ''} ${item.model || ''} (${item.yearOfManufacture || 'N/A'})</div>
                            </div>
                        </div>
                    </td>

                    <td style="padding: 16px;">
                        <div>
                            <div style="font-weight: 500; color: #1a1f36;">${serialNo}</div>
                            <div style="font-size: 12px; color: #5b677c;">IMEI: ${item.imei || 'N/A'}</div>
                            <div style="font-size: 11px; color: #94a3b8;">FW: ${item.firmwareVersion || 'N/A'}</div>
                        </div>
                    </td>

                    <td style="padding: 16px;">
                        <div style="font-size: 13px; color: #1a1f36;">
                            <div><i class="fas fa-sim-card" style="width: 16px; color: #5b677c;"></i> SIM1: ${item.sim1Number || 'N/A'}</div>
                            <div style="margin-top: 4px;"><i class="fas fa-sim-card" style="width: 16px; color: #5b677c;"></i> SIM2: ${item.sim2Number || 'N/A'}</div>
                        </div>
                    </td>

                    <td style="padding: 16px;">
                        <div style="display: flex; flex-direction: column; gap: 6px;">
                            <span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; background: ${item.isOnline ? '#e3f2fd' : '#fee2e2'}; border-radius: 40px; font-size: 12px; font-weight: 500; color: ${item.isOnline ? '#1976d2' : '#dc2626'}; width: fit-content;">
                                <span style="width: 8px; height: 8px; border-radius: 50%; background: ${item.isOnline ? '#1976d2' : '#dc2626'}; ${item.isOnline ? 'animation: pulse 2s infinite;' : ''}"></span>
                                ${item.isOnline ? 'Online' : 'Offline'}
                            </span>
                            <span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; background: ${item.active ? '#e8f5e9' : '#fff3e0'}; border-radius: 40px; font-size: 12px; font-weight: 500; color: ${item.active ? '#2e7d32' : '#ed6c02'}; width: fit-content;">
                                <i class="fas ${item.active ? 'fa-check-circle' : 'fa-clock'}" style="font-size: 10px;"></i>
                                ${item.active ? 'Active' : 'Inactive'}
                            </span>
                        </div>
                    </td>

                    <td style="padding: 16px; text-align: center;">
                        <div class="action-dropdown" style="position: relative; display: inline-block;">
                            <button onclick="toggleActionMenu('${serialNo}')" style="width: 36px; height: 36px; border: 1px solid #eaeef2; border-radius: 8px; background: white; cursor: pointer; transition: all 0.2s;">
                                <i class="fas fa-ellipsis-v" style="color: #5b677c;"></i>
                            </button>
                            <div id="menu_${serialNo}" style="display: none; position: absolute; right: 0; top: 45px; width: 300px; background: white; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); border: 1px solid #eaeef2; z-index: 1000;">
                                <div style="padding: 12px; border-bottom: 1px solid #eaeef2; background: #f8fafc; border-radius: 12px 12px 0 0;">
                                    <span style="font-weight: 600; color: #1a1f36;">Device Commands - ${serialNo}</span>
                                </div>
                                <div style="padding: 8px; max-height: 400px; overflow-y: auto;">
                                    <!-- Power Management -->
                                    <div style="padding: 4px 8px; margin-top: 4px;">
                                        <span style="font-size: 11px; font-weight: 600; color: #64748b; text-transform: uppercase;">Power Management</span>
                                    </div>
                                    <button onclick='lowPowerMode("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-battery-quarter" style="width: 18px; color: #f59e0b;"></i> Low Power Mode
                                    </button>
                                    <button onclick='exitDeepSleep("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-power-off" style="width: 18px; color: #10b981;"></i> Exit Deep Sleep
                                    </button>
                                    <button onclick='enterSleepMode("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-moon" style="width: 18px; color: #6366f1;"></i> Enter Sleep Mode
                                    </button>
                                    <button onclick='disableSleepMode("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-sun" style="width: 18px; color: #f59e0b;"></i> Disable Sleep Mode
                                    </button>

                                    <!-- IP Configuration -->
                                    <div style="padding: 4px 8px; margin-top: 8px;">
                                        <span style="font-size: 11px; font-weight: 600; color: #64748b; text-transform: uppercase;">IP Configuration</span>
                                    </div>
                                    <button onclick='setIPPrimary("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-network-wired" style="width: 18px; color: #3b82f6;"></i> Set Primary IP
                                    </button>
                                    <button onclick='setIPSecondary("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-network-wired" style="width: 18px; color: #8b5cf6;"></i> Set Secondary IP
                                    </button>

                                    <!-- Device Configuration -->
                                    <div style="padding: 4px 8px; margin-top: 8px;">
                                        <span style="font-size: 11px; font-weight: 600; color: #64748b; text-transform: uppercase;">Device Configuration</span>
                                    </div>
                                    <button onclick='setOperationMode("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-sliders-h" style="width: 18px; color: #ec4899;"></i> Set Operation Mode
                                    </button>
                                    <button onclick='setTimezone("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-clock" style="width: 18px; color: #14b8a6;"></i> Set Timezone (GMT+3)
                                    </button>
                                    <button onclick='setAuthorizedNumbers("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-phone-alt" style="width: 18px; color: #8b5cf6;"></i> Set Authorized Numbers
                                    </button>
                                    <button onclick='changeUnlockPassword("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-key" style="width: 18px; color: #f97316;"></i> Change Unlock Password
                                    </button>

                                    <!-- Commands from existing code -->
                                    <div style="padding: 4px 8px; margin-top: 8px;">
                                        <span style="font-size: 11px; font-weight: 600; color: #64748b; text-transform: uppercase;">Basic Commands</span>
                                    </div>
                                    <button onclick='resetHistoricalPosition("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-history" style="width: 18px; color: #ef4444;"></i> Reset Historical Position
                                    </button>
                                    <button onclick='unlockdevice("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-lock-open" style="width: 18px;"></i> Unlock Device
                                    </button>
                                    <button onclick='factoryReset("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #dc2626;">
                                        <i class="fas fa-rotate-left" style="width: 18px;"></i> Factory Reset
                                    </button>
                                    <button onclick='restartDevice("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-power-off" style="width: 18px;"></i> Restart Device
                                    </button>
                                    <button onclick='setSerialNumber("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-barcode" style="width: 18px;"></i> Set Serial Number
                                    </button>

                                    <!-- Query Commands -->
                                    <div style="padding: 4px 8px; margin-top: 8px;">
                                        <span style="font-size: 11px; font-weight: 600; color: #64748b; text-transform: uppercase;">Query Commands</span>
                                    </div>
                                    <button onclick='queryDeviceInfo("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-info-circle" style="width: 18px;"></i> Query IP/Serial/APN
                                    </button>
                                    <button onclick='queryDeviceStatus("${serialNo}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-chart-line" style="width: 18px;"></i> Query Device Status
                                    </button>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
                `;
            });

            html += `
                        </tbody>
                    </table>
                </div>

                <!-- Table Footer -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-top: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
                    <div style="color: #5b677c;">
                        <span id="selectedCount">0</span> items selected
                    </div>
                    <div class="table-pagination" id="tablePagination"></div>
                </div>

                <style>
                    /* Filter chip active state */
                    .filter-chip.active {
                        background: #000 !important;
                        color: white !important;
                        border-color: #000 !important;
                    }
                    
                    /* Table row hover */
                    .devices-table tbody tr:hover {
                        background: #f8fafc;
                        cursor: pointer;
                    }
                    
                    /* Action button hover */
                    .action-dropdown button:hover {
                        background: #f0f2f5;
                    }
                    
                    /* Pulse animation for online dot */
                    @keyframes pulse {
                        0%, 100% { opacity: 1; }
                        50% { opacity: 0.5; }
                    }
                    
                    /* Scrollbar styling */
                    .action-dropdown div::-webkit-scrollbar {
                        width: 4px;
                    }
                    
                    .action-dropdown div::-webkit-scrollbar-track {
                        background: #f1f1f1;
                        border-radius: 4px;
                    }
                    
                    .action-dropdown div::-webkit-scrollbar-thumb {
                        background: #888;
                        border-radius: 4px;
                    }
                    
                    .action-dropdown div::-webkit-scrollbar-thumb:hover {
                        background: #555;
                    }
                    
                    /* Responsive */
                    @media (max-width: 768px) {
                        .devices-container { padding: 12px !important; }
                        .statistics-grid { grid-template-columns: 1fr 1fr !important; }
                    }
                </style>
            </div>
            `;

            $(".tab_commands").html(html);

            // Initialize DataTable
           // In the success function, after rendering the table, replace the DataTable initialization and search code with this:

                // Initialize DataTable with proper configuration
                const table = $('#devicetableview').DataTable({
                    dom: 'rtip',
                    pageLength: parseInt($('#pageSize').val()) || 10,
                    lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
                    order: [[1, 'asc']],
                    columnDefs: [
                        { orderable: false, targets: [0, 6] } // Disable sorting on checkbox and action columns
                    ],
                    initComplete: function() {
                        // Style the pagination
                        $('.dataTables_paginate').css({
                            'display': 'flex',
                            'gap': '4px',
                            'justify-content': 'flex-end',
                            'margin-top': '10px'
                        });
                        
                        $('.paginate_button').css({
                            'padding': '6px 12px',
                            'border': '1px solid #eaeef2',
                            'border-radius': '8px',
                            'background': 'white',
                            'cursor': 'pointer',
                            'margin': '0 2px'
                        });
                        
                        $('.paginate_button.current').css({
                            'background': '#000',
                            'color': 'white',
                            'border-color': '#000'
                        });
                        
                        $('.dataTables_info').css({
                            'color': '#5b677c',
                            'font-size': '14px',
                            'margin-bottom': '10px'
                        });
                    },
                    drawCallback: function() {
                        // Re-attach checkbox functionality after table redraw
                        attachCheckboxHandlers();
                    }
                });

                // Function to attach checkbox handlers
                function attachCheckboxHandlers() {
                    // Select All functionality
                    $("#selectAll").off("click").on("click", function() {
                        $(".row-checkbox").prop("checked", this.checked);
                        updateSelectedCount();
                    });

                    // Individual checkbox change
                    $(".row-checkbox").off("change").on("change", function() {
                        updateSelectedCount();
                        const total = $(".row-checkbox").length;
                        const checked = $(".row-checkbox:checked").length;
                        $("#selectAll").prop("checked", total === checked && total > 0);
                    });
                }

                // Search functionality - FIXED VERSION
                $('#deviceSearch').off('keyup').on('keyup', function() {
                    const searchTerm = this.value;
                    
                    // Clear any existing timer
                    if (window.searchTimer) {
                        clearTimeout(window.searchTimer);
                    }
                    
                    // Set a timer to avoid too many searches while typing
                    window.searchTimer = setTimeout(function() {
                        table.search(searchTerm).draw();
                        
                        // Re-attach checkbox handlers after search
                        setTimeout(attachCheckboxHandlers, 100);
                    }, 300); // 300ms delay
                });

                // Page size change - FIXED VERSION
                $('#pageSize').off('change').on('change', function() {
                    const newLength = parseInt(this.value);
                    table.page.len(newLength).draw();
                });

                // Update selected count function
                function updateSelectedCount() {
                    const count = $(".row-checkbox:checked").length;
                    $("#selectedCount").text(count);
                }

                // Initial attachment of checkbox handlers
                attachCheckboxHandlers();

                // Close dropdowns when clicking outside
                $(document).off('click').on('click', function(e) {
                    if (!$(e.target).closest('.action-dropdown').length) {
                        $('[id^="menu_"]').hide();
                    }
                });

                // Add a clear search button functionality
                $('#deviceSearch').after(`
                    <span id="clearSearch" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); cursor: pointer; color: #94a3b8; display: none;">
                        <i class="fas fa-times"></i>
                    </span>
                `);

                // Show/hide clear button based on search input
                $('#deviceSearch').on('input', function() {
                    if (this.value.length > 0) {
                        $('#clearSearch').show();
                    } else {
                        $('#clearSearch').hide();
                    }
                });

                // Clear search functionality
                $('#clearSearch').off('click').on('click', function() {
                    $('#deviceSearch').val('').trigger('input');
                    table.search('').draw();
                });

                // Also, make sure the table ID is unique and not conflicting with any other elements
                // If you have multiple tables on the same page, consider using a more specific selector

                // Optional: Add a loading indicator for search
                let searchRequestCount = 0;
                $('#deviceSearch').on('keyup', function() {
                    const searchTerm = this.value;
                    searchRequestCount++;
                    const currentRequest = searchRequestCount;
                    
                    // Show loading indicator
                    $(this).parent().find('.fa-search').removeClass('fa-search').addClass('fa-spinner fa-spin');
                    
                    setTimeout(function() {
                        if (currentRequest === searchRequestCount) {
                            table.search(searchTerm).draw();
                            // Hide loading indicator
                            $('#deviceSearch').parent().find('.fa-spinner').removeClass('fa-spinner fa-spin').addClass('fa-search');
                            attachCheckboxHandlers();
                        }
                    }, 500);
                });

            // Search functionality
          

            
        },
        error: function(xhr, status, error) {
            console.error("Error loading devices:", error);
            $(".tab_devices").html(`
                <div style="padding: 40px; text-align: center; background: white; border-radius: 16px; margin: 24px;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #dc2626; margin-bottom: 16px;"></i>
                    <h3 style="color: #1a1f36; margin-bottom: 8px;">Failed to load devices</h3>
                    <p style="color: #5b677c; margin-bottom: 20px;">${error}</p>
                    <button onclick="allDevices()" style="padding: 10px 24px; background: #000; color: white; border: none; border-radius: 10px; cursor: pointer;">
                        <i class="fas fa-sync-alt"></i> Retry
                    </button>
                </div>
            `);
        }
    });
}

// Helper function for time ago
function timeSince(date) {
    const seconds = Math.floor((new Date() - date) / 1000);
    
    let interval = seconds / 31536000;
    if (interval > 1) return Math.floor(interval) + ' years ago';
    
    interval = seconds / 2592000;
    if (interval > 1) return Math.floor(interval) + ' months ago';
    
    interval = seconds / 86400;
    if (interval > 1) return Math.floor(interval) + ' days ago';
    
    interval = seconds / 3600;
    if (interval > 1) return Math.floor(interval) + ' hours ago';
    
    interval = seconds / 60;
    if (interval > 1) return Math.floor(interval) + ' minutes ago';
    
    return 'just now';
}

// Action menu functions
function toggleActionMenu(deviceId) {
    $('[id^="menu_"]').hide();
    $(`#menu_${deviceId}`).toggle();
}

// Helper function to send command
function sendDeviceCommand(serialNo, command, successMessage, errorMessage) {
    const formJson = {
        "deviceSn": serialNo,
        "command": command
    };
    
    const url = serverURL + "devices/command/set";
    
    Swal.fire({
        title: 'Sending Command',
        html: 'Please wait...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    controller.allPostRequestDevice(url, formJson, '', function(data, status) {
        if (data && data.resultCode == 0) {
            Swal.fire({
                title: 'Success!',
                text: successMessage || 'Command sent successfully',
                icon: 'success',
                confirmButtonColor: '#000',
                background: '#ffffff',
                color: '#1a1f36'
            });
        } else {
            Swal.fire({
                title: 'Failed!',
                text: errorMessage || 'Failed to send command',
                icon: 'error',
                confirmButtonColor: '#000',
                background: '#ffffff',
                color: '#1a1f36'
            });
        }
    });
}

// 1. Low Power Mode
function lowPowerMode(serialNo) {
    Swal.fire({
        title: 'Low Power Mode',
        html: `
            <div class="ui form" style="text-align: left; padding: 10px;">
                <div class="field">
                    <label>Device Serial</label>
                    <div class="ui input">
                        <input type="text" value="${serialNo}" readonly>
                    </div>
                </div>
                <div class="field">
                    <label>Battery Level (%) <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-battery-quarter icon"></i>
                        <input type="number" id="batteryLevel" placeholder="e.g., 10" min="0" max="100" step="1" value="10">
                    </div>
                </div>
                <div class="field">
                    <label>Report Duration (hours) <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-clock icon"></i>
                        <input type="number" id="reportDuration" placeholder="e.g., 0.1 (6 minutes)" min="0.1" max="24" step="0.1" value="0.1">
                    </div>
                    <small style="color: #666;">0.1 hours = 6 minutes</small>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Activate Low Power Mode',
        confirmButtonColor: '#f59e0b',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '500px',
        preConfirm: () => {
            const batteryLevel = $('#batteryLevel').val();
            const reportDuration = $('#reportDuration').val();
            
            if (!batteryLevel) {
                Swal.showValidationMessage('Battery level is required');
                return false;
            }
            if (!reportDuration) {
                Swal.showValidationMessage('Report duration is required');
                return false;
            }
            if (batteryLevel < 0 || batteryLevel > 100) {
                Swal.showValidationMessage('Battery level must be between 0 and 100');
                return false;
            }
            
            return { batteryLevel, reportDuration };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { batteryLevel, reportDuration } = result.value;
            const command = `*269#9,M7,${batteryLevel},${reportDuration}`;
            sendDeviceCommand(serialNo, command, 'Low Power Mode activated successfully', 'Failed to activate Low Power Mode');
        }
    });
}

// 2. Set Primary IP
function setIPPrimary(serialNo) {
    Swal.fire({
        title: 'Set Primary IP/Domain',
        html: `
            <div class="ui form" style="text-align: left; padding: 10px;">
                <div class="field">
                    <label>Device Serial</label>
                    <div class="ui input">
                        <input type="text" value="${serialNo}" readonly>
                    </div>
                </div>
                <div class="field">
                    <label>IP/Domain <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-network-wired icon"></i>
                        <input type="text" id="ipPrimary" placeholder="e.g., bsl.co.ke or 192.168.1.100">
                    </div>
                </div>
                <div class="field">
                    <label>Port <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-plug icon"></i>
                        <input type="text" id="portPrimary" placeholder="e.g., 8080">
                    </div>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Set Primary IP',
        confirmButtonColor: '#3b82f6',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '500px',
        preConfirm: () => {
            const ip = $('#ipPrimary').val();
            const port = $('#portPrimary').val();
            
            if (!ip) {
                Swal.showValidationMessage('IP/Domain is required');
                return false;
            }
            if (!port) {
                Swal.showValidationMessage('Port is required');
                return false;
            }
            
            return { ip, port };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { ip, port } = result.value;
            const command = `*269#1,${ip},${port},1`;
            sendDeviceCommand(serialNo, command, 'Primary IP set successfully', 'Failed to set Primary IP');
        }
    });
}

// 2b. Set Secondary IP
function setIPSecondary(serialNo) {
    Swal.fire({
        title: 'Set Secondary IP/Domain',
        html: `
            <div class="ui form" style="text-align: left; padding: 10px;">
                <div class="field">
                    <label>Device Serial</label>
                    <div class="ui input">
                        <input type="text" value="${serialNo}" readonly>
                    </div>
                </div>
                <div class="field">
                    <label>IP/Domain <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-network-wired icon"></i>
                        <input type="text" id="ipSecondary" placeholder="e.g., backup.bsl.co.ke">
                    </div>
                </div>
                <div class="field">
                    <label>Port <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-plug icon"></i>
                        <input type="text" id="portSecondary" placeholder="e.g., 8081">
                    </div>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Set Secondary IP',
        confirmButtonColor: '#8b5cf6',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '500px',
        preConfirm: () => {
            const ip = $('#ipSecondary').val();
            const port = $('#portSecondary').val();
            
            if (!ip) {
                Swal.showValidationMessage('IP/Domain is required');
                return false;
            }
            if (!port) {
                Swal.showValidationMessage('Port is required');
                return false;
            }
            
            return { ip, port };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { ip, port } = result.value;
            const command = `*269#I2,${ip},${port},1`;
            sendDeviceCommand(serialNo, command, 'Secondary IP set successfully', 'Failed to set Secondary IP');
        }
    });
}

// 3. Reset Historical Position
function resetHistoricalPosition(serialNo) {
    Swal.fire({
        title: 'Reset Historical Position',
        html: `
            <div class="ui form" style="text-align: left; padding: 10px;">
                <div class="field">
                    <label>Device Serial</label>
                    <div class="ui input">
                        <input type="text" value="${serialNo}" readonly>
                    </div>
                </div>
                <div class="field">
                    <label>Device Serial Number to Reset <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-barcode icon"></i>
                        <input type="text" id="resetSerial" placeholder="Enter 8-digit serial number" maxlength="8">
                    </div>
                    <small style="color: #666;">Enter the device serial number to reset historical position</small>
                </div>
            </div>
        `,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Reset Historical Position',
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '500px',
        preConfirm: () => {
            const resetSerial = $('#resetSerial').val();
            
            if (!resetSerial) {
                Swal.showValidationMessage('Serial number is required');
                return false;
            }
            if (resetSerial.length !== 8) {
                Swal.showValidationMessage('Serial number must be 8 digits');
                return false;
            }
            if (!/^\d+$/.test(resetSerial)) {
                Swal.showValidationMessage('Serial number must contain only digits');
                return false;
            }
            
            return resetSerial;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const resetSerial = result.value;
            const command = `*269#2,${resetSerial}`;
            sendDeviceCommand(serialNo, command, 'Historical position reset successfully', 'Failed to reset historical position');
        }
    });
}

// 4. Disable Sleep Mode
function disableSleepMode(serialNo) {
    Swal.fire({
        title: 'Disable Sleep Mode',
        html: `<p>Are you sure you want to disable sleep mode for device <strong>${serialNo}</strong>?</p>`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Disable Sleep Mode',
        confirmButtonColor: '#f59e0b',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            const command = "*269#9,M0";
            sendDeviceCommand(serialNo, command, 'Sleep mode disabled successfully', 'Failed to disable sleep mode');
        }
    });
}

// 5. Set Timezone (GMT+3)
function setTimezone(serialNo) {
    Swal.fire({
        title: 'Set Timezone',
        html: `
            <div class="ui form" style="text-align: left; padding: 10px;">
                <div class="field">
                    <label>Device Serial</label>
                    <div class="ui input">
                        <input type="text" value="${serialNo}" readonly>
                    </div>
                </div>
                <div class="field">
                    <label>Timezone</label>
                    <div class="ui input">
                        <input type="text" value="GMT+3" readonly>
                    </div>
                </div>
                <p>This will set the device timezone to GMT+3</p>
            </div>
        `,
        icon: 'info',
        showCancelButton: true,
        confirmButtonText: 'Set Timezone',
        confirmButtonColor: '#14b8a6',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            const command = "*269#I,E3,";
            sendDeviceCommand(serialNo, command, 'Timezone set to GMT+3 successfully', 'Failed to set timezone');
        }
    });
}

// 6. Change Device Operation Mode
function setOperationMode(serialNo) {
    Swal.fire({
        title: 'Set Operation Mode',
        html: `
            <div class="ui form" style="text-align: left; padding: 10px;">
                <div class="field">
                    <label>Device Serial</label>
                    <div class="ui input">
                        <input type="text" value="${serialNo}" readonly>
                    </div>
                </div>
                <div class="field">
                    <label>Report Interval when Locked (seconds) <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-lock icon"></i>
                        <input type="number" id="lockInterval" placeholder="e.g., 5" min="1" step="1" value="5">
                    </div>
                </div>
                <div class="field">
                    <label>Report Interval when Unlocked (seconds) <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-lock-open icon"></i>
                        <input type="number" id="unlockInterval" placeholder="e.g., 300" min="1" step="1" value="300">
                    </div>
                </div>
                <small>Example: 5,300 means report every 5 seconds when locked, 300 seconds when unlocked</small>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Set Operation Mode',
        confirmButtonColor: '#ec4899',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '500px',
        preConfirm: () => {
            const lockInterval = $('#lockInterval').val();
            const unlockInterval = $('#unlockInterval').val();
            
            if (!lockInterval) {
                Swal.showValidationMessage('Lock interval is required');
                return false;
            }
            if (!unlockInterval) {
                Swal.showValidationMessage('Unlock interval is required');
                return false;
            }
            
            return { lockInterval, unlockInterval };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { lockInterval, unlockInterval } = result.value;
            const command = `*269#7,${lockInterval},${unlockInterval},`;
            sendDeviceCommand(serialNo, command, 'Operation mode set successfully', 'Failed to set operation mode');
        }
    });
}

// 7. Exit Deep Sleep Mode
function exitDeepSleep(serialNo) {
    Swal.fire({
        title: 'Exit Deep Sleep Mode',
        html: `<p>Are you sure you want to exit deep sleep mode for device <strong>${serialNo}</strong>?</p>`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Exit Deep Sleep',
        confirmButtonColor: '#10b981',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            const command = "*269#9,M7,0";
            sendDeviceCommand(serialNo, command, 'Exited deep sleep mode successfully', 'Failed to exit deep sleep mode');
        }
    });
}

// 8. Enter Sleep Mode
function enterSleepMode(serialNo) {
    Swal.fire({
        title: 'Enter Sleep Mode',
        html: `
            <div class="ui form" style="text-align: left; padding: 10px;">
                <div class="field">
                    <label>Device Serial</label>
                    <div class="ui input">
                        <input type="text" value="${serialNo}" readonly>
                    </div>
                </div>
                <div class="field">
                    <label>Wake Up Working Time (seconds) <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-clock icon"></i>
                        <input type="number" id="wakeTime" placeholder="e.g., 30" min="1" step="1" value="30">
                    </div>
                </div>
                <div class="field">
                    <label>Sleep Time (seconds) <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-moon icon"></i>
                        <input type="number" id="sleepTime" placeholder="e.g., 300" min="1" step="1" value="300">
                    </div>
                </div>
                <small>M2 mode: Both GSM and GPS will be closed during sleep</small>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Enter Sleep Mode',
        confirmButtonColor: '#6366f1',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '500px',
        preConfirm: () => {
            const wakeTime = $('#wakeTime').val();
            const sleepTime = $('#sleepTime').val();
            
            if (!wakeTime) {
                Swal.showValidationMessage('Wake up time is required');
                return false;
            }
            if (!sleepTime) {
                Swal.showValidationMessage('Sleep time is required');
                return false;
            }
            
            return { wakeTime, sleepTime };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { wakeTime, sleepTime } = result.value;
            const command = `*269#9,M2,${wakeTime},${sleepTime},`;
            sendDeviceCommand(serialNo, command, 'Entered sleep mode successfully', 'Failed to enter sleep mode');
        }
    });
}

// 9. Set Authorized Numbers (up to 4 numbers)
function setAuthorizedNumbers(serialNo) {
    Swal.fire({
        title: 'Set Authorized Numbers',
        html: `
            <div class="ui form" style="text-align: left; padding: 10px;">
                <div class="field">
                    <label>Device Serial</label>
                    <div class="ui input">
                        <input type="text" value="${serialNo}" readonly>
                    </div>
                </div>
                <div class="field">
                    <label>Authorized Number 1 (optional)</label>
                    <div class="ui input left icon">
                        <i class="fas fa-phone-alt icon"></i>
                        <input type="text" id="authNum1" placeholder="e.g., 716826814 (without leading 0)">
                    </div>
                </div>
                <div class="field">
                    <label>Authorized Number 2 (optional)</label>
                    <div class="ui input left icon">
                        <i class="fas fa-phone-alt icon"></i>
                        <input type="text" id="authNum2" placeholder="e.g., 712345678">
                    </div>
                </div>
                <div class="field">
                    <label>Authorized Number 3 (optional)</label>
                    <div class="ui input left icon">
                        <i class="fas fa-phone-alt icon"></i>
                        <input type="text" id="authNum3" placeholder="e.g., 723456789">
                    </div>
                </div>
                <div class="field">
                    <label>Authorized Number 4 (optional)</label>
                    <div class="ui input left icon">
                        <i class="fas fa-phone-alt icon"></i>
                        <input type="text" id="authNum4" placeholder="e.g., 734567890">
                    </div>
                </div>
                <small style="color: #666;">Do not include leading zero. At least one number is required</small>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Set Authorized Numbers',
        confirmButtonColor: '#8b5cf6',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '500px',
        preConfirm: () => {
            const num1 = $('#authNum1').val();
            const num2 = $('#authNum2').val();
            const num3 = $('#authNum3').val();
            const num4 = $('#authNum4').val();
            
            // Validate at least one number
            if (!num1 && !num2 && !num3 && !num4) {
                Swal.showValidationMessage('At least one authorized number is required');
                return false;
            }
            
            // Validate numbers (only digits)
            const numbers = [num1, num2, num3, num4].filter(n => n);
            for (let num of numbers) {
                if (!/^\d+$/.test(num)) {
                    Swal.showValidationMessage('Phone numbers must contain only digits');
                    return false;
                }
            }
            
            return { num1, num2, num3, num4 };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { num1, num2, num3, num4 } = result.value;
            
            // Build command with up to 4 numbers
            let command = "*269#5";
            if (num1) command += `,${num1}`;
            if (num2) command += `,${num2}`;
            if (num3) command += `,${num3}`;
            if (num4) command += `,${num4}`;
            command += ",";
            
            sendDeviceCommand(serialNo, command, 'Authorized numbers set successfully', 'Failed to set authorized numbers');
        }
    });
}

// 10. Change Unlock Password
function changeUnlockPassword(serialNo) {
    Swal.fire({
        title: 'Change Unlock Password',
        html: `
            <div class="ui form" style="text-align: left; padding: 10px;">
                <div class="field">
                    <label>Device Serial</label>
                    <div class="ui input">
                        <input type="text" value="${serialNo}" readonly>
                    </div>
                </div>
                <div class="field">
                    <label>Old Password <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-key icon"></i>
                        <input type="password" id="oldPassword" placeholder="Enter old password" value="888888">
                    </div>
                </div>
                <div class="field">
                    <label>New Password <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-key icon"></i>
                        <input type="password" id="newPassword" placeholder="Enter new password (6 digits)">
                    </div>
                </div>
                <div class="field">
                    <label>Confirm New Password <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-key icon"></i>
                        <input type="password" id="confirmPassword" placeholder="Confirm new password">
                    </div>
                </div>
                <small style="color: #666;">Password must be 6 digits</small>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Change Password',
        confirmButtonColor: '#f97316',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '500px',
        preConfirm: () => {
            const oldPassword = $('#oldPassword').val();
            const newPassword = $('#newPassword').val();
            const confirmPassword = $('#confirmPassword').val();
            
            if (!oldPassword) {
                Swal.showValidationMessage('Old password is required');
                return false;
            }
            if (!newPassword) {
                Swal.showValidationMessage('New password is required');
                return false;
            }
            if (!confirmPassword) {
                Swal.showValidationMessage('Please confirm new password');
                return false;
            }
            if (newPassword !== confirmPassword) {
                Swal.showValidationMessage('Passwords do not match');
                return false;
            }
            if (newPassword.length !== 6 || !/^\d+$/.test(newPassword)) {
                Swal.showValidationMessage('New password must be 6 digits');
                return false;
            }
            
            return { oldPassword, newPassword };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { oldPassword, newPassword } = result.value;
            const command = `*269#4,${oldPassword},${newPassword},`;
            sendDeviceCommand(serialNo, command, 'Password changed successfully', 'Failed to change password');
        }
    });
}

// Unlock Device function
function unlockdevice(serialNo) {
    Swal.fire({
        title: 'Unlock Device',
        html: `<p>Are you sure you want to unlock device <strong>${serialNo}</strong>?</p>`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Unlock',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            const command = "*269#8,888888";
            sendDeviceCommand(serialNo, command, 'Device unlocked successfully', 'Failed to unlock device');
        }
    });
}

// Factory Reset function
function factoryReset(serialNo) {
    Swal.fire({
        title: 'Factory Reset',
        html: `<div style="text-align: center;">
                <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #dc2626; margin-bottom: 16px;"></i>
                <p style="font-size: 16px; color: #1a1f36; margin-bottom: 8px;">Are you sure you want to perform a factory reset on device <strong>${serialNo}</strong>?</p>
                <p style="font-size: 14px; color: #dc2626;">This action cannot be undone!</p>
               </div>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Reset Device',
        confirmButtonColor: '#dc2626',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            const command = "*269#F";
            sendDeviceCommand(serialNo, command, 'Factory reset command sent successfully', 'Failed to send factory reset command');
        }
    });
}

// Restart Device function
function restartDevice(serialNo) {
    Swal.fire({
        title: 'Restart Device',
        html: `<div style="text-align: center;">
                <p style="font-size: 16px; color: #1a1f36; margin-bottom: 8px;">Are you sure you want to restart device <strong>${serialNo}</strong>?</p>
                <p style="font-size: 14px; color: #5b677c;">The device will be temporarily offline during restart.</p>
               </div>`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Restart',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            const command = "*269#B";
            sendDeviceCommand(serialNo, command, 'Restart command sent successfully', 'Failed to send restart command');
        }
    });
}

// Set Serial Number function
function setSerialNumber(serialNo) {
    Swal.fire({
        title: 'Set Device Serial Number',
        html: `
            <div class="ui form" style="text-align: left; padding: 10px;">
                <div class="field">
                    <label>Current Serial</label>
                    <div class="ui input">
                        <input type="text" value="${serialNo}" readonly>
                    </div>
                </div>
                <div class="field">
                    <label>New Serial Number <span style="color: #db2828;">*</span></label>
                    <div class="ui input left icon">
                        <i class="fas fa-barcode icon"></i>
                        <input type="text" id="newSerial" placeholder="Enter 8-digit serial number" maxlength="8">
                    </div>
                    <small style="color: #666;">Serial number must be 8 digits</small>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Set Serial',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '500px',
        preConfirm: () => {
            const newSerial = $('#newSerial').val();
            
            if (!newSerial) {
                Swal.showValidationMessage('Serial number is required');
                return false;
            }
            if (newSerial.length !== 8) {
                Swal.showValidationMessage('Serial number must be 8 digits');
                return false;
            }
            if (!/^\d+$/.test(newSerial)) {
                Swal.showValidationMessage('Serial number must contain only digits');
                return false;
            }
            
            return newSerial;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const newSerial = result.value;
            const command = `*269#2,${newSerial}`;
            sendDeviceCommand(serialNo, command, 'Serial number set successfully', 'Failed to set serial number');
        }
    });
}

// Query Device Info (IP, Serial, APN) function
function queryDeviceInfo(serialNo) {
    Swal.fire({
        title: 'Query Device Information',
        text: `Fetching IP, Serial Number and APN for device ${serialNo}...`,
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
            
            const formJson = {
                "deviceSn": serialNo,
                "command": "*269#C"
            };
            const url = serverURL + "devices/command/query";
            
            controller.allPostRequestDevice(url, formJson, '', function(data, status) {
                if (data && data.resultCode == 0) {
                    let responseText = data.response || data.message || 'No response data';
                    
                    Swal.fire({
                        title: 'Device Information',
                        html: `
                            <div class="ui segment" style="text-align: left; padding: 15px;">
                                <div class="ui relaxed list">
                                    <div class="item">
                                        <i class="fas fa-microchip icon"></i>
                                        <div class="content">
                                            <div class="header">Device Serial</div>
                                            <div class="description">${serialNo}</div>
                                        </div>
                                    </div>
                                    <div class="item">
                                        <i class="fas fa-info-circle icon"></i>
                                        <div class="content">
                                            <div class="header">Response</div>
                                            <div class="description">
                                                <pre style="background: #f8fafc; padding: 10px; border-radius: 4px; border: 1px solid #eaeef2; overflow-x: auto; white-space: pre-wrap; word-wrap: break-word; margin-top: 5px;">${responseText}</pre>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `,
                        icon: 'success',
                        confirmButtonColor: '#000',
                        background: '#ffffff',
                        color: '#1a1f36',
                        width: '600px'
                    });
                } else {
                    Swal.fire({
                        title: 'Query Failed',
                        text: data.message || 'Failed to query device information',
                        icon: 'error',
                        confirmButtonColor: '#000',
                        background: '#ffffff',
                        color: '#1a1f36'
                    });
                }
            });
        }
    });
}

// Query Device Status function
function queryDeviceStatus(serialNo) {
    Swal.fire({
        title: 'Query Device Status',
        text: `Fetching status for device ${serialNo}...`,
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
            
            const formJson = {
                "deviceSn": serialNo,
                "command": "*269#R"
            };
            const url = serverURL + "devices/command/query";
            
            controller.allPostRequestDevice(url, formJson, '', function(data, status) {
                if (data && data.resultCode == 0) {
                    let responseText = data.response || data.message || 'No response data';
                    
                    Swal.fire({
                        title: 'Device Status',
                        html: `
                            <div class="ui segment" style="text-align: left; padding: 15px;">
                                <div class="ui relaxed list">
                                    <div class="item">
                                        <i class="fas fa-microchip icon"></i>
                                        <div class="content">
                                            <div class="header">Device Serial</div>
                                            <div class="description">${serialNo}</div>
                                        </div>
                                    </div>
                                    <div class="item">
                                        <i class="fas fa-chart-line icon"></i>
                                        <div class="content">
                                            <div class="header">Status Response</div>
                                            <div class="description">
                                                <pre style="background: #f8fafc; padding: 10px; border-radius: 4px; border: 1px solid #eaeef2; overflow-x: auto; white-space: pre-wrap; word-wrap: break-word; margin-top: 5px;">${responseText}</pre>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `,
                        icon: 'success',
                        confirmButtonColor: '#000',
                        background: '#ffffff',
                        color: '#1a1f36',
                        width: '600px'
                    });
                } else {
                    Swal.fire({
                        title: 'Query Failed',
                        text: data.message || 'Failed to query device status',
                        icon: 'error',
                        confirmButtonColor: '#000',
                        background: '#ffffff',
                        color: '#1a1f36'
                    });
                }
            });
        }
    });
}

// Bulk Commands function (for selected devices)
function sendBulkCommand() {
    const selectedDevices = $(".row-checkbox:checked").map(function() {
        return $(this).data('id');
    }).get();
    
    if (selectedDevices.length === 0) {
        Swal.fire({
            title: 'No Devices Selected',
            text: 'Please select at least one device',
            icon: 'warning',
            confirmButtonColor: '#000',
            background: '#ffffff',
            color: '#1a1f36'
        });
        return;
    }
    
    Swal.fire({
        title: 'Send Bulk Command',
        html: `
            <div class="ui form" style="text-align: left; padding: 10px;">
                <div class="field">
                    <label>Selected Devices</label>
                    <div class="ui label">
                        <i class="fas fa-microchip icon"></i> ${selectedDevices.length} devices
                    </div>
                </div>
                <div class="field">
                    <label>Select Command <span style="color: #db2828;">*</span></label>
                    <select id="bulkCommand" class="ui dropdown">
                        <option value="">-- Select Command --</option>
                        <option value="*269#B">Restart Device</option>
                        <option value="*269#8,888888">Unlock Device</option>
                        <option value="*269#9,M0">Disable Sleep Mode</option>
                        <option value="*269#9,M7,0">Exit Deep Sleep</option>
                        <option value="*269#F">Factory Reset</option>
                        <option value="*269#C">Query IP/Serial/APN</option>
                        <option value="*269#R">Query Status</option>
                    </select>
                </div>
                <small style="color: #666;">Note: This will send the command to all selected devices</small>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Send Command',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '500px',
        preConfirm: () => {
            const command = $('#bulkCommand').val();
            if (!command) {
                Swal.showValidationMessage('Please select a command');
                return false;
            }
            return command;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const command = result.value;
            const url = serverURL + "devices/command/set";
            
            Swal.fire({
                title: 'Sending Bulk Command',
                html: `Sending to ${selectedDevices.length} devices...`,
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                    
                    let completed = 0;
                    let successful = 0;
                    let failed = 0;
                    let results = [];
                    
                    selectedDevices.forEach((serialNo, index) => {
                        setTimeout(() => {
                            const formJson = {
                                "deviceSn": serialNo,
                                "command": command
                            };
                            
                            controller.allPostRequestDevice(url, formJson, '', function(data, status) {
                                completed++;
                                if (data && data.resultCode == 0) {
                                    successful++;
                                    results.push(`✓ ${serialNo}: Success`);
                                } else {
                                    failed++;
                                    results.push(`✗ ${serialNo}: Failed`);
                                }
                                
                                if (completed === selectedDevices.length) {
                                    let resultHtml = `
                                        <div class="ui statistic">
                                            <div class="value">${selectedDevices.length}</div>
                                            <div class="label">Total Devices</div>
                                        </div>
                                        <div class="ui statistic" style="margin-left: 20px;">
                                            <div class="value" style="color: #2e7d32;">${successful}</div>
                                            <div class="label">Successful</div>
                                        </div>
                                        <div class="ui statistic" style="margin-left: 20px;">
                                            <div class="value" style="color: #dc2626;">${failed}</div>
                                            <div class="label">Failed</div>
                                        </div>
                                        <div class="ui divider"></div>
                                        <div style="max-height: 200px; overflow-y: auto; text-align: left; font-size: 12px;">
                                            ${results.map(r => `<div style="padding: 2px 0;">${r}</div>`).join('')}
                                        </div>
                                    `;
                                    
                                    Swal.fire({
                                        title: 'Bulk Command Complete',
                                        html: resultHtml,
                                        icon: failed === 0 ? 'success' : (successful > 0 ? 'warning' : 'error'),
                                        confirmButtonColor: '#000',
                                        background: '#ffffff',
                                        color: '#1a1f36',
                                        width: '600px'
                                    });
                                }
                            });
                        }, index * 300); // Delay between requests
                    });
                }
            });
        }
    });
}

// Set IP/Domain function (keeping for backward compatibility)
function createSetdevice(serialNo) {
    setIPPrimary(serialNo);
}