

<?php $__env->startSection('content'); ?>

<?php if (! $__env->hasRenderedOnce('d86f8eb4-3037-4bde-a1cd-d3f3f9dce13b')): $__env->markAsRenderedOnce('d86f8eb4-3037-4bde-a1cd-d3f3f9dce13b'); ?>
<style>
/* Your existing CSS */
.signal-bars {
    display: inline-flex;
    align-items: flex-end;
    gap: 8px;
    height: 20px;
    margin-right: 8px;
}
.signal-bar {
    width: 4px;
    border-radius: 1px;
    transition: all 0.3s ease;
}
.signal-bar.bar-1 { height: 4px; }
.signal-bar.bar-2 { height: 8px; }
.signal-bar.bar-3 { height: 12px; }
.signal-bar.bar-4 { height: 16px; }
.signal-bar.bar-5 { height: 20px; }

.signal-bar.active.excellent { background-color: #22c55e; }
.signal-bar.active.good { background-color: #84cc16; }
.signal-bar.active.fair { background-color: #eab308; }
.signal-bar.active.poor { background-color: #f97316; }
.signal-bar.active.very-poor { background-color: #ef4444; }
.signal-bar.inactive { background-color: #e5e7eb; }

.signal-container {
    display: flex;
    align-items: center;
    gap: 8px;
}

.signal-value {
    font-size: 0.75rem;
    color: #6b7280;
    font-weight: 500;
}

.no-signal {
    color: #9ca3af;
    font-style: italic;
    font-size: 0.875rem;
}

.raw-json-container {
    margin-top: 20px;
    background: #f4f4f4;
    padding: 10px;
    border-radius: 6px;
    max-height: 300px;
    overflow-y: auto;
    font-size: 0.8rem;
    white-space: pre-wrap;
    user-select: text;
}

.btn {
    cursor: pointer;
    padding: 6px 12px;
    font-size: 0.875rem;
    border-radius: 4px;
    border: 1px solid #0d6efd;
    background-color: #fff;
    color: #0d6efd;
    transition: background-color 0.2s ease;
}

.btn:hover {
    background-color: #0d6efd;
    color: #fff;
}

/* New styles for row selection and control panel */
.table tbody tr {
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.table tbody tr:hover {
    background-color: #f8f9fa !important;
}

.table tbody tr.selected {
    background-color: #e3f2fd !important;
    border-left: 4px solid #2196f3;
}

.control-panel {
    display: flex;
    align-items: center;
    background: white;
    border: 1px solid #dee2e6;
    margin-top: 20px;
    border-radius: 4px;
    overflow: hidden;
}

.control-section {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 16px;
    border-right: 1px solid #dee2e6;
}

.control-section:last-child {
    border-right: none;
}

.control-label {
    font-size: 14px;
    font-weight: 500;
    color: #495057;
    white-space: nowrap;
}

.control-input {
    width: 200px;
    height: 32px;
    padding: 4px 8px;
    border: 1px solid #ced4da;
    border-radius: 4px;
    font-size: 14px;
}

.control-btn {
    height: 32px;
    padding: 0 16px;
    font-size: 14px;
    font-weight: 600;
    border: 1px solid #6c757d;
    background-color: #fff;
    color: #000;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.control-btn:hover {
    background-color: #f8f9fa;
}

.toggle-group {
    display: flex;
}

.toggle-btn {
    height: 32px;
    padding: 0 16px;
    font-size: 14px;
    font-weight: 600;
    border: 1px solid #6c757d;
    background-color: #fff;
    color: #000;
    cursor: pointer;
    transition: all 0.2s ease;
}

.toggle-btn:first-child {
    border-radius: 4px 0 0 4px;
    border-right: none;
}

.toggle-btn:last-child {
    border-radius: 0 4px 4px 0;
}

.toggle-btn:hover {
    background-color: #f8f9fa;
}

.toggle-btn.active {
    background-color: #e91e63;
    color: white;
    border-color: #e91e63;
}

.qr-icon {
    padding: 12px;
    color: #6c757d;
}

.selected-info {
    margin-top: 10px;
    padding: 8px 12px;
    background-color: #e3f2fd;
    border-radius: 4px;
    font-size: 14px;
    color: #1976d2;
}
</style>
<?php endif; ?>

<?php
$getSignalInfo = function($signal) {
    if ($signal == 0 || $signal == 99) {
        return ['bars' => 0, 'quality' => 'none'];
    }
    if ($signal >= 25) return ['bars' => 5, 'quality' => 'excellent'];
    if ($signal >= 19) return ['bars' => 4, 'quality' => 'good'];
    if ($signal >= 13) return ['bars' => 3, 'quality' => 'fair'];
    if ($signal >= 7)  return ['bars' => 2, 'quality' => 'poor'];
    if ($signal >= 1)  return ['bars' => 1, 'quality' => 'very-poor'];
    return ['bars' => 0, 'quality' => 'none'];
};
?>

<div class="container-fluid px-4 py-3">
    <h1>Modem Device Ports</h1>

    <div class="table-responsive">
        <table class="table table-bordered table-hover">
            <thead class="table-light">
                <tr>
                    <th>#</th>
                    <th>USB (port_name)</th>
                    <th>CCID (sim_iccid)</th>
                    <th>IMSI (subscriber_imsi)</th>
                    <th>SIM Country</th>
                    <th>SIM Operator (network_operator)</th>
                    <th>PIN (sim_pin_status)</th>
                    <th>Sim Network Signal</th>
                    <th>Operator</th>
                    <th>Online</th>
                    <th>Errors (operator_errors)</th>
                </tr>
            </thead>
            <tbody id="device-table-body">
                
                <?php $__currentLoopData = $data; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $device): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php
                        $signalArray = json_decode($device->signal_quality, true);
                        $signalsInt = is_array($signalArray)
                            ? array_filter(array_map('intval', $signalArray), fn($val) => $val > 0)
                            : [];
                        sort($signalsInt);
                    ?>
                    <tr class="<?php echo e($device->operator_errors ? 'table-danger' : 'table-primary'); ?>" data-device-id="<?php echo e($device->id ?? $index); ?>" data-port="<?php echo e($device->port_name); ?>">
                        <td><?php echo e($index + 1); ?></td>
                        <td><?php echo e($device->port_name ?? 'N/A'); ?></td>
                        <td><?php echo e($device->sim_iccid ?? '0'); ?></td>
                        <td><?php echo e($device->subscriber_imsi ?? '0'); ?></td>
                        <td>unknown</td>
                        <td><?php echo e($device->network_operator ?? ''); ?></td>
                        <td><?php echo e($device->sim_pin_status == 1 ? 'OK' : 'ERROR'); ?></td>
                        <td>
                            <?php if(empty($signalsInt)): ?>
                                <span class="no-signal">No signal data</span>
                            <?php else: ?>
                                <div class="d-flex flex-wrap gap-3">
                                    <?php $__currentLoopData = $signalsInt; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $signal): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <?php
                                            $signalInfo = $getSignalInfo($signal);
                                        ?>
                                        <div class="signal-container">
                                            <div class="signal-bars">
                                                <?php for($i = 1; $i <= 5; $i++): ?>
                                                    <div class="signal-bar bar-<?php echo e($i); ?> <?php echo e($i <= $signalInfo['bars'] ? 'active ' . $signalInfo['quality'] : 'inactive'); ?>"></div>
                                                <?php endfor; ?>
                                            </div>
                                            <span class="signal-value">(<?php echo e($signal); ?>)</span>
                                        </div>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </div>
                            <?php endif; ?>
                        </td>
                        <td><?php echo e($device->modem_model ?? 'Searching.. (auto)'); ?></td>
                        <td><?php echo e($device->last_update ? 'ON' : 'OFF'); ?></td>
                        <td><?php echo e($device->operator_errors ? 'Error' : 'Modem offline'); ?></td>
                    </tr>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </tbody>
        </table>
    </div>

    <div class="mt-2 mb-4">
        <p>Showing 1 to <?php echo e($data->count()); ?> of <?php echo e($data->count()); ?> entries</p>
    </div>

    <!-- Control Panel -->
    <div class="control-panel">
        <div class="control-section">
            <span class="control-label">AT Command</span>
            <input type="text" class="control-input" id="command-input" placeholder="Enter AT command e.g. AT;wait">
            <button class="control-btn" onclick="sendCommand()">Send AT Command</button>
        </div>

        <div class="control-section">
            <span class="control-label">Reset Modem</span>
            <button class="control-btn" onclick="resetModem()">Reset</button>
        </div>
        
        <div class="control-section">
            <span class="control-label">SIM on sale</span>
            <div class="toggle-group">
                <button class="toggle-btn" id="sim-on-btn" onclick="toggleSim('on')">ON</button>
                <button class="toggle-btn active" id="sim-off-btn" onclick="toggleSim('off')">OFF</button>
            </div>
        </div>
        
        <div class="qr-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <rect width="5" height="5" x="3" y="3" rx="1"/>
                <rect width="5" height="5" x="16" y="3" rx="1"/>
                <rect width="5" height="5" x="3" y="16" rx="1"/>
                <path d="m21 16-3.5-3.5-3.5 3.5"/>
                <path d="m21 21-3.5-3.5-3.5 3.5"/>
                <path d="M12 7h3a2 2 0 0 1 2 2v3"/>
                <path d="M8 21V8a2 2 0 0 1 2-2h2"/>
            </svg>
        </div>
    </div>

    <div id="selected-info" class="selected-info" style="display: none;">
        No device selected
    </div>

    <button class="btn" onclick="toggleRawJson()">Toggle Raw JSON Data</button>
    <pre id="raw-json" class="raw-json-container" style="display:none;"></pre>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const tbody = document.getElementById('device-table-body');
    const rawJson = document.getElementById('raw-json');
    const infoParagraph = document.querySelector('.mt-2.mb-4 p');
    const selectedInfo = document.getElementById('selected-info');
    const modemId = <?php echo e(intval(request()->route('id') ?? 0)); ?>;
    
    const apiKey = <?php echo json_encode($modem->api_key, 15, 512) ?>;
    const equipmentUuid = <?php echo json_encode($modem->equipment_uuid, 15, 512) ?>;

    let selectedRow = null;
    let selectedDevice = null;

    // WebSocket setup
    const wsUrl = 'ws://ws.zedsms.com:801';
    let ws;

    function connectWebSocket() {
        ws = new WebSocket(wsUrl);

        ws.onopen = () => {
            console.log('WebSocket connected');
            ws.send(JSON.stringify({
                action: 'registerweb',
                apikey: apiKey,
                uuid: equipmentUuid
            }));
        };

        ws.onmessage = (event) => {
            console.log('Received from WebSocket:', event.data);
        };

        ws.onclose = () => {
            console.log('WebSocket disconnected. Reconnecting in 3 seconds...');
            setTimeout(connectWebSocket, 3000);
        };

        ws.onerror = (error) => {
            console.error('WebSocket error:', error);
            ws.close();
        };
    }

    connectWebSocket();

    function sendWebSocketPayload(payload) {
        if (ws && ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify(payload));
            console.log('Sent payload:', payload);
            alert('Command sent: ' + JSON.stringify(payload));
        } else {
            alert('WebSocket is not connected.');
        }
    }

    function getSignalInfo(signal) {
        signal = Number(signal);
        if (signal === 0 || signal === 99) return { bars: 0, quality: 'none' };
        if (signal >= 25) return { bars: 5, quality: 'excellent' };
        if (signal >= 19) return { bars: 4, quality: 'good' };
        if (signal >= 13) return { bars: 3, quality: 'fair' };
        if (signal >= 7) return { bars: 2, quality: 'poor' };
        if (signal >= 1) return { bars: 1, quality: 'very-poor' };
        return { bars: 0, quality: 'none' };
    }

    function createSignalBars(signal) {
        const { bars, quality } = getSignalInfo(signal);
        let barsHtml = '';
        for (let i = 1; i <= 5; i++) {
            barsHtml += `<div class="signal-bar bar-${i} ${i <= bars ? 'active ' + quality : 'inactive'}"></div>`;
        }
        return barsHtml;
    }

    function escapeHtml(text) {
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    function selectRow(row, device) {
        if (selectedRow) {
            selectedRow.classList.remove('selected');
        }
        selectedRow = row;
        selectedDevice = device;
        row.classList.add('selected');
        selectedInfo.style.display = 'block';
        selectedInfo.textContent = `Selected: ${device.port_name || 'N/A'} (Device ID: ${device.id || 'N/A'})`;
    }

    function buildRow(device, index) {
        let signalsRaw = [];
        try {
            signalsRaw = device.signal_quality ? JSON.parse(device.signal_quality) : [];
        } catch (e) {
            console.error("Invalid JSON in signal_quality for device", device, e);
        }

        const signalsInt = signalsRaw.filter(s => s > 0).sort((a,b) => a - b);

        let signalHtml = '';
        if (signalsInt.length === 0) {
            signalHtml = '<span class="no-signal">No signal data</span>';
        } else {
            signalHtml = signalsInt.map(signal => `
                <div class="signal-container">
                    <div class="signal-bars">${createSignalBars(signal)}</div>
                    <span class="signal-value">(${signal})</span>
                </div>
            `).join('');
        }

        return `
            <tr class="${device.operator_errors ? 'table-danger' : 'table-primary'}" data-device-id="${device.id || index}" data-port="${device.port_name || ''}">
                <td>${index + 1}</td>
                <td>${escapeHtml(device.port_name ?? 'N/A')}</td>
                <td>${escapeHtml(device.sim_iccid ?? '0')}</td>
                <td>${escapeHtml(device.subscriber_imsi ?? '0')}</td>
                <td>unknown</td>
                <td>${escapeHtml(device.network_operator ?? '')}</td>
                <td>${device.sim_pin_status == 1 ? 'OK' : 'ERROR'}</td>
                <td><div class="d-flex flex-wrap gap-3">${signalHtml}</div></td>
                <td>${escapeHtml(device.modem_model ?? 'Searching.. (auto)')}</td>
                <td>${device.last_update ? 'ON' : 'OFF'}</td>
                <td>${device.operator_errors ? 'Error' : 'Modem offline'}</td>
            </tr>
        `;
    }

    function attachRowClickHandlers(devices) {
        const rows = tbody.querySelectorAll('tr');
        rows.forEach((row, index) => {
            row.addEventListener('click', function() {
                selectRow(row, devices[index]);
            });
        });
    }

    async function fetchDataAndUpdate() {
        if (!modemId) return;

        try {
            const response = await fetch(`/equipment/json/${modemId}`);
            if (!response.ok) throw new Error('Network response was not ok');
            const devices = await response.json();

            const rowsHtml = devices.map((device, idx) => buildRow(device, idx)).join('');
            tbody.innerHTML = rowsHtml;

            attachRowClickHandlers(devices);

            rawJson.textContent = JSON.stringify(devices, null, 2);

            if (infoParagraph) {
                infoParagraph.textContent = `Showing 1 to ${devices.length} of ${devices.length} entries`;
            }
        } catch (err) {
            console.error('Failed to fetch devices data:', err);
        }
    }

    // Initial setup
    const initialDevices = <?php echo json_encode($data, 15, 512) ?>;
    attachRowClickHandlers(initialDevices);

    fetchDataAndUpdate();
setInterval(fetchDataAndUpdate, 3000);


    window.toggleRawJson = function() {
        if (rawJson.style.display === 'none') {
            rawJson.style.display = 'block';
        } else {
            rawJson.style.display = 'none';
        }
    };

    // Send AT command via WebSocket
    window.sendCommand = function() {
        if (!selectedDevice) {
            alert('Please select a device first');
            return;
        }
        const atCommand = document.getElementById('command-input').value.trim();
        if (!atCommand) {
            alert('Please enter an AT command');
            return;
        }

        const payload = {
            action: 'send',
            at: atCommand,
            tty: selectedDevice.port_name,
            apikey: apiKey,
            uuid: equipmentUuid
        };

        sendWebSocketPayload(payload);
        document.getElementById('command-input').value = '';
    };

    // Send Reset command via WebSocket
    window.resetModem = function() {
        if (!selectedDevice) {
            alert('Please select a device first');
            return;
        }

        const payload = {
            action: 'reset',
            tty: selectedDevice.port_name,
            apikey: apiKey,
            uuid: equipmentUuid
        };

        sendWebSocketPayload(payload);
    };

    window.rebootModem = function() {
        if (!selectedDevice) {
            alert('Please select a device first');
            return;
        }

        if (confirm(`Are you sure you want to reboot modem ${selectedDevice.port_name}?`)) {
            console.log(`Rebooting modem ${selectedDevice.port_name}`);
            alert(`Rebooting modem ${selectedDevice.port_name}`);
            // Implement reboot logic here if needed
        }
    };

    window.toggleSim = function(state) {
        const onBtn = document.getElementById('sim-on-btn');
        const offBtn = document.getElementById('sim-off-btn');

        if (state === 'on') {
            onBtn.classList.add('active');
            offBtn.classList.remove('active');
        } else {
            offBtn.classList.add('active');
            onBtn.classList.remove('active');
        }

        if (!selectedDevice) {
            alert('Please select a device first');
            return;
        }

        console.log(`Setting SIM ${state} for device ${selectedDevice.port_name}`);
        alert(`SIM set to ${state.toUpperCase()} for ${selectedDevice.port_name}`);
        // Implement SIM toggle logic here if needed
    };
});
</script>

<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\zedsmsapi\api\resources\views/equipment_detail.blade.php ENDPATH**/ ?>