<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/iscms_layout.php';

$conn = iscms_init();
iscms_require_roles(['SUPER_ADMIN', 'ADMIN']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'export_audit_csv') {
    if (!iscms_csrf_validate($_POST['csrf_token'] ?? null)) {
        http_response_code(403);
        header('Content-Type: text/plain; charset=UTF-8');
        echo 'Invalid security token.';
        exit;
    }
    $fn = 'audit_export_' . date('Y-m-d_His') . '.csv';
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $fn . '"');
    $out = fopen('php://output', 'w');
    if ($out === false) {
        exit;
    }
    fputcsv($out, ['created_at', 'user_id', 'action', 'module', 'entity_type', 'entity_id', 'ip_address', 'request_method', 'request_path']);
    $sql = "SELECT created_at, user_id, action, module, entity_type, entity_id, ip_address, request_method, request_path
            FROM audit_logs ORDER BY created_at DESC LIMIT 5000";
    $res = $conn->query($sql);
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            fputcsv($out, [
                (string) ($row['created_at'] ?? ''),
                (string) ($row['user_id'] ?? ''),
                (string) ($row['action'] ?? ''),
                (string) ($row['module'] ?? ''),
                (string) ($row['entity_type'] ?? ''),
                (string) ($row['entity_id'] ?? ''),
                (string) ($row['ip_address'] ?? ''),
                (string) ($row['request_method'] ?? ''),
                (string) ($row['request_path'] ?? ''),
            ]);
        }
    }
    fclose($out);
    exit;
}

$pageTitle = 'Backup and restore';
$activeNav = 'settings';
$csrf = iscms_csrf_token();

iscms_render_head($pageTitle);
iscms_render_sidebar($activeNav);
iscms_render_topbar($pageTitle);
?>
    <div class="page-header">
        <h1>Backup and restore</h1>
        <p>Database and file backups are normally run on the server or hosting control panel.</p>
    </div>

    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-links-line"></i> Administration</h2>
        </div>
        <div class="quick-actions">
            <a class="qa-btn" href="settings.php"><i class="ri-settings-3-line"></i> System settings editor</a>
            <a class="qa-btn" href="audit_logs.php"><i class="ri-file-code-line"></i> Audit logs</a>
            <a class="qa-btn" href="database_export.php"><i class="ri-file-excel-2-line"></i> Database export</a>
        </div>
    </div>

    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-download-2-line"></i> Export</h2>
        </div>
        <div class="p-3" style="font-size:.9rem">
            <p class="text-muted mb-2">Download the latest 5,000 audit log rows as CSV (for offline retention or analysis). This is not a full database backup.</p>
            <form method="post" action="backup_restore.php">
                <input type="hidden" name="csrf_token" value="<?= iscms_h($csrf) ?>">
                <input type="hidden" name="action" value="export_audit_csv">
                <button type="submit" class="btn btn-sm btn-outline-primary"><i class="ri-file-excel-2-line me-1"></i>Export audit CSV</button>
            </form>
        </div>
    </div>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-database-2-line"></i> Guidance</h2>
        </div>
        <div class="p-3" style="font-size:.9rem; line-height:1.6; color:#374151">
            <p class="mb-2">Production backup policy should include:</p>
            <ul class="mb-0">
                <li>Scheduled logical dumps of the MySQL database (e.g. <code class="iscms-mono">mysqldump</code>).</li>
                <li>Secure off-site storage of dumps and uploaded documents (<code>file_path</code> columns across modules).</li>
                <li>Tested restore drills on a non-production instance.</li>
            </ul>
        </div>
    </div>
<?php
iscms_render_footer();
