<?php
require_once '../system/bootstrap.php';
require_auth($pdo);

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="audit_export.csv"');

$params = [];
$where  = [];

if (!empty($_GET['date_from'])) {
    $where[] = 'created_at >= :date_from';
    $params[':date_from'] = $_GET['date_from'] . ' 00:00:00';
}

if (!empty($_GET['date_to'])) {
    $where[] = 'created_at <= :date_to';
    $params[':date_to'] = $_GET['date_to'] . ' 23:59:59';
}

$sql = "
    SELECT
        created_at,
        action,
        actor_user_id,
        target_user_id,
        company_id,
        ip_address,
        browser,
        operating_system
    FROM audit_logs
";

if ($where) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}

$sql .= ' ORDER BY created_at ASC';

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* =========================
   GENERATE CSV IN MEMORY
   ========================= */
$fp = fopen('php://temp', 'r+');

fputcsv($fp, array_keys($rows[0] ?? [
    'created_at','action','actor_user_id','target_user_id',
    'company_id','ip_address','browser','operating_system'
]));

foreach ($rows as $row) {
    fputcsv($fp, $row);
}

rewind($fp);
$csvData = stream_get_contents($fp);
fclose($fp);

/* =========================
   SIGN EXPORT (SHA-256)
   ========================= */
$hash = hash('sha256', $csvData);

/* =========================
   STORE HASH (IMMUTABLE)
   ========================= */
$insert = $pdo->prepare("
    INSERT INTO audit_export_hashes
        (exported_by_user_id, export_hash, record_count, date_from, date_to)
    VALUES
        (:user, :hash, :count, :date_from, :date_to)
");

$insert->execute([
    ':user'      => $_SESSION['user_id'],
    ':hash'      => $hash,
    ':count'     => count($rows),
    ':date_from' => $_GET['date_from'] ?? null,
    ':date_to'   => $_GET['date_to'] ?? null
]);

/* =========================
   OPTIONAL AUDIT ENTRY
   ========================= */
if (function_exists('audit_log')) {
    audit_log(
        $pdo,
        'audit_export',
        null,
        null
    );
}

/* =========================
   OUTPUT CSV + HASH HEADER
   ========================= */
header('X-Audit-Export-Hash: ' . $hash);
echo $csvData;
exit;
