/* ===============================
   GLOBAL STATE & SETTINGS
================================ */
let alertPlayed = false;
let currentSiteFilter = 'all';

let settings = {
    max_temperature: 75,
    notify_sound: 1,
    notify_email: 0
};

/* ===============================
   LOAD SETTINGS
================================ */
function loadSettings() {
    return fetch('../api/monitoring/get_settings.php')
        .then(res => res.json())
        .then(data => { settings = data; })
        .catch(() => {});
}

/* ===============================
   COLOR LOGIC
================================ */
function getColor(val, type) {
    val = Number(val) || 0;

    if (type === 'temp') {
        if (val < 60) return 'safe';
        if (val < Number(settings.max_temperature)) return 'warn';
        return 'danger';
    }

    if (val < 70) return 'safe';
    if (val < 85) return 'warn';
    return 'danger';
}

/* ===============================
   ALERT LOGIC
================================ */
function isCritical(pc) {
    return (
        pc.status === 'online' &&
        (
            pc.temp >= Number(settings.max_temperature) ||
            pc.cpu >= 90 ||
            pc.ram >= 90
        )
    );
}

function getCardClass(pc) {
    if (pc.status === 'offline') return 'offline';
    if (isCritical(pc)) return 'critical';
    return 'online';
}

/* ===============================
   TOGGLE SITE COLLAPSE
================================ */
function toggleSite(id) {
    document.getElementById(id)?.classList.toggle('collapsed');
}

/* ===============================
   SITE FILTER
================================ */
function populateSiteFilter(data) {
    const select = document.getElementById('siteFilter');
    if (!select) return;

    const sites = new Set();
    data.forEach(pc => {
        if (pc.site_name) sites.add(pc.site_name);
    });

    select.innerHTML = `<option value="all">All Site</option>`;

    [...sites].sort().forEach(site => {
        const opt = document.createElement('option');
        opt.value = site;
        opt.textContent = site;
        select.appendChild(opt);
    });

    select.value = currentSiteFilter;
}

document.addEventListener('change', e => {
    if (e.target.id === 'siteFilter') {
        currentSiteFilter = e.target.value;
        loadDashboard();
    }
});

/* ===============================
   DASHBOARD RENDER
================================ */
function loadDashboard() {
    fetch('../api/monitoring/list_pc.php')
        .then(res => res.json())
        .then(data => {

            const grid  = document.getElementById('pcGrid');
            const sound = document.getElementById('alertSound');

            grid.innerHTML = '';

            populateSiteFilter(data);

            // FILTER SITE
            if (currentSiteFilter !== 'all') {
                data = data.filter(pc => pc.site_name === currentSiteFilter);
            }

            let online = 0;
            let criticalFound = false;

            const grouped = {};
            data.forEach(pc => {
                const site = pc.site_name || 'Unknown Site';
                if (!grouped[site]) grouped[site] = [];
                grouped[site].push(pc);
                if (pc.status === 'online') online++;
            });

            Object.entries(grouped).forEach(([siteName, pcs], idx) => {
                const siteId = `site-${idx}-${siteName.replace(/\s+/g, '-')}`;

                grid.innerHTML += `
                    <div class="site-group">
                        <div class="site-header" onclick="toggleSite('${siteId}')">
                            <h3>📍 ${siteName}</h3>
                            <span>${pcs.length} PC</span>
                        </div>
                        <div class="site-content" id="${siteId}"></div>
                    </div>
                `;

                const container = document.getElementById(siteId);

                pcs.forEach(pc => {
                    const cardClass = getCardClass(pc);
                    if (cardClass === 'critical') criticalFound = true;

                    container.innerHTML += `
                        <div class="device-card ${cardClass}" onclick='openModal(${JSON.stringify(pc)})'>
                            <h4>
                                ${pc.hostname}
                                ${cardClass === 'critical'
                                    ? '<span class="badge-alert">ALERT</span>'
                                    : ''}
                            </h4>
                            <small>${pc.ip_address}</small>

                            <div class="metrics">
                                <div class="metric ${getColor(pc.temp,'temp')}">🌡️ ${pc.temp ?? '-'}</div>
                                <div class="metric ${getColor(pc.cpu)}">🧠 ${pc.cpu ?? '-'}</div>
                                <div class="metric ${getColor(pc.ram)}">💾 ${pc.ram ?? '-'}</div>
                            </div>

                            <p class="status ${pc.status}">${pc.status.toUpperCase()}</p>
                            <small>${pc.last_seen}</small>
                        </div>
                    `;
                });
            });

            document.getElementById('total_pc').innerText = data.length;
            document.getElementById('online_pc').innerText = `Online: ${online}`;

            /* 🔊 SOUND ALERT */
            if (criticalFound && !alertPlayed && settings.notify_sound == 1) {
                sound?.play().catch(() => {});
                alertPlayed = true;
            }

            if (!criticalFound) {
                alertPlayed = false;
            }
        })
        .catch(err => console.error(err));
}

/* ===============================
   EMAIL ALERT CHECK
================================ */
function checkEmailAlert() {
    fetch('../api/monitoring/check_alert.php').catch(() => {});
}

/* ===============================
   MODAL SENSOR DETAIL
================================ */
function openModal(pc) {
    const modal = document.getElementById('sensorModal');
    const body  = document.getElementById('modalBody');
    const title = document.getElementById('modalTitle');

    title.innerText = `🖥️ ${pc.hostname} (${pc.status.toUpperCase()})`;

    let html = '';

    if (pc.sensors?.cpu_temp?.length) {
        html += '<h4>🌡️ CPU Temperature</h4><ul>';
        pc.sensors.cpu_temp.forEach(t => {
            html += `<li>${t.name}: <b>${t.value}°C</b></li>`;
        });
        html += '</ul>';
    }

    html += `<h4>🧠 CPU Usage</h4><p>${pc.cpu ?? '-'}%</p>`;
    html += `<h4>💾 RAM Usage</h4><p>${pc.ram ?? '-'}%</p>`;

    body.innerHTML = html;
    modal.style.display = 'block';
}

function closeModal() {
    document.getElementById('sensorModal').style.display = 'none';
}

window.onclick = function (e) {
    if (e.target === document.getElementById('sensorModal')) closeModal();
};

/* ===============================
   SIDEBAR TOGGLE
================================ */
function toggleSidebar() {
    document.querySelector('.sidebar')?.classList.toggle('show');
    document.getElementById('overlay')?.classList.toggle('show');
}

/* ===============================
   INIT
================================ */
loadSettings().then(() => {
    loadDashboard();
    checkEmailAlert();

    setInterval(() => {
        loadDashboard();
        checkEmailAlert();
    }, 10000);
});
