<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$allowedTypes = ['master', 'manager', 'accounts'];
$currentType = strtolower(trim((string)($_SESSION['type'] ?? '')));

if (!in_array($currentType, $allowedTypes, true)) {
    http_response_code(403);
    exit('You are not allowed to export audit logs.');
}

$orderId = (int)($_GET['order_id'] ?? 0);
if ($orderId <= 0) {
    exit('Invalid order.');
}

/*
   If your auth table is not `users`, change this join.
   Example alternatives:
   - LEFT JOIN tbluser u ON u.id = l.action_by
   - LEFT JOIN staff u ON u.id = l.action_by
*/
$stmt = $pdo->prepare("
    SELECT
        l.*,
        COALESCE(
            NULLIF(TRIM(CONCAT(COALESCE(u.firstname,''), ' ', COALESCE(u.lastname,''))), ''),
            NULLIF(u.firstname, ''),
            CONCAT('User #', COALESCE(l.action_by, 0))
        ) AS action_by_name
    FROM payment_audit_log l
    LEFT JOIN users u ON u.id = l.action_by
    WHERE l.order_id = :order_id
    ORDER BY l.action_at DESC, l.id DESC
");
$stmt->execute([':order_id' => $orderId]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$filename = 'audit_log_order_' . $orderId . '_' . date('Ymd_His') . '.csv';

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');

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

fputcsv($out, [
    'ID',
    'Action Date',
    'Action Type',
    'Reason',
    'Done By',
    'User Type',
    'Property ID',
    'Order ID',
    'Folio ID',
    'Payment ID',
    'Folio Transaction ID',
    'Payload JSON'
]);

foreach ($rows as $row) {
    fputcsv($out, [
        (int)($row['id'] ?? 0),
        (string)($row['action_at'] ?? ''),
        (string)($row['action_type'] ?? ''),
        (string)($row['action_reason'] ?? ''),
        (string)($row['action_by_name'] ?? ''),
        (string)($row['action_by_type'] ?? ''),
        (int)($row['property_id'] ?? 0),
        (int)($row['order_id'] ?? 0),
        (int)($row['folio_id'] ?? 0),
        (int)($row['payment_id'] ?? 0),
        (int)($row['folio_transaction_id'] ?? 0),
        (string)($row['payload_json'] ?? ''),
    ]);
}

fclose($out);
exit;