$(function () {
    loadStats();
    loadLogs(1);
    loadPolicies();
    loadRetentionLog();

    $('#filterModule, #filterAction, #filterUser, #filterSearch').on('change keyup', function () {
        loadLogs(1);
    });

    $('#btnPrevPage').on('click', function () {
        var p = parseInt($('#paginationInfo').data('page') || 1) - 1;
        if (p >= 1) loadLogs(p);
    });

    $('#btnNextPage').on('click', function () {
        var p = parseInt($('#paginationInfo').data('page') || 1) + 1;
        var pages = parseInt($('#paginationInfo').data('pages') || 1);
        if (p <= pages) loadLogs(p);
    });

    $('#btnVerifyIntegrity').on('click', function () {
        verifyIntegrity();
    });

    $('#btnBackfillHashes').on('click', function () {
        backfillHashes();
    });

    $('#btnNewPolicy').on('click', function () {
        resetPolicyForm();
        $('#policyModalTitle').text('New Retention Policy');
        $('#policyModal').modal('show');
    });

    $('#policyForm').on('submit', function (e) {
        e.preventDefault();
        savePolicy();
    });

    $('#btnRunRetention').on('click', function () {
        if (!confirm('Run retention cleanup now? This will apply all active policies.')) return;
        runRetention();
    });

    $(document).on('click', '.btn-edit-policy', function () {
        editPolicy($(this).data('id'));
    });

    $(document).on('click', '.btn-delete-policy', function () {
        if (confirm('Delete this policy?')) deletePolicy($(this).data('id'));
    });

    $(document).on('click', '.btn-view-hash', function () {
        var hash = $(this).data('hash');
        var prevHash = $(this).data('prev');
        alert('Hash: ' + hash + '\n\nPrevious Hash: ' + (prevHash || 'None'));
    });
});

var auditPage = 1;

function loadStats() {
    $.get('api/audit.php?action=stats', function (r) {
        if (r.status !== 'success') return;
        var d = r.data || {};
        $('#kpiTotal').text(d.total || 0);
        $('#kpiHashed').text(d.hashed || 0);
        $('#kpiUnhashed').text(d.unhashed || 0);
        $('#kpiDeleted').text(d.deleted || 0);
        if (d.unhashed > 0) $('#kpiUnhashed').closest('.kpi-card').addClass('border-warning border-2');
    }, 'json');
}

function loadLogs(page) {
    auditPage = page;
    var params = {
        action: 'list',
        page: page,
        module: $('#filterModule').val(),
        action_filter: $('#filterAction').val(),
        user_id: $('#filterUser').val(),
        search: $('#filterSearch').val()
    };

    $.get('api/audit.php', params, function (r) {
        if (r.status !== 'success') return;
        var rows = r.data || [];

        if (page === 1 && r.filters) {
            populateFilter('#filterModule', r.filters.modules || [], 'All modules');
            populateFilter('#filterAction', r.filters.actions || [], 'All actions');
            var users = r.filters.users || [];
            var uOpts = '<option value="">All users</option>';
            users.forEach(function (u) { uOpts += '<option value="' + u.user_id + '">' + esc(u.name) + '</option>'; });
            $('#filterUser').html(uOpts);
        }

        $('#paginationInfo').text('Page ' + r.page + ' of ' + r.pages + ' (' + r.total + ' total)').data('page', r.page).data('pages', r.pages);
        $('#btnPrevPage').prop('disabled', r.page <= 1);
        $('#btnNextPage').prop('disabled', r.page >= r.pages);

        var html = '';
        rows.forEach(function (a) {
            var hashIcon = a.hash ? '<span class="text-success" title="Hash verified"><i class="bi bi-shield-fill-check"></i></span>' : '<span class="text-muted" title="No hash"><i class="bi bi-shield"></i></span>';
            html += '<tr>' +
                '<td class="text-muted small">' + a.id + '</td>' +
                '<td><strong>' + esc(a.user_name || 'System') + '</strong></td>' +
                '<td><span class="badge bg-' + actionBadge(a.action) + '">' + esc(a.action) + '</span></td>' +
                '<td><span class="badge bg-secondary">' + esc(a.module) + '</span></td>' +
                '<td><small title="' + esc(a.description || '') + '">' + esc(truncate(a.description, 80)) + '</small></td>' +
                '<td class="small text-muted">' + esc(a.ip_address || '-') + '</td>' +
                '<td class="text-center">' +
                (a.hash ? '<button class="btn btn-sm btn-link p-0 btn-view-hash" data-hash="' + esc(a.hash) + '" data-prev="' + esc(a.prev_hash || '') + '" title="View hash">' + hashIcon + '</button>' : hashIcon) +
                '</td>' +
                '<td class="small">' + esc(a.created_at) + '</td>' +
                '</tr>';
        });
        if (!html) html = '<tr><td colspan="8" class="text-center text-muted py-3">No audit records found.</td></tr>';
        $('#auditTable').html(html);
    }, 'json');
}

function verifyIntegrity() {
    $('#integrityResult').html('<div class="spinner-border spinner-border-sm me-2"></div>Verifying hash chain...');
    $.get('api/audit.php?action=verify', function (r) {
        if (r.status !== 'success') {
            $('#integrityResult').html('<span class="text-danger">' + esc(r.message) + '</span>');
            return;
        }
        var d = r.data || {};
        var cls = d.tampered > 0 ? 'danger' : 'success';
        var icon = d.tampered > 0 ? 'bi-x-circle-fill' : 'bi-check-circle-fill';
        $('#integrityResult').html(
            '<div class="fs-5 mb-2 text-' + cls + '"><i class="bi ' + icon + ' me-2"></i>' +
            d.total_checked + ' records checked — ' + d.valid + ' valid, ' + d.tampered + ' tampered</div>' +
            '<div class="small text-muted">' + (d.tampered > 0 ? 'WARNING: Hash chain integrity is compromised!' : 'Hash chain integrity is intact.') + '</div>'
        );

        var chainHtml = '<div class="table-responsive"><table class="table table-sm small mb-0"><thead><tr><th>ID</th><th>Valid</th><th>Hash Match</th><th>Chain OK</th><th>Description</th><th>Date</th></tr></thead><tbody>';
        (d.details || []).forEach(function (det) {
            var vCls = det.valid ? 'success' : 'danger';
            chainHtml += '<tr class="table-' + vCls + '">' +
                '<td>' + det.id + '</td>' +
                '<td><span class="badge bg-' + vCls + '">' + (det.valid ? 'OK' : 'FAIL') + '</span></td>' +
                '<td>' + (det.hash_mismatch ? '<span class="text-danger">MISMATCH</span>' : '<span class="text-success">OK</span>') + '</td>' +
                '<td>' + (det.chain_broken ? '<span class="text-danger">BROKEN</span>' : '<span class="text-success">OK</span>') + '</td>' +
                '<td><small>' + esc(det.description) + '</small></td>' +
                '<td>' + (det.created_at || '') + '</td></tr>';
        });
        chainHtml += '</tbody></table></div>';
        $('#chainDetails').html(chainHtml);
    }, 'json');
}

function backfillHashes() {
    $('#integrityResult').html('<div class="spinner-border spinner-border-sm me-2"></div>Backfilling hashes...');
    $.post('api/audit.php?action=backfill', { csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status !== 'success') {
            $('#integrityResult').html('<span class="text-danger">' + esc(r.message) + '</span>');
            return;
        }
        var d = r.data || {};
        $('#integrityResult').html('<span class="text-success"><i class="bi bi-check-circle me-1"></i> Backfilled ' + d.backfilled + ' hashes.</span>');
        loadStats();
    }, 'json');
}

function loadPolicies() {
    $.get('api/audit.php?action=retention_policies', function (r) {
        if (r.status !== 'success') return;
        var rows = r.data || [];
        var html = '';
        rows.forEach(function (p) {
            var actionCls = p.archive_action === 'delete' ? 'danger' : (p.archive_action === 'archive' ? 'warning text-dark' : 'info');
            html += '<tr>' +
                '<td><strong>' + esc(p.module) + '</strong></td>' +
                '<td>' + esc(p.action || 'All') + '</td>' +
                '<td>' + p.retention_days + '</td>' +
                '<td><span class="badge bg-' + actionCls + '">' + esc(p.archive_action) + '</span></td>' +
                '<td><span class="badge bg-' + (p.is_active ? 'success' : 'secondary') + '">' + (p.is_active ? 'Active' : 'Inactive') + '</span></td>' +
                '<td class="text-end">' +
                '<button class="btn btn-sm btn-outline-primary btn-edit-policy me-1" data-id="' + p.id + '"><i class="bi bi-pencil"></i></button>' +
                '<button class="btn btn-sm btn-outline-danger btn-delete-policy" data-id="' + p.id + '"><i class="bi bi-trash"></i></button>' +
                '</td></tr>';
        });
        if (!html) html = '<tr><td colspan="6" class="text-center text-muted py-3">No policies defined.</td></tr>';
        $('#policiesTable').html(html);
    }, 'json');
}

function savePolicy() {
    var data = $('#policyForm').serialize();
    $.post('api/audit.php?action=save_retention_policy', data, function (r) {
        if (r.status !== 'success') { alert(r.message); return; }
        $('#policyModal').modal('hide');
        loadPolicies();
    }, 'json');
}

function editPolicy(id) {
    var row = null;
    $('#policiesTable tr').each(function () {
        var btn = $(this).find('.btn-edit-policy[data-id="' + id + '"]');
        if (btn.length) {
            var cells = $(this).find('td');
            row = {
                id: id,
                module: $(cells[0]).text().trim(),
                action: $(cells[1]).text().trim(),
                retention_days: parseInt($(cells[2]).text().trim()),
                archive_action: $(cells[3]).text().trim().toLowerCase(),
                is_active: $(cells[4]).text().trim() === 'Active' ? 1 : 0
            };
        }
    });
    if (!row) return;
    $('#policy_id').val(row.id);
    $('#policy_module').val(row.module);
    $('#policy_action').val(row.action === 'All' ? '' : row.action);
    $('#policy_days').val(row.retention_days);
    $('#policy_archive_action').val(row.archive_action);
    $('#policyModalTitle').text('Edit Policy');
    $('#policyModal').modal('show');
}

function deletePolicy(id) {
    $.post('api/audit.php?action=delete_retention_policy', { id: id, csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status !== 'success') { alert(r.message); return; }
        loadPolicies();
    }, 'json');
}

function resetPolicyForm() {
    $('#policyForm')[0].reset();
    $('#policy_id').val('');
    $('#policy_days').val('365');
    $('#policy_archive_action').val('delete');
}

function runRetention() {
    $('#retentionRunResult').html('<div class="spinner-border spinner-border-sm me-2"></div>Running cleanup...');
    $.post('api/audit.php?action=retention_run', { csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status !== 'success') {
            $('#retentionRunResult').html('<span class="text-danger">' + esc(r.message) + '</span>');
            return;
        }
        var d = r.data || {};
        var html = '<div class="mb-2">' +
            '<span class="badge bg-danger me-2">' + (d.records_deleted || 0) + ' Deleted</span>' +
            '<span class="badge bg-warning text-dark">' + (d.records_archived || 0) + ' Archived</span>' +
            '</div><ul class="small text-muted mb-0">';
        (d.details || []).forEach(function (det) {
            html += '<li>' + esc(det) + '</li>';
        });
        html += '</ul>';
        $('#retentionRunResult').html(html);
        loadRetentionLog();
        loadStats();
    }, 'json');
}

function loadRetentionLog() {
    $.get('api/audit.php?action=retention_log', function (r) {
        if (r.status !== 'success') return;
        var rows = r.data || [];
        var html = '';
        rows.forEach(function (l) {
            html += '<tr><td>' + esc(l.ran_at) + '</td><td>' + (l.records_deleted || 0) + '</td><td>' + (l.records_archived || 0) + '</td><td><small>' + esc(truncate((l.details || ''), 120)) + '</small></td></tr>';
        });
        if (!html) html = '<tr><td colspan="4" class="text-center text-muted py-3">No cleanup runs yet.</td></tr>';
        $('#retentionLogTable').html(html);
    }, 'json');
}

function populateFilter(sel, items, defaultLabel) {
    var opts = '<option value="">' + defaultLabel + '</option>';
    items.forEach(function (i) { opts += '<option value="' + esc(i) + '">' + esc(i) + '</option>'; });
    $(sel).html(opts);
}

function actionBadge(action) {
    var map = { create: 'success', update: 'primary', delete: 'danger', restore: 'info', login: 'secondary', logout: 'secondary', save: 'primary' };
    return map[action] || 'secondary';
}

function truncate(s, n) {
    if (!s) return '';
    return s.length > n ? s.substring(0, n) + '...' : s;
}

function esc(t) { return $('<div>').text(t || '').html(); }
