<?php
/**
 * includes/audit.php — Audit logging helper
 *
 * Records user actions to the audit_logs table.
 * Silently fails if the DB is unavailable — never crash the app for a log write.
 */

/**
 * Write an entry to audit_logs.
 *
 * @param string      $action      Short action name, e.g. 'agency.create', 'user.login'
 * @param string      $description Human-readable description of what happened
 * @param int|null    $target_id   The primary-key ID of the affected row (optional)
 * @param string|null $target_type The table/entity type, e.g. 'agency', 'user', 'learner'
 */
function audit_log(
    string  $action,
    string  $description,
    ?int    $target_id   = null,
    ?string $target_type = null
): void {
    try {
        $user_id   = current_user_id() ?: null;
        $ip        = $_SERVER['REMOTE_ADDR'] ?? null;

        $stmt = db()->prepare(
            'INSERT INTO audit_logs
                (user_id, action, description, target_id, target_type, ip_address, created_at)
             VALUES
                (:user_id, :action, :description, :target_id, :target_type, :ip, NOW())'
        );

        $stmt->execute([
            'user_id'     => $user_id,
            'action'      => $action,
            'description' => $description,
            'target_id'   => $target_id,
            'target_type' => $target_type,
            'ip'          => $ip,
        ]);
    } catch (Throwable $e) {
        // Never let a logging failure crash the application
        error_log('audit_log failed: ' . $e->getMessage());
    }
}
