<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Device Details - GO-ACS</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/static/css/style.css">
    <style>
        .tabs {
            margin-bottom: 2rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            gap: 1rem;
            overflow-x: auto;
            padding-bottom: 2px;
        }

        .tab {
            padding: 12px 24px;
            cursor: pointer;
            color: var(--gray);
            font-weight: 500;
            white-space: nowrap;
            border-bottom: 2px solid transparent;
            transition: all 0.2s;
            background: none;
            border-top: none;
            border-left: none;
            border-right: none;
        }

        .tab:hover {
            color: var(--light);
        }

        .tab.active {
            color: var(--primary);
            border-bottom-color: var(--primary);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .card-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .info-card {
            background: var(--dark-card);
            border-radius: 12px;
            padding: 1.5rem;
            border: 1px solid rgba(255, 255, 255, 0.05);
        }

        .info-card h3 {
            margin-bottom: 1.25rem;
            font-size: 1.1rem;
            display: flex;
            align-items: center;
            gap: 10px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
            padding-bottom: 10px;
        }

        .info-rows {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
        }

        .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            background: rgba(255, 255, 255, 0.02);
            border-radius: 8px;
        }

        .info-row span:first-child {
            color: var(--gray);
            font-size: 0.9rem;
        }

        .info-row span:last-child {
            font-weight: 500;
            color: var(--light);
        }

        .status-online {
            color: #10b981;
        }

        .status-offline {
            color: #ef4444;
        }

        .vendor-badge {
            font-size: 0.7rem;
            padding: 2px 8px;
            border-radius: 4px;
            background: var(--primary);
            color: white;
            text-transform: uppercase;
            font-weight: 700;
        }

        .wan-table,
        .wlan-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }

        .wan-table th,
        .wlan-table th {
            text-align: left;
            padding: 12px;
            background: rgba(255, 255, 255, 0.05);
            color: var(--gray);
            font-size: 0.8rem;
            text-transform: uppercase;
        }

        .wan-table td,
        .wlan-table td {
            padding: 12px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
            font-size: 0.9rem;
        }

        .val-enabled {
            color: #10b981;
            font-weight: bold;
        }

        .val-disabled {
            color: #ef4444;
        }
    </style>
    <!-- Sidebar loaded via sidebar.js -->
    <script src="/static/js/sidebar.js"></script>
</head>

<body>
    <!-- Sidebar will be injected automatically by sidebar.js -->

    <main class="main-content">
        <div class="header">
            <div>
                <a href="/devices" class="back-link"><i class="fas fa-arrow-left"></i> Back to Devices</a>
                <h1 id="deviceTitle">Device Details</h1>
            </div>
            <div class="header-actions">
                <button class="btn btn-secondary" onclick="refreshDevice()"><i class="fas fa-sync"></i> Summon</button>
                <button class="btn btn-warning" onclick="rebootDevice()"><i class="fas fa-power-off"></i>
                    Reboot</button>
            </div>
        </div>

        <div class="tabs">
            <button class="tab active" onclick="showTab('summary', this)">Summary</button>
            <button class="tab" onclick="showTab('wan', this)">WAN</button>
            <button class="tab" onclick="showTab('lan', this)">LAN</button>
            <button class="tab" onclick="showTab('wlan', this)">WLAN</button>
            <button class="tab" onclick="showTab('user', this)">USER</button>
            <button class="tab" onclick="showTab('tr069', this)">TR-069</button>
            <button class="tab" onclick="showTab('params', this)">All Parameters</button>
            <button class="tab" onclick="showTab('logs', this)">History</button>
        </div>

        <!-- Summary Tab -->
        <div id="summary" class="tab-content active">
            <div class="card-grid">
                <div class="info-card">
                    <h3><i class="fas fa-info-circle"></i> Basic Information</h3>
                    <div class="info-rows" id="summaryInfo"></div>
                </div>
                <div class="info-card">
                    <h3><i class="fas fa-signal"></i> Optical Info (PON)</h3>
                    <div class="info-rows" id="ponInfo"></div>
                </div>
            </div>
        </div>

        <!-- WAN Tab -->
        <div id="wan" class="tab-content">
            <div id="wanContainer"></div>
        </div>

        <!-- LAN Tab -->
        <div id="lan" class="tab-content">
            <div class="card-grid">
                <div class="info-card">
                    <h3><i class="fas fa-network-wired"></i> LAN Status</h3>
                    <div class="info-rows" id="lanInfo"></div>
                </div>
                <div class="info-card">
                    <h3><i class="fas fa-laptop"></i> Connected Hosts</h3>
                    <div id="lanHosts"></div>
                </div>
            </div>
        </div>

        <!-- WLAN Tab -->
        <div id="wlan" class="tab-content">
            <!-- WiFi Configuration Form -->
            <div class="info-card" style="margin-bottom: 1rem;">
                <h3><i class="fas fa-edit"></i> Edit WiFi Configuration</h3>
                <div style="display: grid; gap: 1rem; margin-top: 1rem;">
                    <!-- SSID Edit -->
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <label style="min-width: 100px; color: var(--gray);">SSID:</label>
                        <input type="text" id="editSSID" placeholder="Enter new SSID"
                            style="flex: 1; padding: 10px; border-radius: 8px; border: 1px solid var(--border); background: var(--card); color: var(--light);">
                        <button class="btn btn-primary" onclick="saveSSID()" style="white-space: nowrap;"><i
                                class="fas fa-save"></i> Save SSID</button>
                    </div>
                    <!-- Password Edit -->
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <label style="min-width: 100px; color: var(--gray);">Password:</label>
                        <input type="text" id="editPassword" placeholder="Enter new password"
                            style="flex: 1; padding: 10px; border-radius: 8px; border: 1px solid var(--border); background: var(--card); color: var(--light);">
                        <button class="btn btn-primary" onclick="savePassword()" style="white-space: nowrap;"><i
                                class="fas fa-save"></i> Save Password</button>
                    </div>
                </div>
                <p style="color: var(--gray); font-size: 0.8rem; margin-top: 10px;"><i class="fas fa-info-circle"></i>
                    Changes will be queued and applied when the device connects next.</p>
            </div>

            <!-- Current WiFi Status -->
            <div id="wlanContainer"></div>
        </div>

        <!-- USER Tab -->
        <div id="user" class="tab-content">
            <div class="info-card">
                <h3><i class="fas fa-user-shield"></i> Management Accounts</h3>
                <div class="info-rows" id="userInfo"></div>
            </div>
        </div>

        <!-- TR069 Tab -->
        <div id="tr069" class="tab-content">
            <div class="info-card">
                <h3><i class="fas fa-server"></i> CWMP Settings</h3>
                <div class="info-rows" id="tr069Info"></div>
            </div>
        </div>

        <!-- Params Tab -->
        <div id="params" class="tab-content">
            <div class="info-card">
                <h3><i class="fas fa-list"></i> Full Parameter List</h3>
                <div id="paramsList" class="params-list"></div>
            </div>
        </div>

        <!-- History Tab -->
        <div id="logs" class="tab-content">
            <div class="info-card">
                <h3><i class="fas fa-history"></i> Log History</h3>
                <div id="logsList"></div>
            </div>
        </div>
    </main>

    <script>
        let device = null;
        const deviceId = window.location.pathname.split('/').pop();

        function showTab(tabId, el) {
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

            if (el) {
                el.classList.add('active');
            } else {
                // Find tab button by onclick
                const tabs = document.querySelectorAll('.tab');
                for (let t of tabs) {
                    if (t.getAttribute('onclick')?.includes(tabId)) {
                        t.classList.add('active');
                        break;
                    }
                }
            }

            const content = document.getElementById(tabId);
            if (content) content.classList.add('active');

            // Re-load data for specific tabs if needed
            if (tabId === 'wan') loadWan();
            if (tabId === 'wlan') loadWlan();
            if (tabId === 'lan') loadLan();
            if (tabId === 'user') loadUser();
            if (tabId === 'tr069') loadTR069();
            if (tabId === 'params') loadAllParams();
        }

        async function fetchDevice() {
            try {
                const res = await fetch(`/api/devices/${deviceId}`);
                if (!res.ok) throw new Error('Failed to fetch device');
                device = await res.json();
                renderSummary();
                loadPon();
            } catch (err) {
                console.error(err);
                document.getElementById('summaryInfo').innerHTML = `<div class="error">Error loading device data: ${err.message}</div>`;
            }
        }

        async function refreshDevice() {
            const res = await fetch(`/api/devices/${deviceId}/refresh`, { method: 'POST' });
            if (res.ok) {
                alert('Refresh command queued successfully');
                location.reload();
            }
        }

        async function rebootDevice() {
            if (!confirm('Are you sure you want to reboot this device?')) return;
            const res = await fetch(`/api/devices/${deviceId}/reboot`, { method: 'POST' });
            if (res.ok) alert('Reboot command queued');
        }

        async function factoryResetDevice() {
            if (!confirm('WARNING: Factory reset will erase all settings. Continue?')) return;
            const res = await fetch(`/api/devices/${deviceId}/factory-reset`, { method: 'POST' });
            if (res.ok) alert('Factory reset command queued');
        }

        async function loadAllParams() {
            const res = await fetch(`/api/devices/${deviceId}/parameters`);
            const params = await res.json();
            const list = document.getElementById('paramsList');
            list.innerHTML = params.map(p => `
                <div class="info-row" style="justify-content: flex-start; gap: 20px;">
                    <code style="color:var(--primary); font-size:0.8rem; min-width: 300px;">${p.path}</code>
                    <span style="color:var(--light); font-weight:bold;">${p.value}</span>
                </div>
            `).join('');
        }

        async function loadLan() {
            const res = await fetch(`/api/devices/${deviceId}/clients`);
            const data = await res.json();
            const hosts = document.getElementById('lanHosts');

            if (data.clients && data.clients.length > 0) {
                hosts.innerHTML = data.clients.map(c => `
                    <div class="info-row">
                        <span>${c.name} (${c.ip})</span>
                        <span>${c.mac}</span>
                    </div>
                `).join('');
            } else {
                hosts.innerHTML = '<div class="empty-state">No connected hosts detected</div>';
            }
        }

        function renderSummary() {
            document.getElementById('deviceTitle').textContent = `${device.manufacturer} ${device.modelName || ''}`;
            const info = document.getElementById('summaryInfo');
            info.innerHTML = `
                <div class="info-row"><span>Status</span><span class="status-${device.status}">${device.status.toUpperCase()}</span></div>
                <div class="info-row"><span>Serial Number</span><span>${device.serialNumber}</span></div>
                <div class="info-row"><span>Product Class</span><span>${device.productClass || 'N/A'}</span></div>
                <div class="info-row"><span>OUI</span><span>${device.oui || 'N/A'}</span></div>
                <div class="info-row"><span>Manufacturer</span><span>${device.manufacturer || 'N/A'}</span></div>
                <div class="info-row"><span>Hardware Version</span><span>${device.hardwareVersion || 'N/A'}</span></div>
                <div class="info-row"><span>Software Version</span><span>${device.softwareVersion || 'N/A'}</span></div>
                <div class="info-row"><span>PPPoE User</span><span style="color:var(--primary);">${device.template || 'N/A'}</span></div>
                <div class="info-row"><span>WAN IP</span><span>${device.ipAddress || 'N/A'}</span></div>
                <div class="info-row"><span>Uptime</span><span>${formatUptime(device.uptime)}</span></div>
            `;
        }

        async function loadPon() {
            const res = await fetch(`/api/devices/${deviceId}/pon`);
            const pon = await res.json();
            const info = document.getElementById('ponInfo');
            info.innerHTML = `
                <div class="info-row"><span>PON Mode</span><span class="vendor-badge">${pon.ponMode || 'N/A'}</span></div>
                <div class="info-row"><span>RX Power</span><span style="color:${pon.rxPower > -25 ? '#10b981' : '#ef4444'}">${pon.rxPower ? pon.rxPower.toFixed(2) : '--'} dBm</span></div>
                <div class="info-row"><span>TX Power</span><span>${pon.txPower ? pon.txPower.toFixed(2) : '--'} dBm</span></div>
                <div class="info-row"><span>Temperature</span><span>${pon.temperature ? pon.temperature.toFixed(1) : '--'} °C</span></div>
                <div class="info-row"><span>Voltage</span><span>${pon.voltage ? pon.voltage.toFixed(2) : '--'} V</span></div>
                <div class="info-row"><span>Bias Current</span><span>${pon.biasCurrent ? pon.biasCurrent.toFixed(1) : '--'} mA</span></div>
            `;
        }

        // --- WAN TAB (Logic based on your Blueprint) ---
        async function loadWan() {
            const container = document.getElementById('wanContainer');

            if (!device || !device.manufacturer) {
                container.innerHTML = '<div class="empty-state">Device data not loaded yet</div>';
                return;
            }

            try {
                const res = await fetch(`/api/devices/${deviceId}/parameters`);
                const params = await res.json();

                if (!params || !Array.isArray(params) || params.length === 0) {
                    container.innerHTML = '<div class="empty-state">No parameters found. Click "Summon" to fetch data from device.</div>';
                    return;
                }

                let html = '';

                // Huawei Template (Support multiple WANs)
                if (device.manufacturer.includes('Huawei')) {
                    const wanInstances = params.filter(p => p.path.includes('WANPPPConnection.') && p.path.endsWith('.Username'));
                    wanInstances.forEach((p, idx) => {
                        const prefix = p.path.split('.Username')[0] + '.';
                        html += renderWanTable(`WAN PPPoE #${idx + 1}`, params, prefix, [
                            { label: 'Enable', path: 'Enable' },
                            { label: 'Name', path: 'Name' },
                            { label: 'VLAN', path: 'X_HW_VLAN' },
                            { label: 'User', path: 'Username' },
                            { label: 'Pass', path: 'Password' },
                            { label: 'Status', path: 'ConnectionStatus' }
                        ]);
                    });
                }
                // ZTE Template
                else if (device.manufacturer.includes('ZTE')) {
                    const wanInstances = params.filter(p => p.path.includes('WANPPPConnection.') && p.path.endsWith('.Username'));
                    wanInstances.forEach((p, idx) => {
                        const prefix = p.path.split('.Username')[0] + '.';
                        html += renderWanTable(`ZTE WAN PPPoE #${idx + 1}`, params, prefix, [
                            { label: 'Enable', path: 'Enable' },
                            { label: 'Name', path: 'Name' },
                            { label: 'VLAN', path: 'X_ZTE-COM_VLANID' },
                            { label: 'User', path: 'Username' },
                            { label: 'Status', path: 'ConnectionStatus' }
                        ]);
                    });
                }
                // FiberHome
                else if (device.manufacturer.includes('FiberHome')) {
                    const wanInstances = params.filter(p => p.path.includes('WANPPPConnection.') && p.path.endsWith('.Username'));
                    wanInstances.forEach((p, idx) => {
                        const prefix = p.path.split('.Username')[0] + '.';
                        html += renderWanTable(`FH WAN PPPoE #${idx + 1}`, params, prefix, [
                            { label: 'Enable', path: 'Enable' },
                            { label: 'VLAN', path: 'VLANID' },
                            { label: 'User', path: 'Username' },
                            { label: 'Status', path: 'ConnectionStatus' }
                        ]);
                    });
                }
                // Default fallback if no vendor match but has PPP
                if (!html) {
                    const wanInstances = params.filter(p => p.path.includes('WANPPPConnection.') && p.path.endsWith('.Username'));
                    wanInstances.forEach((p, idx) => {
                        const prefix = p.path.split('.Username')[0] + '.';
                        html += renderWanTable(`WAN PPPoE #${idx + 1}`, params, prefix, [
                            { label: 'User', path: 'Username' },
                            { label: 'Status', path: 'ConnectionStatus' }
                        ]);
                    });
                }

                container.innerHTML = html || '<div class="empty-state">No WAN data found. Click "Summon" to fetch data from device.</div>';
            } catch (err) {
                console.error('Error loading WAN:', err);
                container.innerHTML = '<div class="empty-state">Error loading WAN data</div>';
            }
        }

        function renderWanTable(title, params, prefix, fields) {
            let rows = fields.map(f => {
                const val = params.find(p => p.path === prefix + f.path)?.value || 'N/A';
                return `<div class="info-row"><span>${f.label}</span><span>${val}</span></div>`;
            }).join('');

            return `
                <div class="info-card" style="margin-bottom:1rem;">
                    <h3><i class="fas fa-globe"></i> ${title}</h3>
                    <div class="info-rows">${rows}</div>
                </div>
            `;
        }

        // --- WLAN TAB ---
        async function loadWlan() {
            const container = document.getElementById('wlanContainer');

            if (!device) {
                container.innerHTML = '<div class="empty-state">Device data not loaded yet</div>';
                return;
            }

            try {
                const res = await fetch(`/api/devices/${deviceId}/parameters`);
                const params = await res.json();

                if (!params || !Array.isArray(params) || params.length === 0) {
                    container.innerHTML = '<div class="empty-state">No parameters found. Click "Summon" to fetch data from device.</div>';
                    return;
                }

                let html = '';
                // Basic SSID Search - Search for all .SSID parameters
                const ssids = params.filter(p => (p.path.includes('WLANConfiguration') || p.path.includes('WiFi.SSID.')) && p.path.endsWith('.SSID'));

                ssids.forEach((s, i) => {
                    const prefix = s.path.split('.SSID')[0] + '.';
                    const pwd = params.find(p => p.path.startsWith(prefix) && (p.path.endsWith('KeyPassphrase') || p.path.endsWith('PreSharedKey.1.KeyPassphrase') || p.path.endsWith('Key')))?.value || '****';
                    const enable = params.find(p => p.path === prefix + 'Enable')?.value;
                    const channel = params.find(p => p.path === prefix + 'Channel')?.value || 'Auto';

                    html += `
                        <div class="info-card" style="margin-bottom:1rem;">
                            <h3><i class="fas fa-wifi"></i> WiFi SSID: ${s.value}</h3>
                            <div class="info-rows">
                                <div class="info-row"><span>Status</span><span class="${enable == '1' || enable == 'true' ? 'val-enabled' : 'val-disabled'}">${enable == '1' || enable == 'true' ? 'ENABLED' : 'DISABLED'}</span></div>
                                <div class="info-row"><span>Channel</span><span>${channel}</span></div>
                                <div class="info-row"><span>Password</span><span style="color:var(--primary); font-family: monospace;">${pwd}</span></div>
                                <div class="info-row"><span>Full Path</span><small style="color:var(--gray); font-size:0.7rem;">${prefix}</small></div>
                            </div>
                        </div>
                    `;
                });

                container.innerHTML = html || '<div class="empty-state">No WiFi configured. Click "Summon" to fetch data from device.</div>';
            } catch (err) {
                console.error('Error loading WLAN:', err);
                container.innerHTML = '<div class="empty-state">Error loading WiFi data</div>';
            }
        }

        // --- USER TAB (Account Management) ---
        async function loadUser() {
            const info = document.getElementById('userInfo');

            try {
                const res = await fetch(`/api/devices/${deviceId}/parameters`);
                const params = await res.json();

                if (!params || !Array.isArray(params)) {
                    info.innerHTML = '<div class="empty-state">No parameters found</div>';
                    return;
                }

                let html = '';
                // Search for WebUserInfo Or SuperUser
                const accounts = params.filter(p => p.path.includes('WebUserInfo') || p.path.includes('Account.UserName') || p.path.includes('ConfigUserName'));

                if (accounts.length > 0) {
                    accounts.forEach(a => {
                        const prefix = a.path.split('.').slice(0, -1).join('.') + '.';
                        const pwd = params.find(p => p.path === prefix + 'Password' || p.path === prefix + 'AdminPassword' || p.path === prefix + 'UserPassword' || p.path === prefix + 'ConfigPassword')?.value || '****';
                        html += `
                            <div class="info-row"><span>Username (${a.path.split('.').pop()})</span><span>${a.value}</span></div>
                            <div class="info-row"><span>Password</span><span style="color:var(--primary);">${pwd}</span></div>
                        `;
                    });
                }

                info.innerHTML = html || '<div class="empty-state">No credentials found</div>';
            } catch (err) {
                console.error('Error loading USER:', err);
                info.innerHTML = '<div class="empty-state">Error loading user data</div>';
            }
        }

        // --- TR069 TAB (CWMP) ---
        async function loadTR069() {
            const info = document.getElementById('tr069Info');

            try {
                const res = await fetch(`/api/devices/${deviceId}/parameters`);
                const params = await res.json();

                if (!params || !Array.isArray(params)) {
                    info.innerHTML = '<div class="empty-state">No parameters found</div>';
                    return;
                }

                const paramsArr = params;
                const paths = [
                    { label: 'ACS URL', path: 'InternetGatewayDevice.ManagementServer.URL' },
                    { label: 'Inform Enable', path: 'InternetGatewayDevice.ManagementServer.PeriodicInformEnable' },
                    { label: 'Inform Interval', path: 'InternetGatewayDevice.ManagementServer.PeriodicInformInterval' },
                    { label: 'Connection Request User', path: 'InternetGatewayDevice.ManagementServer.ConnectionRequestUsername' }
                ];

                let html = paths.map(f => {
                    const val = paramsArr.find(p => p.path === f.path || p.path === 'Device.ManagementServer.' + f.label)?.value || 'N/A';
                    return `<div class="info-row"><span>${f.label}</span><span>${val}</span></div>`;
                }).join('');

                info.innerHTML = html;
            } catch (err) {
                console.error('Error loading TR069:', err);
                info.innerHTML = '<div class="empty-state">Error loading TR-069 data</div>';
            }
        }

        function formatUptime(s) {
            if (!s) return '0d 0h 0m';
            const d = Math.floor(s / 86400);
            const h = Math.floor((s % 86400) / 3600);
            const m = Math.floor((s % 3600) / 60);
            return `${d}d ${h}h ${m}m`;
        }

        // Save SSID function
        async function saveSSID() {
            const ssid = document.getElementById('editSSID').value.trim();
            if (!ssid) {
                alert('Please enter a new SSID');
                return;
            }

            try {
                const res = await fetch(`/api/devices/${deviceId}/wifi/ssid`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ ssid: ssid })
                });

                if (res.ok) {
                    alert('SSID change queued successfully! The device will apply this on next connection.');
                    document.getElementById('editSSID').value = '';
                    loadWlan(); // Refresh the list
                } else {
                    const err = await res.json();
                    alert('Error: ' + (err.error || 'Failed to save SSID'));
                }
            } catch (err) {
                console.error('Error saving SSID:', err);
                alert('Error saving SSID: ' + err.message);
            }
        }

        // Save Password function
        async function savePassword() {
            const password = document.getElementById('editPassword').value.trim();
            if (!password) {
                alert('Please enter a new password');
                return;
            }

            if (password.length < 8) {
                alert('Password must be at least 8 characters');
                return;
            }

            try {
                const res = await fetch(`/api/devices/${deviceId}/wifi/password`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ password: password })
                });

                if (res.ok) {
                    alert('WiFi password change queued successfully! The device will apply this on next connection.');
                    document.getElementById('editPassword').value = '';
                    loadWlan(); // Refresh the list
                } else {
                    const err = await res.json();
                    alert('Error: ' + (err.error || 'Failed to save password'));
                }
            } catch (err) {
                console.error('Error saving password:', err);
                alert('Error saving password: ' + err.message);
            }
        }

        fetchDevice();
    </script>
</body>

</html>