<?php
declare(strict_types=1);

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';

try {
    /* =========================
       AUTH
       ========================= */
    $user = require_auth($pdo);
    $role = strtolower((string)$user['role_key']);

    if (!in_array($role, ['super_admin', 'platform_admin', 'rsp_admin', 'company_admin'], true)) {
        http_response_code(403);
        exit;
    }

    /* =========================
       FILTERS (SAME AS EXPORT)
       ========================= */
    $filters = [
        'actor'       => trim((string)($_GET['actor'] ?? '')),
        'action'      => trim((string)($_GET['action'] ?? '')),
        'target_type' => trim((string)($_GET['target_type'] ?? '')),
        'from'        => trim((string)($_GET['from'] ?? '')),
        'to'          => trim((string)($_GET['to'] ?? '')),
    ];

    /* =========================
       WHERE + PARAMS
       ========================= */
    $where = [];
    $params = [];

    if ($role === 'rsp_admin') {
        $where[] = 'rsp_id = :rsp_id';
        $params[':rsp_id'] = (int)$user['rsp_id'];
    }

    if ($role === 'company_admin') {
        $where[] = 'company_id = :company_id';
        $params[':company_id'] = (int)$user['company_id'];
    }

    if ($filters['actor'] !== '') {
        $where[] = 'actor_email LIKE :actor';
        $params[':actor'] = '%' . $filters['actor'] . '%';
    }

    if ($filters['action'] !== '') {
        $where[] = 'action = :action';
        $params[':action'] = $filters['action'];
    }

    if ($filters['target_type'] !== '') {
        $where[] = 'target_type = :target_type';
        $params[':target_type'] = $filters['target_type'];
    }

    if ($filters['from'] !== '') {
        $where[] = 'created_at >= :from_date';
        $params[':from_date'] = $filters['from'] . ' 00:00:00';
    }

    if ($filters['to'] !== '') {
        $where[] = 'created_at <= :to_date';
        $params[':to_date'] = $filters['to'] . ' 23:59:59';
    }

    $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

    /* =========================
       QUERY
       ========================= */
    $stmt = $pdo->prepare("
        SELECT
            created_at,
            action,
            actor_email,
            actor_role,
            target_type,
            target_id,
            company_name,
            rsp_name,
            ip_address,
            metadata
        FROM audit_logs
        $whereSql
        ORDER BY created_at DESC
    ");

    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v);
    }

    $stmt->execute();

    /* =========================
       TEMP ZIP FILE
       ========================= */
    $tmpZip = tempnam(sys_get_temp_dir(), 'audit_bundle_');
    $zip = new ZipArchive();

    if ($zip->open($tmpZip, ZipArchive::OVERWRITE) !== true) {
        http_response_code(500);
        exit;
    }

    /* =========================
       CSV CONTENT
       ========================= */
    $csv = fopen('php://temp', 'r+');
    fprintf($csv, "\xEF\xBB\xBF");

    fputcsv($csv, [
        'Date',
        'Action',
        'Actor Email',
        'Actor Role',
        'Target Type',
        'Target ID',
        'Company',
        'RSP',
        'IP Address',
        'Metadata'
    ]);

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($csv, [
            $row['created_at'],
            $row['action'],
            $row['actor_email'],
            $row['actor_role'],
            $row['target_type'],
            $row['target_id'],
            $row['company_name'],
            $row['rsp_name'],
            $row['ip_address'],
            $row['metadata']
        ]);
    }

    rewind($csv);
    $zip->addFromString('audit_logs.csv', stream_get_contents($csv));
    fclose($csv);

    /* =========================
       MANIFEST
       ========================= */
    $manifest = [
        'generated_at' => date('c'),
        'generated_by' => [
            'id'    => $user['id'],
            'email' => $user['email'],
            'role'  => $user['role_key'],
        ],
        'scope' => [
            'company_id' => $user['company_id'] ?? null,
            'rsp_id'     => $user['rsp_id'] ?? null,
        ],
        'filters' => $filters,
        'system' => 'TechStackBase Audit Evidence Bundle'
    ];

    $zip->addFromString(
        'manifest.json',
        json_encode($manifest, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)
    );

    /* =========================
       README
       ========================= */
    $zip->addFromString('README.txt',
        "TechStackBase Audit Evidence Bundle\n\n" .
        "This archive contains an immutable export of audit logs\n" .
        "generated for compliance, investigation, or legal review.\n\n" .
        "Files:\n" .
        "- audit_logs.csv : Raw audit events\n" .
        "- manifest.json  : Generation context and scope\n\n" .
        "Generated at: {$manifest['generated_at']}\n"
    );

    $zip->close();

    /* =========================
       AUDIT THE EXPORT (BEST EFFORT)
       ========================= */
    try {
        $auditStmt = $pdo->prepare("
            INSERT INTO audit_logs (
                actor_id, actor_email, actor_role,
                action, target_type,
                company_id, company_name,
                rsp_id, rsp_name,
                ip_address, metadata
            ) VALUES (
                :actor_id, :actor_email, :actor_role,
                'export', 'audit_bundle',
                :company_id, :company_name,
                :rsp_id, :rsp_name,
                :ip_address, :metadata
            )
        ");

        $auditStmt->execute([
            ':actor_id'     => (int)$user['id'],
            ':actor_email'  => (string)$user['email'],
            ':actor_role'   => (string)$user['role_key'],
            ':company_id'   => $user['company_id'] ?? null,
            ':company_name' => $user['company_name'] ?? null,
            ':rsp_id'       => $user['rsp_id'] ?? null,
            ':rsp_name'     => $user['rsp_name'] ?? null,
            ':ip_address'   => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            ':metadata'     => json_encode(['filters' => $filters], JSON_THROW_ON_ERROR)
        ]);
    } catch (Throwable $ignored) {}

    /* =========================
       STREAM ZIP
       ========================= */
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="audit_evidence_bundle_' . date('Ymd_His') . '.zip"');
    header('Content-Length: ' . filesize($tmpZip));

    readfile($tmpZip);
    unlink($tmpZip);
    exit;

} catch (Throwable $e) {
    http_response_code(500);
    exit;
}
