<?php
require_once 'app/helpers/auth.php';
require_once 'app/helpers/rbac.php';
require_once 'app/helpers/csrf.php';
requireLogin();

if (!can('audit.view')) {
    echo "Access denied";
    exit;
}

$page_js = 'audit.js';
$canVerify = isAdmin() || can('audit.verify');
$canManageRetention = isAdmin() || can('audit.retention.manage');
$canRunRetention = isAdmin() || can('audit.retention.run');

include 'views/layouts/header.php';
include 'views/layouts/sidebar.php';
?>

<main class="main-content">
<?php include 'views/layouts/topbar.php'; ?>

<div class="container-fluid p-3 p-md-4">
    <div id="alertBox" class="alert d-none"></div>

    <section class="mb-4">
        <span class="section-chip mb-3"><i class="bi bi-clock-history"></i> Audit & Compliance</span>
        <h1 class="mb-2">Audit Logs</h1>
        <p class="text-muted mb-0">Tamper-proof audit trail with hash-chain integrity verification and retention management.</p>
    </section>

    <div class="row g-3 mb-4">
        <div class="col-6 col-md-3">
            <div class="card kpi-card shadow-sm border-0 h-100">
                <div class="card-body">
                    <div class="kpi-label">Total Records</div>
                    <div class="kpi-value" id="kpiTotal">-</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="card kpi-card shadow-sm border-0 h-100">
                <div class="card-body">
                    <div class="kpi-label">With Hashes</div>
                    <div class="kpi-value" id="kpiHashed">-</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="card kpi-card shadow-sm border-0 h-100">
                <div class="card-body">
                    <div class="kpi-label">Unhashed</div>
                    <div class="kpi-value" id="kpiUnhashed">-</div>
                </div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="card kpi-card shadow-sm border-0 h-100">
                <div class="card-body">
                    <div class="kpi-label">Deleted</div>
                    <div class="kpi-value" id="kpiDeleted">-</div>
                </div>
            </div>
        </div>
    </div>

    <ul class="nav nav-tabs mb-3" id="auditTabs" role="tablist">
        <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tabLogs"><i class="bi bi-list-ul me-1"></i> Logs</button></li>
        <?php if ($canVerify): ?>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabIntegrity"><i class="bi bi-shield-check me-1"></i> Integrity</button></li>
        <?php endif; ?>
        <?php if ($canManageRetention || $canRunRetention): ?>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabRetention"><i class="bi bi-archive me-1"></i> Retention</button></li>
        <?php endif; ?>
    </ul>

    <div class="tab-content">
        <!-- Logs Tab -->
        <div class="tab-pane fade show active" id="tabLogs">
            <div class="card shadow-sm border-0">
                <div class="card-header bg-white d-flex flex-wrap justify-content-between align-items-center gap-2 py-2">
                    <div class="d-flex gap-2 flex-wrap">
                        <select id="filterModule" class="form-select form-select-sm" style="min-width:120px"><option value="">All modules</option></select>
                        <select id="filterAction" class="form-select form-select-sm" style="min-width:100px"><option value="">All actions</option></select>
                        <select id="filterUser" class="form-select form-select-sm" style="min-width:140px"><option value="">All users</option></select>
                        <input type="text" id="filterSearch" class="form-control form-control-sm" placeholder="Search..." style="min-width:120px">
                    </div>
                    <div class="d-flex gap-2">
                        <span class="text-muted small align-self-center" id="paginationInfo"></span>
                        <button class="btn btn-outline-secondary btn-sm" id="btnPrevPage" disabled>&laquo; Prev</button>
                        <button class="btn btn-outline-secondary btn-sm" id="btnNextPage" disabled>Next &raquo;</button>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table align-middle table-hover table-sm mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th style="min-width:30px">#</th>
                                    <th style="min-width:100px">User</th>
                                    <th style="min-width:70px">Action</th>
                                    <th style="min-width:80px">Module</th>
                                    <th style="min-width:200px">Description</th>
                                    <th style="min-width:80px">IP</th>
                                    <th style="min-width:60px" title="Hash Present">H</th>
                                    <th style="min-width:130px">Date</th>
                                </tr>
                            </thead>
                            <tbody id="auditTable">
                                <tr><td colspan="8" class="text-center text-muted py-4">Loading...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($canVerify): ?>
        <!-- Integrity Tab -->
        <div class="tab-pane fade" id="tabIntegrity">
            <div class="card shadow-sm border-0 mb-3">
                <div class="card-header bg-white d-flex justify-content-between align-items-center py-2">
                    <h6 class="mb-0"><i class="bi bi-shield-check me-1"></i> Hash Chain Verification</h6>
                    <div class="d-flex gap-2">
                        <button class="btn btn-outline-warning btn-sm" id="btnBackfillHashes"><i class="bi bi-files me-1"></i> Backfill Missing Hashes</button>
                        <button class="btn btn-outline-primary btn-sm" id="btnVerifyIntegrity"><i class="bi bi-check-circle me-1"></i> Verify Integrity</button>
                    </div>
                </div>
                <div class="card-body">
                    <div id="integrityResult" class="text-muted small">Click "Verify Integrity" to check the audit log hash chain.</div>
                </div>
            </div>
            <div class="card shadow-sm border-0">
                <div class="card-header bg-white py-2">
                    <h6 class="mb-0"><i class="bi bi-diagram-2 me-1"></i> Chain Details</h6>
                </div>
                <div class="card-body p-0" style="max-height:500px;overflow-y:auto">
                    <div id="chainDetails" class="text-muted small p-3">Run verification to see chain details.</div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if ($canManageRetention || $canRunRetention): ?>
        <!-- Retention Tab -->
        <div class="tab-pane fade" id="tabRetention">
            <?php if ($canManageRetention): ?>
            <div class="card shadow-sm border-0 mb-3">
                <div class="card-header bg-white d-flex justify-content-between align-items-center py-2">
                    <h6 class="mb-0"><i class="bi bi-gear me-1"></i> Retention Policies</h6>
                    <button class="btn btn-primary btn-sm" id="btnNewPolicy"><i class="bi bi-plus-lg me-1"></i> Add Policy</button>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table align-middle table-hover table-sm mb-0">
                            <thead class="table-light">
                                <tr><th>Module</th><th>Action</th><th>Retention (Days)</th><th>Action Type</th><th>Status</th><th class="text-end">Actions</th></tr>
                            </thead>
                            <tbody id="policiesTable">
                                <tr><td colspan="6" class="text-center text-muted py-3">Loading...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            <?php if ($canRunRetention): ?>
            <div class="card shadow-sm border-0 mb-3">
                <div class="card-header bg-white d-flex justify-content-between align-items-center py-2">
                    <h6 class="mb-0"><i class="bi bi-play-circle me-1"></i> Execute Cleanup</h6>
                    <button class="btn btn-danger btn-sm" id="btnRunRetention"><i class="bi bi-trash me-1"></i> Run Cleanup Now</button>
                </div>
                <div class="card-body" id="retentionRunResult">
                    <div class="text-muted small">Click "Run Cleanup Now" to apply all active retention policies.</div>
                </div>
            </div>
            <div class="card shadow-sm border-0">
                <div class="card-header bg-white py-2">
                    <h6 class="mb-0"><i class="bi bi-clock-history me-1"></i> Cleanup History</h6>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table align-middle table-hover table-sm mb-0">
                            <thead class="table-light">
                                <tr><th>Date</th><th>Deleted</th><th>Archived</th><th>Details</th></tr>
                            </thead>
                            <tbody id="retentionLogTable">
                                <tr><td colspan="4" class="text-center text-muted py-3">Loading...</td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Policy Modal -->
<div class="modal fade" id="policyModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title"><span id="policyModalTitle">New Policy</span></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <form id="policyForm">
                <input type="hidden" id="policy_id">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-12"><label class="form-label">Module</label><input type="text" id="policy_module" class="form-control form-control-sm" placeholder="e.g. vehicle_fuel_entry" required></div>
                        <div class="col-12"><label class="form-label">Action (optional)</label><input type="text" id="policy_action" class="form-control form-control-sm" placeholder="Leave blank for all actions"></div>
                        <div class="col-6"><label class="form-label">Retention Days</label><input type="number" id="policy_days" class="form-control form-control-sm" value="365" min="1" required></div>
                        <div class="col-6"><label class="form-label">Action</label><select id="policy_archive_action" class="form-select form-select-sm"><option value="delete">Delete</option><option value="archive">Archive (soft-delete)</option><option value="anonymize">Anonymize</option></select></div>
                    </div>
                </div>
                <div class="modal-footer"><button type="submit" class="btn btn-primary btn-sm">Save Policy</button></div>
            </form>
        </div>
    </div>
</div>
</main>
<?php include 'views/layouts/footer.php'; ?>
