// ============================================================
// FORTIGATE DASHBOARD - MAIN JAVASCRIPT
// ============================================================

const API_BASE = 'api/fortigate.php';
const REFRESH_INTERVAL = 15000; // 15 seconds

let trafficChart = null;
let updateTimer = null;

// ============================================================
// DOM Ready
// ============================================================
document.addEventListener('DOMContentLoaded', function() {
    initSidebar();
    initClock();
    initRefreshButton();
    initLogTypeSelector();
    initInterfaceSelector();
    initTrafficChart();
    loadAllData();
    startAutoRefresh();
});

// ============================================================
// Sidebar Navigation
// ============================================================
function initSidebar() {
    const navItems = document.querySelectorAll('.nav-item');
    const pageTitle = document.getElementById('pageTitle');
    const titles = {
        overview: 'Overview Dashboard',
        network: 'Network Monitor',
        security: 'Security Dashboard',
        vpn: 'VPN Status',
        logs: 'Log Viewer',
        admin: 'Admin Controls',
        chat: 'AI Chat Assistant'
    };
    const icons = {
        overview: 'fa-chart-pie',
        network: 'fa-network-wired',
        security: 'fa-shield-alt',
        vpn: 'fa-lock',
        logs: 'fa-list',
        admin: 'fa-user-cog',
        chat: 'fa-robot'
    };
    
    navItems.forEach(item => {
        item.addEventListener('click', function(e) {
            const tab = this.dataset.tab;
            
            // Handle chat tab separately (floating widget)
            if (tab === 'chat') {
                toggleChat();
                e.preventDefault();
                return;
            }
            
            e.preventDefault();
            
            navItems.forEach(n => n.classList.remove('active'));
            this.classList.add('active');
            
            document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
            const target = document.getElementById('tab-' + tab);
            if (target) target.classList.add('active');
            
            pageTitle.innerHTML = `<i class="fas ${icons[tab]}"></i> ${titles[tab]}`;
            loadTabData(tab);
        });
    });
}

// ============================================================
// Clock
// ============================================================
function initClock() {
    function updateClock() {
        const now = new Date();
        document.getElementById('clockDisplay').textContent = 
            now.toLocaleString('en-MY', { 
                day: '2-digit', month: 'short', year: 'numeric',
                hour: '2-digit', minute: '2-digit', second: '2-digit',
                hour12: false
            });
    }
    updateClock();
    setInterval(updateClock, 1000);
}

// ============================================================
// Refresh Button
// ============================================================
function initRefreshButton() {
    document.getElementById('refreshBtn').addEventListener('click', function() {
        const icon = this.querySelector('i');
        icon.classList.add('fa-spin');
        loadAllData().finally(() => {
            icon.classList.remove('fa-spin');
        });
    });
}

// ============================================================
// Auto Refresh
// ============================================================
function startAutoRefresh() {
    if (updateTimer) clearInterval(updateTimer);
    updateTimer = setInterval(() => {
        const activeTab = document.querySelector('.nav-item.active');
        if (activeTab) {
            const tab = activeTab.dataset.tab;
            if (tab !== 'chat') {
                loadTabData(tab);
            }
        }
    }, REFRESH_INTERVAL);
}

// ============================================================
// API Calls
// ============================================================
async function apiCall(action, params = {}) {
    const url = new URL(API_BASE, window.location.href);
    url.searchParams.append('action', action);
    Object.keys(params).forEach(key => {
        url.searchParams.append(key, params[key]);
    });
    
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        return await response.json();
    } catch (error) {
        console.error('API Error:', error);
        return { error: error.message };
    }
}

// ============================================================
// Load All Data
// ============================================================
async function loadAllData() {
    await Promise.allSettled([
        loadHealthData(),
        loadInterfaces(),
        loadDhcpData(),
        loadHaStatus(),
        loadAdminUsers(),
        loadDnsConfig()
    ]);
}

// ============================================================
// Health / KPI Data
// ============================================================
async function loadHealthData() {
    const data = await apiCall('health');
    
    if (data.error) {
        console.warn('Health data error:', data.error);
        return;
    }
    
    updateKPI('cpuUsage', (data.cpu || 0) + '%', data.cpu || 0, 'cpuBar');
    updateKPI('memoryUsage', (data.memory || 0) + '%', data.memory || 0, 'memoryBar');
    updateKPI('diskUsage', (data.disk || 0) + '%', data.disk || 0, 'diskBar');
    updateKPI('sessionCount', data.sessions || 0, Math.min((data.sessions || 0) / 1000 * 100, 100), 'sessionBar');
    
    if (data.interfaces) {
        updateWanStatus(data.interfaces);
    }
    
    document.getElementById('lastUpdate').textContent = 
        new Date().toLocaleTimeString('en-MY', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
}

function updateKPI(elementId, displayValue, rawValue, barId) {
    document.getElementById(elementId).textContent = displayValue;
    const bar = document.getElementById(barId);
    if (bar) {
        const percent = Math.min(rawValue, 100);
        bar.style.width = percent + '%';
        bar.className = 'progress-bar';
        if (percent > 80) bar.classList.add('danger');
        else if (percent > 60) bar.classList.add('warning');
    }
}

function updateWanStatus(interfaces) {
    const wanMap = {
        'wan1': 'wan1Status',
        'wan2': 'wan2Status',
        'port2': 'wan3Status'
    };
    
    Object.keys(wanMap).forEach(name => {
        const el = document.getElementById(wanMap[name]);
        if (el && interfaces[name]) {
            const status = interfaces[name].status;
            el.textContent = status === 'up' ? '🟢 Online' : '🔴 Offline';
            el.style.color = status === 'up' ? 'var(--success)' : 'var(--danger)';
        }
    });
}

// ============================================================
// Interface Data
// ============================================================
async function loadInterfaces() {
    const data = await apiCall('interfaces');
    
    if (data.error) {
        console.warn('Interface data error:', data.error);
        return;
    }
    
    const interfaces = data.results || [];
    
    // Interface list in overview
    const container = document.getElementById('interfaceList');
    if (container) {
        if (interfaces.length === 0) {
            container.innerHTML = '<div class="loading">No interfaces found</div>';
            return;
        }
        container.innerHTML = interfaces.map(iface => `
            <div class="interface-item">
                <span class="interface-name">
                    <i class="fas ${getInterfaceIcon(iface)}"></i>
                    ${iface.alias || iface.name}
                </span>
                <span class="interface-ip">${iface.ip || '--'}</span>
                <span class="status-badge ${iface.status === 'up' ? 'up' : 'down'}">
                    <span class="status-dot-sm ${iface.status === 'up' ? 'up' : 'down'}"></span>
                    ${iface.status}
                </span>
            </div>
        `).join('');
    }
    
    // Interface table in network tab
    const tableContainer = document.getElementById('interfaceTable');
    if (tableContainer) {
        if (interfaces.length === 0) {
            tableContainer.innerHTML = '<div class="loading">No interfaces found</div>';
            return;
        }
        tableContainer.innerHTML = `
            <table>
                <thead>
                    <tr>
                        <th>Interface</th>
                        <th>Alias</th>
                        <th>IP Address</th>
                        <th>Mode</th>
                        <th>Role</th>
                        <th>Status</th>
                        <th>Access</th>
                    </tr>
                </thead>
                <tbody>
                    ${interfaces.map(iface => `
                        <tr>
                            <td><strong>${iface.name}</strong></td>
                            <td>${iface.alias || '-'}</td>
                            <td><code>${iface.ip || '0.0.0.0/0'}</code></td>
                            <td>${iface.mode || 'static'}</td>
                            <td>${iface.role || 'undefined'}</td>
                            <td><span class="status-badge ${iface.status === 'up' ? 'up' : 'down'}">
                                <span class="status-dot-sm ${iface.status === 'up' ? 'up' : 'down'}"></span>
                                ${iface.status}
                            </span></td>
                            <td>${iface.allowaccess || '-'}</td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        `;
    }
    
    // Populate interface selector
    const selector = document.getElementById('trafficInterface');
    if (selector) {
        const currentVal = selector.value;
        selector.innerHTML = `
            <option value="all">All Interfaces</option>
            ${interfaces.map(iface => 
                `<option value="${iface.name}">${iface.alias || iface.name}</option>`
            ).join('')}
        `;
        if (currentVal) selector.value = currentVal;
    }
}

function getInterfaceIcon(iface) {
    const name = iface.name;
    if (name.startsWith('wan') || name === 'port2') return 'fa-globe';
    if (name === 'lan') return 'fa-building';
    if (name === 'dmz') return 'fa-desktop';
    if (name.includes('Wifi') || name.includes('wifi')) return 'fa-wifi';
    if (name === 'fortilink') return 'fa-link';
    if (name.startsWith('port')) return 'fa-plug';
    if (name.includes('tunnel') || name.includes('ssl.root')) return 'fa-lock';
    return 'fa-network-wired';
}

// ============================================================
// DHCP Data
// ============================================================
async function loadDhcpData() {
    const data = await apiCall('dhcp');
    
    if (data.error) {
        console.warn('DHCP data error:', data.error);
        return;
    }
    
    const container = document.getElementById('dhcpList');
    if (!container) return;
    
    const servers = data.results || [];
    if (servers.length === 0) {
        container.innerHTML = '<div class="loading">No DHCP servers configured</div>';
        return;
    }
    container.innerHTML = servers.map(server => `
        <div class="interface-item">
            <span class="interface-name">
                <i class="fas fa-server"></i>
                ${server.interface || 'unknown'}
            </span>
            <span class="interface-ip">${server.default_gateway || '-'}</span>
            <span class="status-badge ${server.status === 'enable' ? 'up' : 'down'}">
                ${server.status === 'enable' ? 'Active' : 'Disabled'}
            </span>
        </div>
    `).join('');
}

// ============================================================
// HA Status
// ============================================================
async function loadHaStatus() {
    const data = await apiCall('ha');
    
    if (data.error) {
        console.warn('HA data error:', data.error);
        return;
    }
    
    const container = document.getElementById('haStatus');
    if (!container) return;
    
    const ha = data.results || {};
    container.innerHTML = `
        <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 4px 0;">
            <div><strong>Mode:</strong> <span class="status-badge info">${ha.mode || 'standalone'}</span></div>
            <div><strong>Group ID:</strong> ${ha['group-id'] || 'N/A'}</div>
            <div><strong>Priority:</strong> ${ha.priority || 'N/A'}</div>
            <div><strong>Override:</strong> ${ha.override === 'enable' ? 'Enabled' : 'Disabled'}</div>
            <div style="grid-column: 1/-1;"><strong>Sync Config:</strong> ${ha['sync-config'] === 'enable' ? 'Enabled' : 'Disabled'}</div>
        </div>
    `;
}

// ============================================================
// Admin Users
// ============================================================
async function loadAdminUsers() {
    const data = await apiCall('admin');
    
    if (data.error) {
        console.warn('Admin data error:', data.error);
        return;
    }
    
    const container = document.getElementById('adminUserList');
    if (!container) return;
    
    const users = data.results || [];
    if (users.length === 0) {
        container.innerHTML = '<div class="loading">No admin users found</div>';
        return;
    }
    container.innerHTML = `
        <table>
            <thead>
                <tr>
                    <th>Username</th>
                    <th>Profile</th>
                    <th>VDOM</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                ${users.map(user => `
                    <tr>
                        <td><strong>${user.name}</strong></td>
                        <td>${user.accprofile || 'unknown'}</td>
                        <td>${user.vdom || 'root'}</td>
                        <td><span class="status-badge up">Active</span></td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
}

// ============================================================
// DNS Configuration
// ============================================================
async function loadDnsConfig() {
    const data = await apiCall('dns');
    
    if (data.error) {
        console.warn('DNS data error:', data.error);
        return;
    }
    
    const container = document.getElementById('dnsConfig');
    if (!container) return;
    
    const dns = data.results || {};
    container.innerHTML = `
        <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 8px 24px; padding: 4px 0;">
            <div><strong>Primary DNS:</strong> ${dns.primary || 'Not set'}</div>
            <div><strong>Secondary DNS:</strong> ${dns.secondary || 'Not set'}</div>
            <div><strong>Protocol:</strong> ${dns.protocol || 'cleartext'}</div>
            <div><strong>Interface:</strong> ${dns.interface || 'auto'}</div>
            <div style="grid-column: 1/-1;"><strong>Cache TTL:</strong> ${dns['dns-cache-ttl'] || 1800}s</div>
        </div>
    `;
}

// ============================================================
// Tab Data Loading
// ============================================================
async function loadTabData(tab) {
    switch (tab) {
        case 'overview':
            await loadHealthData();
            await loadInterfaces();
            await loadDhcpData();
            await loadHaStatus();
            break;
        case 'network':
            await loadInterfaces();
            break;
        case 'security':
            await loadSecurityData();
            break;
        case 'vpn':
            await loadVpnData();
            break;
        case 'logs':
            await loadLogs();
            break;
        case 'admin':
            await loadAdminUsers();
            await loadDnsConfig();
            break;
    }
}

// ============================================================
// Security Data
// ============================================================
async function loadSecurityData() {
    const ipsData = await apiCall('ips');
    const ipsContainer = document.getElementById('ipsList');
    if (ipsContainer && !ipsData.error) {
        if (Object.keys(ipsData).length === 0) {
            ipsContainer.innerHTML = '<div class="loading">No IPS sensors found</div>';
            return;
        }
        ipsContainer.innerHTML = Object.keys(ipsData).map(name => {
            const sensor = ipsData[name];
            const entries = sensor.entries || [];
            return `
                <div class="interface-item">
                    <span class="interface-name"><i class="fas fa-shield"></i> ${name}</span>
                    <span>${entries.length} rules</span>
                    <span class="status-badge info">Active</span>
                </div>
            `;
        }).join('');
    }
    
    const appData = await apiCall('appctrl', { name: 'APPCTRL-MRL' });
    const appContainer = document.getElementById('appControlList');
    if (appContainer && !appData.error) {
        const entries = appData.entries || [];
        if (entries.length === 0) {
            appContainer.innerHTML = '<div class="loading">No App Control entries</div>';
            return;
        }
        appContainer.innerHTML = entries.slice(0, 10).map(e => `
            <div class="interface-item">
                <span class="interface-name"><i class="fas fa-applications"></i> ${e.application || 'rule'}</span>
                <span class="status-badge ${e.action === 'block' ? 'danger' : 'up'}">
                    ${e.action || 'pass'}
                </span>
            </div>
        `).join('');
    }
    
    const urlData = await apiCall('webfilter', { id: 1 });
    const urlContainer = document.getElementById('urlFilterList');
    if (urlContainer && !urlData.error) {
        const entries = urlData.entries || [];
        if (entries.length === 0) {
            urlContainer.innerHTML = '<div class="loading">No URL Filter rules</div>';
            return;
        }
        urlContainer.innerHTML = `
            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>URL Pattern</th>
                        <th>Type</th>
                        <th>Action</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    ${entries.map((e, i) => `
                        <tr>
                            <td>${i + 1}</td>
                            <td><code>${e.url || '-'}</code></td>
                            <td>${e.type || 'wildcard'}</td>
                            <td><span class="status-badge danger">${e.action || 'block'}</span></td>
                            <td><span class="status-badge ${e.status === 'enable' ? 'up' : 'down'}">
                                ${e.status === 'enable' ? 'Active' : 'Disabled'}
                            </span></td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        `;
    }
}

// ============================================================
// VPN Data
// ============================================================
async function loadVpnData() {
    const data = await apiCall('vpn');
    
    if (data.error) {
        console.warn('VPN data error:', data.error);
        return;
    }
    
    const sslContainer = document.getElementById('sslVpnStatus');
    if (sslContainer) {
        const ssl = data.ssl || {};
        const portals = ssl.results || [];
        if (portals.length === 0) {
            sslContainer.innerHTML = '<div class="loading">No SSL VPN portals</div>';
        } else {
            sslContainer.innerHTML = portals.map(p => `
                <div class="interface-item">
                    <span class="interface-name">
                        <i class="fas fa-user-lock"></i> ${p.portal_name || 'default'}
                    </span>
                    <span class="status-badge up">Active</span>
                </div>
            `).join('');
        }
    }
    
    const ipsecContainer = document.getElementById('ipsecTunnels');
    if (ipsecContainer) {
        const ipsec = data.ipsec || {};
        const tunnels = ipsec.results || [];
        if (tunnels.length === 0) {
            ipsecContainer.innerHTML = '<div class="loading">No IPSec tunnels</div>';
        } else {
            ipsecContainer.innerHTML = tunnels.map(t => `
                <div class="interface-item">
                    <span class="interface-name">
                        <i class="fas fa-ipsec"></i> ${t.name || 'unnamed'}
                    </span>
                    <span class="interface-ip">${t.remote_gw || '-'}</span>
                    <span class="status-badge ${t.status === 'up' ? 'up' : 'down'}">
                        ${t.status || 'down'}
                    </span>
                </div>
            `).join('');
        }
    }
}

// ============================================================
// Logs
// ============================================================
async function loadLogs() {
    const type = document.getElementById('logType').value;
    const data = await apiCall('logs', { type: type, limit: 50 });
    
    if (data.error) {
        console.warn('Log data error:', data.error);
        return;
    }
    
    const container = document.getElementById('logTable');
    if (!container) return;
    
    const logs = data.results || [];
    if (logs.length === 0) {
        container.innerHTML = '<div class="loading">No logs found</div>';
        return;
    }
    container.innerHTML = `
        <table>
            <thead>
                <tr>
                    <th>Time</th>
                    <th>Source</th>
                    <th>Destination</th>
                    <th>Action</th>
                    <th>Message</th>
                </tr>
            </thead>
            <tbody>
                ${logs.map(log => `
                    <tr>
                        <td style="white-space:nowrap;font-size:11px;">${log.time || '-'}</td>
                        <td>${log.srcip || '-'}</td>
                        <td>${log.dstip || '-'}</td>
                        <td><span class="status-badge ${log.action === 'accept' || log.action === 'allow' ? 'up' : 'danger'}">
                            ${log.action || 'unknown'}
                        </span></td>
                        <td>${log.msg || log.message || '-'}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
}

// ============================================================
// Log Type Selector
// ============================================================
function initLogTypeSelector() {
    document.getElementById('logType').addEventListener('change', function() {
        loadLogs();
    });
}

// ============================================================
// Traffic Chart
// ============================================================
function initTrafficChart() {
    const ctx = document.getElementById('trafficChart').getContext('2d');
    
    trafficChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: generateTimeLabels(),
            datasets: [
                {
                    label: 'Inbound (Mbps)',
                    data: generateSampleData(),
                    borderColor: '#3b82f6',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    fill: true,
                    tension: 0.4,
                    pointRadius: 2
                },
                {
                    label: 'Outbound (Mbps)',
                    data: generateSampleData(0.6),
                    borderColor: '#22c55e',
                    backgroundColor: 'rgba(34, 197, 94, 0.1)',
                    fill: true,
                    tension: 0.4,
                    pointRadius: 2
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    labels: { color: '#94a3b8', font: { size: 11 } }
                }
            },
            scales: {
                x: {
                    ticks: { color: '#64748b', font: { size: 10 }, maxTicksLimit: 12 },
                    grid: { color: '#1e293b' }
                },
                y: {
                    ticks: { color: '#64748b', font: { size: 10 } },
                    grid: { color: '#1e293b' }
                }
            },
            interaction: {
                intersect: false,
                mode: 'index'
            }
        }
    });
}

function generateTimeLabels() {
    const labels = [];
    const now = new Date();
    for (let i = 59; i >= 0; i--) {
        const d = new Date(now - i * 60000);
        labels.push(d.toLocaleTimeString('en-MY', { hour: '2-digit', minute: '2-digit', hour12: false }));
    }
    return labels;
}

function generateSampleData(factor = 1) {
    const data = [];
    let val = 50;
    for (let i = 0; i < 60; i++) {
        val += (Math.random() - 0.5) * 20;
        val = Math.max(5, Math.min(200, val));
        data.push(Math.round(val * factor * 10) / 10);
    }
    return data;
}

function initInterfaceSelector() {
    document.getElementById('trafficInterface')?.addEventListener('change', function() {
        if (trafficChart) {
            trafficChart.data.datasets[0].data = generateSampleData();
            trafficChart.data.datasets[1].data = generateSampleData(0.6);
            trafficChart.update();
        }
    });
}

// ============================================================
// Live Chart Updates (Simulated)
// ============================================================
setInterval(() => {
    if (trafficChart) {
        const labels = trafficChart.data.labels;
        const now = new Date();
        labels.push(now.toLocaleTimeString('en-MY', { hour: '2-digit', minute: '2-digit', hour12: false }));
        labels.shift();
        
        const lastIn = trafficChart.data.datasets[0].data[trafficChart.data.datasets[0].data.length - 1] || 50;
        const lastOut = trafficChart.data.datasets[1].data[trafficChart.data.datasets[1].data.length - 1] || 30;
        
        trafficChart.data.datasets[0].data.push(Math.max(5, Math.min(200, lastIn + (Math.random() - 0.5) * 15)));
        trafficChart.data.datasets[0].data.shift();
        trafficChart.data.datasets[1].data.push(Math.max(3, Math.min(150, lastOut + (Math.random() - 0.5) * 12)));
        trafficChart.data.datasets[1].data.shift();
        
        trafficChart.update('none');
    }
}, 3000);