{% extends "base.html" %}
{% block title %}Admin — Server Monitoring{% endblock %}
{% block page_title %}Admin &amp; Maintenance{% endblock %}

{% block extra_css %}
<style>
.danger-card { border: 2px solid #dc3545; }
.danger-card .card-header { background-color: #dc3545; color: #fff; }
.warning-card { border: 2px solid #fd7e14; }
.warning-card .card-header { background-color: #fd7e14; color: #fff; }
.stat-box { background: #f8f9fa; border-radius: 8px; padding: 12px 20px; text-align: center; }
.stat-box .num { font-size: 2rem; font-weight: bold; line-height: 1; }
.stat-box .lbl { font-size: .78rem; color: #6c757d; margin-top: 2px; }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">

    <!-- Current stats row -->
    <div class="row g-3 mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-secondary text-white">
                    <h5 class="mb-0"><i class="fas fa-database me-2"></i>Current Database &amp; Inventory State</h5>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-6 col-md-2">
                            <div class="stat-box">
                                <div class="num text-primary" id="stat-devices">{{ stats.get('devices', '?') }}</div>
                                <div class="lbl">Devices</div>
                            </div>
                        </div>
                        <div class="col-6 col-md-2">
                            <div class="stat-box">
                                <div class="num text-info" id="stat-logs">{{ stats.get('logs', '?') }}</div>
                                <div class="lbl">Log Entries</div>
                            </div>
                        </div>
                        <div class="col-6 col-md-2">
                            <div class="stat-box">
                                <div class="num text-secondary" id="stat-templates">{{ stats.get('templates', '?') }}</div>
                                <div class="lbl">Msg Templates</div>
                            </div>
                        </div>
                        <div class="col-6 col-md-2">
                            <div class="stat-box">
                                <div class="num text-danger" id="stat-wmt">{{ stats.get('wmt_requests', '?') }}</div>
                                <div class="lbl">WMT Requests</div>
                            </div>
                        </div>
                        <div class="col-6 col-md-2">
                            <div class="stat-box">
                                <div class="num text-warning" id="stat-inv-hosts">{{ stats.get('inventory_hosts', '?') }}</div>
                                <div class="lbl">Inventory Hosts</div>
                            </div>
                        </div>
                        <div class="col-6 col-md-2">
                            <div class="stat-box">
                                <div class="num text-success" id="stat-inv-groups">{{ stats.get('inventory_groups_yaml', '?') }}</div>
                                <div class="lbl">Inventory Groups</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4">

        <!-- ── Backup Manager ──────────────────────────────────────────── -->
        <div class="col-md-8">
            <div class="card h-100" style="border:2px solid #198754">
                <div class="card-header" style="background:#198754;color:#fff">
                    <h5 class="mb-0"><i class="fas fa-archive me-2"></i>Backup Manager</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3 gap-3 flex-wrap">
                        <button class="btn btn-success" id="btn-run-backup" onclick="runBackup()">
                            <i class="fas fa-play me-2"></i>Run Backup Now
                        </button>
                        <span class="small" id="backup-status-msg"></span>
                    </div>
                    <hr class="my-2">
                    <h6 class="text-muted mb-2"><i class="fas fa-list me-1"></i>Existing Backups</h6>
                    <div id="backup-list-container">
                        <div class="text-center text-muted py-3">
                            <span class="spinner-border spinner-border-sm me-2"></span>Loading…
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ── Restore / Migrate ───────────────────────────────────────── -->
        <div class="col-md-4">
            <div class="card h-100" style="border:2px solid #0d6efd">
                <div class="card-header" style="background:#0d6efd;color:#fff">
                    <h5 class="mb-0"><i class="fas fa-upload me-2"></i>Restore / Migrate</h5>
                </div>
                <div class="card-body d-flex flex-column">
                    <p class="text-muted small mb-3">
                        Restore devices, Ansible inventory &amp; config from a backup archive.
                        Use <strong>Upload</strong> to migrate to a new server.
                    </p>

                    <div class="mb-3">
                        <label class="form-label fw-semibold small mb-1">Source</label>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="restore-source"
                                   id="src-existing" value="existing" checked onchange="toggleRestoreSource()">
                            <label class="form-check-label small" for="src-existing">Select existing backup</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="restore-source"
                                   id="src-upload" value="upload" onchange="toggleRestoreSource()">
                            <label class="form-check-label small" for="src-upload">Upload backup file (.tar.gz)</label>
                        </div>
                    </div>

                    <div id="restore-existing-picker" class="mb-3">
                        <select class="form-select form-select-sm" id="restore-existing-select">
                            <option value="">— loading… —</option>
                        </select>
                    </div>

                    <div id="restore-upload-picker" class="mb-3" style="display:none">
                        <input type="file" class="form-control form-control-sm"
                               id="restore-file-input" accept=".tar.gz">
                        <div class="form-text">Only .tar.gz archives produced by this system.</div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold small mb-1">Restore Scope</label>
                        <select class="form-select form-select-sm" id="restore-mode">
                            <option value="all">Full restore (DB + Ansible + Config)</option>
                            <option value="db-only">Database only (devices, groups, WMT config)</option>
                            <option value="ansible-only">Ansible only (inventory, playbooks, SSH keys)</option>
                        </select>
                    </div>

                    <div class="alert alert-warning py-2 small mb-3">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        A safety copy of the current DB is created automatically before restore.
                    </div>

                    <button class="btn btn-primary mt-auto w-100" id="btn-restore" onclick="runRestore()">
                        <i class="fas fa-undo me-2"></i>Restore Backup
                    </button>
                </div>
            </div>
        </div>

        <!-- Clear Log Entries -->
        <div class="col-md-4">
            <div class="card warning-card h-100">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-stream me-2"></i>Clear Log Entries</h5>
                </div>
                <div class="card-body d-flex flex-column">
                    <p class="text-muted flex-grow-1">
                        Deletes <strong>all log entries</strong> from the database.
                        Devices remain intact — they will start logging again automatically.
                    </p>
                    <div class="alert alert-warning py-2 mb-3">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        Currently <strong id="badge-logs">{{ stats.get('logs', '?') }}</strong> log entries.
                    </div>
                    <button class="btn btn-warning w-100"
                            onclick="runAction('clear-logs', 'Delete ALL log entries? This cannot be undone.')">
                        <i class="fas fa-trash me-2"></i>Clear All Logs
                    </button>
                </div>
            </div>
        </div>

        <!-- Registered Device Registry -->
        <div class="col-md-8">
            <div class="card danger-card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-server me-2"></i>Registered Device Registry</h5>
                    <span class="badge bg-light text-danger">{{ devices|length }} device(s)</span>
                </div>
                <div class="card-body p-0">
                    {% if devices %}
                    <div class="table-responsive" style="max-height:320px;overflow-y:auto;">
                        <table class="table table-sm table-hover mb-0">
                            <thead class="table-light sticky-top">
                                <tr>
                                    <th>Work Place</th>
                                    <th>Hostname</th>
                                    <th>MAC</th>
                                    <th>IP</th>
                                    <th class="text-end">Delete</th>
                                </tr>
                            </thead>
                            <tbody id="device-registry-body">
                                {% for d in devices %}
                                <tr id="device-row-{{ d.id }}">
                                    <td>{{ d.nume_masa or '—' }}</td>
                                    <td>{{ d.hostname or '—' }}</td>
                                    <td><code>{{ d.mac_address or '—' }}</code></td>
                                    <td>{{ d.device_ip or '—' }}</td>
                                    <td class="text-end">
                                        <button class="btn btn-danger btn-sm"
                                                onclick="deleteDevice({{ d.id }}, '{{ (d.nume_masa or d.hostname)|e }}')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    {% else %}
                    <div class="p-4 text-center text-muted">
                        <i class="fas fa-check-circle fa-2x mb-2 text-success"></i><br>
                        No registered devices.
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- Clear Ansible Inventory -->
        <div class="col-md-3">
            <div class="card danger-card h-100">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-sitemap me-2"></i>Clear Ansible Inventory</h5>
                </div>
                <div class="card-body d-flex flex-column">
                    <p class="text-muted flex-grow-1">
                        Resets the Ansible inventory file and clears all inventory groups.
                        The file is left fully empty — ready for new hosts and groups.
                    </p>
                    <div class="alert alert-danger py-2 mb-3">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        Currently <strong id="badge-inv-hosts">{{ stats.get('inventory_hosts', '?') }}</strong> hosts
                        in <strong id="badge-inv-groups">{{ stats.get('inventory_groups_yaml', '?') }}</strong> group(s).
                    </div>
                    <button class="btn btn-danger w-100"
                            onclick="runAction('clear-inventory', 'Reset Ansible inventory and delete all groups? This cannot be undone.')">
                        <i class="fas fa-trash me-2"></i>Clear Inventory
                    </button>
                </div>
            </div>
        </div>

        <!-- Clear WMT Update Requests -->
        <div class="col-md-3">
            <div class="card warning-card h-100">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-clipboard-list me-2"></i>Clear WMT Requests</h5>
                </div>
                <div class="card-body d-flex flex-column">
                    <p class="text-muted flex-grow-1">
                        Deletes <strong>all WMT update requests</strong> (pending, accepted and rejected).
                        Devices are not affected and can submit new requests at any time.
                    </p>
                    <div class="alert alert-warning py-2 mb-3">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        Currently <strong id="badge-wmt">{{ stats.get('wmt_requests', '?') }}</strong> update request(s).
                    </div>
                    <button class="btn btn-warning w-100"
                            onclick="runAction('clear-wmt', 'Delete ALL WMT update requests? This cannot be undone.')">
                        <i class="fas fa-trash me-2"></i>Clear WMT Requests
                    </button>
                </div>
            </div>
        </div>

    </div><!-- /row -->

</div><!-- /container -->

<!-- Output Modal (backup / restore log) -->
<div class="modal fade" id="outputModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="outputModalTitle">Output</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-2">
                <pre id="outputModalBody"
                     class="bg-dark text-light p-3 rounded mb-0"
                     style="max-height:420px;overflow-y:auto;font-size:.78rem;white-space:pre-wrap;word-break:break-all;"></pre>
            </div>
        </div>
    </div>
</div>

<!-- Result toast -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index:9999">
    <div id="resultToast" class="toast align-items-center text-white border-0" role="alert" aria-live="assertive">
        <div class="d-flex">
            <div class="toast-body" id="toastMsg">Done.</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<script>
const ENDPOINTS = {
    'clear-logs':         '{{ url_for("main.admin_clear_logs") }}',
    'clear-device-logs':  '{{ url_for("main.admin_clear_device_logs") }}',
    'clear-inventory':    '{{ url_for("main.admin_clear_inventory") }}',
    'clear-wmt':          '{{ url_for("main.admin_clear_wmt") }}'
};

function runAction(action, confirmMsg) {
    if (!confirm(confirmMsg)) return;
    const btn = event.currentTarget;
    btn.disabled = true;
    const origLabel = btn.innerHTML;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Working…';

    fetch(ENDPOINTS[action], {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            showToast('success', buildMessage(action, data));
            refreshStats();
        } else {
            showToast('danger', 'Error: ' + (data.error || 'Unknown'));
        }
    })
    .catch(err => showToast('danger', 'Network error: ' + err))
    .finally(() => { btn.disabled = false; btn.innerHTML = origLabel; });
}

function deleteDevice(deviceId, deviceName) {
    if (!confirm(`Delete device "${deviceName}" and all its logs and WMT requests?\n\nThis cannot be undone.`)) return;
    const btn = event.currentTarget;
    btn.disabled = true;
    const origLabel = btn.innerHTML;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

    fetch(`/admin/delete/device/${deviceId}`, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            // Remove row from table without page reload
            const row = document.getElementById(`device-row-${deviceId}`);
            if (row) row.remove();
            showToast('success', `Device "${data.name}" deleted.`);
            refreshStats();
        } else {
            showToast('danger', 'Error: ' + (data.error || 'Unknown'));
            btn.disabled = false;
            btn.innerHTML = origLabel;
        }
    })
    .catch(err => {
        showToast('danger', 'Network error: ' + err);
        btn.disabled = false;
        btn.innerHTML = origLabel;
    });
}

function buildMessage(action, data) {
    if (action === 'clear-logs' || action === 'clear-device-logs')
        return `Deleted ${data.deleted} log entries.`;
    if (action === 'clear-inventory')
        return `Inventory reset. ${data.groups_deleted} group(s) removed.`;
    if (action === 'clear-wmt')
        return `Deleted ${data.deleted} WMT update request(s).`;
    return 'Done.';
}

function showToast(type, msg) {
    const toast = document.getElementById('resultToast');
    toast.className = `toast align-items-center text-white bg-${type} border-0`;
    document.getElementById('toastMsg').textContent = msg;
    bootstrap.Toast.getOrCreateInstance(toast, {delay: 4000}).show();
}

function refreshStats() {
    // Reload the page stats after a short delay to let DB settle
    setTimeout(() => location.reload(), 800);
}

// ── Backup Manager ──────────────────────────────────────────────────────────

function escHtml(s) {
    return String(s)
        .replace(/&/g, '&amp;').replace(/</g, '&lt;')
        .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function showOutputModal(title, content) {
    document.getElementById('outputModalTitle').textContent = title;
    document.getElementById('outputModalBody').textContent = content || '(no output)';
    bootstrap.Modal.getOrCreateInstance(document.getElementById('outputModal')).show();
}

function loadBackupList() {
    fetch('/admin/backup/list')
        .then(r => r.json())
        .then(data => {
            renderBackupList(data.success ? data.backups : []);
            const sel = document.getElementById('restore-existing-select');
            if (data.success && data.backups.length) {
                sel.innerHTML = data.backups
                    .map(b => `<option value="${escHtml(b.name)}">${escHtml(b.name)} (${escHtml(b.size_human)})</option>`)
                    .join('');
            } else {
                sel.innerHTML = '<option value="">— no backups found —</option>';
            }
        })
        .catch(() => renderBackupList(null));
}

function renderBackupList(backups) {
    const el = document.getElementById('backup-list-container');
    if (!backups) {
        el.innerHTML = '<div class="text-danger small">Failed to load backup list.</div>';
        return;
    }
    if (backups.length === 0) {
        el.innerHTML = `<div class="text-muted small text-center py-3">
            <i class="fas fa-inbox fa-2x d-block mb-2"></i>
            No backups yet. Click "Run Backup Now" to create one.</div>`;
        return;
    }
    const rows = backups.map(b => `
        <tr>
            <td class="small font-monospace text-break">${escHtml(b.name)}</td>
            <td class="small text-nowrap">${escHtml(b.mtime)}</td>
            <td class="small text-end text-nowrap">${escHtml(b.size_human)}</td>
            <td class="text-end text-nowrap">
                <a href="/admin/backup/download/${encodeURIComponent(b.name)}"
                   class="btn btn-sm btn-outline-secondary me-1" title="Download">
                    <i class="fas fa-download"></i>
                </a>
                <button class="btn btn-sm btn-outline-danger" title="Delete"
                        onclick="deleteBackup('${escHtml(b.name)}')">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>`).join('');
    el.innerHTML = `
        <div class="table-responsive" style="max-height:220px;overflow-y:auto;">
            <table class="table table-sm table-hover mb-0">
                <thead class="table-light sticky-top">
                    <tr>
                        <th>Archive</th>
                        <th class="text-nowrap">Created</th>
                        <th class="text-end">Size</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>${rows}</tbody>
            </table>
        </div>`;
}

function runBackup() {
    if (!confirm('Run a full backup now?')) return;
    const btn = document.getElementById('btn-run-backup');
    const msg = document.getElementById('backup-status-msg');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Running…';
    msg.textContent = '';

    fetch('/admin/backup/run', {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            msg.className = 'text-success small';
            msg.textContent = data.archive ? '✓ Created: ' + data.archive : '✓ Backup completed.';
            loadBackupList();
            showOutputModal('Backup Output', data.output);
        } else {
            msg.className = 'text-danger small';
            msg.textContent = 'Backup failed — see details';
            showOutputModal('Backup Error', data.error);
        }
    })
    .catch(err => {
        msg.className = 'text-danger small';
        msg.textContent = 'Network error: ' + err;
    })
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-play me-2"></i>Run Backup Now';
    });
}

function deleteBackup(name) {
    if (!confirm('Delete backup "' + name + '"?\nThis cannot be undone.')) return;
    fetch('/admin/backup/delete/' + encodeURIComponent(name), {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            loadBackupList();
            showToast('success', 'Deleted: ' + data.deleted);
        } else {
            showToast('danger', 'Error: ' + (data.error || 'Unknown'));
        }
    })
    .catch(err => showToast('danger', 'Network error: ' + err));
}

function toggleRestoreSource() {
    const val = document.querySelector('input[name="restore-source"]:checked').value;
    document.getElementById('restore-existing-picker').style.display = val === 'existing' ? '' : 'none';
    document.getElementById('restore-upload-picker').style.display  = val === 'upload'   ? '' : 'none';
}

function runRestore() {
    const source = document.querySelector('input[name="restore-source"]:checked').value;
    const mode   = document.getElementById('restore-mode').value;

    if (!confirm('Restore from backup (scope: ' + mode + ')?\n\n' +
                 'This will overwrite the current database / Ansible files.\n' +
                 'A safety copy of the current DB is created automatically.')) return;

    const btn = document.getElementById('btn-restore');
    btn.disabled = true;
    const origLabel = btn.innerHTML;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Restoring…';

    const fd = new FormData();
    fd.append('mode', mode);

    if (source === 'existing') {
        const name = document.getElementById('restore-existing-select').value;
        if (!name) {
            showToast('danger', 'Select a backup first.');
            btn.disabled = false; btn.innerHTML = origLabel; return;
        }
        fd.append('existing_backup', name);
    } else {
        const file = document.getElementById('restore-file-input').files[0];
        if (!file) {
            showToast('danger', 'Select a .tar.gz file to upload.');
            btn.disabled = false; btn.innerHTML = origLabel; return;
        }
        fd.append('backup_file', file);
    }

    fetch('/admin/backup/restore', {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: fd
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            showToast('success', 'Restore completed successfully.');
            showOutputModal('Restore Output', data.output);
        } else {
            showOutputModal('Restore Error', data.error);
            showToast('danger', 'Restore failed — see output');
        }
    })
    .catch(err => showToast('danger', 'Network error: ' + err))
    .finally(() => { btn.disabled = false; btn.innerHTML = origLabel; });
}

document.addEventListener('DOMContentLoaded', loadBackupList);
</script>
{% endblock %}
