<?php
/**
 * Sticky red banner shown at the top of every panel page when:
 *  - the caller is root (AUTH_USER === 'root')
 *  - any disk partition is currently in critical (severity_level >= 4 / >=95%)
 *
 * Read-only: the banner just surfaces what whp-monitor-poll.py already
 * captures in /var/lib/whp-ai-monitor/monitor.db. Cheap query, run on
 * every page load -- adds ~1 SQLite query and skips entirely for non-root.
 *
 * Included from index.php just inside the main page wrapper so the warning
 * is visible regardless of which sidebar item the operator is on.
 */
if (!defined('AUTH_USER') || AUTH_USER !== 'root') return;

$_critical_disks = [];
$_db_path = '/var/lib/whp-ai-monitor/monitor.db';
if (is_file($_db_path) && is_readable($_db_path)) {
    try {
        $_pdo = new PDO('sqlite:' . $_db_path);
        $_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $_stmt = $_pdo->query("
            SELECT subsystem, status, severity_level, detail_json, transitioned_at
              FROM health_state
             WHERE subsystem LIKE 'disk:%'
               AND status = 'critical'
               AND severity_level >= 4
             ORDER BY severity_level DESC
        ");
        $_critical_disks = $_stmt->fetchAll(PDO::FETCH_ASSOC);
        $_pdo = null;
    } catch (Throwable $_e) {
        // Banner is opportunistic; silently skip on DB issues.
    }
}

if (empty($_critical_disks)) return;
?>
<div class="alert alert-danger m-0 rounded-0 border-0" role="alert" style="position: sticky; top: 0; z-index: 1050;">
    <div class="container-fluid">
        <strong><i class="fa fa-exclamation-triangle"></i> Critical disk usage</strong>
        <ul class="mb-1 mt-1">
            <?php foreach ($_critical_disks as $_d):
                $_partition = substr($_d['subsystem'], 5); // strip 'disk:' prefix
                $_detail = json_decode($_d['detail_json'] ?? '{}', true) ?: [];
                $_pct = isset($_detail['usage_percent']) ? round((float)$_detail['usage_percent'], 1) : null;
                $_freeGb = $_detail['free_gb'] ?? null;
                $_tierLabels = [4 => 'critical (>=95%)', 5 => 'urgent (>=99%)', 6 => 'collapse (100%)'];
                $_label = $_tierLabels[(int)$_d['severity_level']] ?? 'critical';
            ?>
                <li>
                    <code><?php echo htmlspecialchars($_partition); ?></code>
                    is at <strong><?php echo $_pct !== null ? htmlspecialchars($_pct) . '%' : 'critical'; ?></strong>
                    <?php if ($_freeGb !== null): ?>
                        (<?php echo htmlspecialchars($_freeGb); ?> GB free)
                    <?php endif; ?>
                    &mdash; <?php echo htmlspecialchars($_label); ?>
                </li>
            <?php endforeach; ?>
        </ul>
        <a href="index.php?page=ai-monitor" class="btn btn-sm btn-outline-light me-2">
            <i class="fa fa-search"></i> View diagnosis
        </a>
        <button type="button" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#diskCleanupModal">
            <i class="fa fa-broom"></i> Suggest cleanup
        </button>
    </div>
</div>

<?php // Cleanup modal -- shared by all pages so the banner CTA always has a target ?>
<div class="modal fade" id="diskCleanupModal" tabindex="-1" aria-labelledby="diskCleanupModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="diskCleanupModalLabel">Disk cleanup suggestions</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="diskCleanupContent">
                    <p class="text-muted">Loading detected cleanup candidates...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-danger" id="diskCleanupExecuteBtn" disabled>
                    <i class="fa fa-trash"></i> Execute selected cleanups
                </button>
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    var modal = document.getElementById('diskCleanupModal');
    if (!modal) return;
    var content = document.getElementById('diskCleanupContent');
    var executeBtn = document.getElementById('diskCleanupExecuteBtn');
    var csrf = <?php echo json_encode($_SESSION['csrf_token'] ?? ''); ?>;

    function escapeHtml(s) {
        return String(s).replace(/[&<>"']/g, function(c) {
            return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
        });
    }

    modal.addEventListener('show.bs.modal', function() {
        while (content.firstChild) content.removeChild(content.firstChild);
        var loading = document.createElement('p');
        loading.className = 'text-muted';
        loading.textContent = 'Scanning for cleanup candidates...';
        content.appendChild(loading);
        executeBtn.disabled = true;

        fetch('api/disk-cleanup.php?action=detect', {
            headers: { 'X-CSRF-Token': csrf }
        }).then(function(r) { return r.json(); }).then(function(data) {
            while (content.firstChild) content.removeChild(content.firstChild);
            if (!data.success) {
                var err = document.createElement('div');
                err.className = 'alert alert-warning';
                err.textContent = 'Detection failed: ' + (data.error || 'unknown error');
                content.appendChild(err);
                return;
            }
            if (!data.candidates || data.candidates.length === 0) {
                var none = document.createElement('p');
                none.className = 'text-muted';
                none.textContent = 'No cleanup candidates detected.';
                content.appendChild(none);
                return;
            }
            var help = document.createElement('p');
            help.className = 'small text-muted';
            help.textContent = 'Review and select the items you want to remove. Nothing happens until you click Execute.';
            content.appendChild(help);

            var table = document.createElement('table');
            table.className = 'table table-sm table-hover';
            var thead = document.createElement('thead');
            var theadRow = document.createElement('tr');
            ['', 'Path', 'Size', 'Reason'].forEach(function(label, idx) {
                var th = document.createElement('th');
                if (idx === 0) {
                    var cb = document.createElement('input');
                    cb.type = 'checkbox';
                    cb.id = 'diskCleanupSelectAll';
                    th.appendChild(cb);
                } else {
                    th.textContent = label;
                }
                theadRow.appendChild(th);
            });
            thead.appendChild(theadRow);
            table.appendChild(thead);
            var tbody = document.createElement('tbody');
            data.candidates.forEach(function(c, i) {
                var tr = document.createElement('tr');
                var tdSel = document.createElement('td');
                var cb = document.createElement('input');
                cb.type = 'checkbox';
                cb.className = 'diskCleanupItem';
                cb.value = String(i);
                tdSel.appendChild(cb);
                tr.appendChild(tdSel);

                var tdPath = document.createElement('td');
                var code = document.createElement('code');
                code.textContent = c.path || '';
                tdPath.appendChild(code);
                tr.appendChild(tdPath);

                var tdSize = document.createElement('td');
                tdSize.className = 'text-end';
                tdSize.textContent = (c.size / 1024 / 1024).toFixed(1) + ' MB';
                tr.appendChild(tdSize);

                var tdReason = document.createElement('td');
                tdReason.className = 'small';
                tdReason.textContent = c.reason || '';
                tr.appendChild(tdReason);

                tbody.appendChild(tr);
            });
            table.appendChild(tbody);
            content.appendChild(table);

            executeBtn.disabled = false;
            executeBtn.dataset.candidates = JSON.stringify(data.candidates);
            document.getElementById('diskCleanupSelectAll').addEventListener('change', function(e) {
                document.querySelectorAll('.diskCleanupItem').forEach(function(c2) { c2.checked = e.target.checked; });
            });
        }).catch(function(err) {
            content.textContent = 'Detection error: ' + err;
        });
    });

    executeBtn.addEventListener('click', function() {
        var all = JSON.parse(executeBtn.dataset.candidates || '[]');
        var selected = [];
        document.querySelectorAll('.diskCleanupItem:checked').forEach(function(cb) {
            selected.push(all[parseInt(cb.value, 10)]);
        });
        if (selected.length === 0) {
            alert('Select at least one item to remove.');
            return;
        }
        if (!confirm('Permanently delete ' + selected.length + ' selected items?')) return;
        executeBtn.disabled = true;
        fetch('api/disk-cleanup.php?action=execute', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': csrf
            },
            body: JSON.stringify({ paths: selected.map(function(s) { return s.path; }) })
        }).then(function(r) { return r.json(); }).then(function(data) {
            if (data.success) {
                alert('Cleanup complete. Freed ' + (data.freed_mb || 0) + ' MB across ' + (data.deleted || 0) + ' files.');
                window.location.reload();
            } else {
                alert('Cleanup failed: ' + (data.error || 'unknown error'));
                executeBtn.disabled = false;
            }
        }).catch(function(err) {
            alert('Cleanup error: ' + err);
            executeBtn.disabled = false;
        });
    });
})();
</script>
