<?php
declare(strict_types=1);

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';
require_once __DIR__ . '/../system/response.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;
    }

    /* =========================
       INPUT (MATCH list.php)
       ========================= */
    $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 (NO PAGINATION)
       ========================= */
    $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();

    /* =========================
       AUDIT THE EXPORT (BEST EFFORT)
       ========================= */
    try {
        $auditStmt = $pdo->prepare("
            INSERT INTO audit_logs (
                actor_id,
                actor_email,
                actor_role,
                action,
                target_type,
                target_id,
                company_id,
                company_name,
                rsp_id,
                rsp_name,
                ip_address,
                metadata
            ) VALUES (
                :actor_id,
                :actor_email,
                :actor_role,
                'export',
                'audit',
                NULL,
                :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) {
        // Export must never fail due to audit logging
    }

    /* =========================
       CSV OUTPUT
       ========================= */
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="audit_export_' . date('Ymd_His') . '.csv"');

    $out = fopen('php://output', 'w');

    // UTF-8 BOM for Excel compatibility
    fprintf($out, "\xEF\xBB\xBF");

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

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($out, [
            $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']
        ]);
    }

    fclose($out);
    exit;

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