<?php
// function logAction($user_id, $user_type, $endpoint, $response, $method, $data) {
//     $log = [
//         'user_id' => $user_id,
//         'user_type' => $user_type,
//         'endpoint' => $endpoint,
//         'method' => $method,
//         'data' => $data,
//         'response_status' => json_decode($response, true)['status'] ?? 'unknown',
//         'time' => date('Y-m-d H:i:s')
//     ];
//     file_put_contents('audit.log', json_encode($log) . PHP_EOL, FILE_APPEND);
// }

function logAction($user_id, $user_type, $controller, $endpoint, $method, $requestData, $responseData, $statusCode) {
    $payload = [
        'user_id' => $user_id ?? null,
        'user_type' => $user_type ?? null,
        'endpoint' => $endpoint,
        'method' => $method,
        'request_payload' => is_array($requestData) || is_object($requestData)
            ? json_encode($requestData)
            : (string) $requestData,
        'response_payload' => is_array($responseData) || is_object($responseData)
            ? json_encode($responseData)
            : (string) $responseData,
        'status_code' => $statusCode,
        'ip_address' => filter_var($_SERVER['REMOTE_ADDR'] ?? '', FILTER_VALIDATE_IP),
        'user_agent' => htmlspecialchars($_SERVER['HTTP_USER_AGENT'] ?? '', ENT_QUOTES, 'UTF-8')
    ];

    $controller->logApiRequest($payload);
}


function handleApiWithAudit($user_id, $user_type, $controllerFunc, $auditController, $endpoint, $method = null) {
    $method = $method ?? $_SERVER['REQUEST_METHOD'];
    $requestData = ($method === 'GET') ? $_GET : (json_decode(file_get_contents("php://input"), true) ?? []);
    
    $response = call_user_func($controllerFunc, $requestData);
    $statusCode = (isset($response['message']) && stripos($response['message'], 'error') !== false) ? 400 : 200;

    logAction($user_id, $user_type, $auditController, $endpoint, $method, $requestData, $response, $statusCode);

    header('Content-Type: application/json');
    echo is_array($response) ? json_encode($response) : $response;
    exit;
}

?>