<?php
/**
 * Audit & login-event logging. Mirrors the audit_logs / login_logs tables.
 *
 *   audit_log('user.role.assign', 'user', $userId, $beforeArr, $afterArr);
 *   login_log_attempt($userId, $email, 'success');
 *   download_log($userId, $reportId, $outputId, 'export.xlsx', 'xlsx');
 */

function audit_log(
    string $action,
    string $entityType,
    ?int $entityId = null,
    ?array $before = null,
    ?array $after = null,
    ?int $userId = null,
): void {
    $stmt = db()->prepare(
        'INSERT INTO audit_logs (user_id, action, entity_type, entity_id,
                                 before_json, after_json, ip, user_agent, created_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())'
    );
    $stmt->execute([
        $userId ?? ($_SESSION['uid'] ?? null),
        $action, $entityType, $entityId,
        $before ? json_encode($before, JSON_UNESCAPED_UNICODE) : null,
        $after  ? json_encode($after,  JSON_UNESCAPED_UNICODE) : null,
        $_SERVER['REMOTE_ADDR'] ?? null,
        substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255),
    ]);
}

function login_log_attempt(
    ?int $userId,
    string $emailAttempted,
    string $status,
    ?string $failureReason = null,
): void {
    $stmt = db()->prepare(
        'INSERT INTO login_logs (user_id, email_attempted, ip, user_agent,
                                 status, failure_reason, created_at)
         VALUES (?, ?, ?, ?, ?, ?, NOW())'
    );
    $stmt->execute([
        $userId,
        $emailAttempted,
        $_SERVER['REMOTE_ADDR'] ?? null,
        substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255),
        $status,
        $failureReason ? substr($failureReason, 0, 150) : null,
    ]);
}

function download_log(
    ?int $userId,
    ?int $reportId,
    ?int $outputId,
    string $fileName,
    string $format,
    ?array $filterJson = null,
): void {
    $stmt = db()->prepare(
        'INSERT INTO download_logs (user_id, report_id, output_id, file_name,
                                    format, filter_json, ip, created_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, NOW())'
    );
    $stmt->execute([
        $userId, $reportId, $outputId, $fileName, $format,
        $filterJson ? json_encode($filterJson) : null,
        $_SERVER['REMOTE_ADDR'] ?? null,
    ]);
}
