<?php
require_once 'helpers/audit_trail.php';
error_reporting(0);
function logAndRespond($user_id, $user_type, $endpoint, $response, $method = 'GET', $params = []) {
    global $auditController;

    if (is_array($response)) {
        $status = ($response['status'] ?? '') === 'success' ? 200 : 400;
    } else {
        $decoded = json_decode($response, true);
        $status = ($decoded['status'] ?? '') === 'success' ? 200 : 400;
    }
    http_response_code($status);
    header('Content-Type: application/json');
    echo is_array($response) ? json_encode($response) : $response;

    logAction($user_id, $user_type, $auditController, $endpoint, $method, $params, $response, $status);
    exit;
}

function logPublicResponse($endpoint, $method, $params, $response, $status = 200) {
    global $auditController;

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

    logAction(null, 'public', $auditController, $endpoint, $method, $params, $response, $status);
    exit;
}


function handleWithAudit($user_id, $user_type, $controllerFunc, $endpoint, $method, $requestData = [], $status = 200) {
    global $auditController;

    $response = call_user_func($controllerFunc, $requestData);
    http_response_code($status);
    logAction($user_id, $user_type, $auditController, $endpoint, $method, $requestData, $response, $status);
    header('Content-Type: application/json');
    echo is_array($response) ? json_encode($response) : $response;
    exit;
}

// ✅ Helper to log and respond
function auditAndRespond($user_id, $user_type, $endpoint, $method, $input, $response, $status = 200) {
    global $auditController;
    http_response_code($status);
    header('Content-Type: application/json');
    echo is_array($response) ? json_encode($response) : $response;

    logAction($user_id, $user_type, $auditController, $endpoint, $method, $input, $response, $status);
    exit;
}


function handleRegistrationAudit($user_id, $user_type, $endpoint, $method, $controllerCallback) {
    global $auditController;
    $input = json_decode(file_get_contents('php://input'), true);

    // Call the controller method
    $rawResponse = call_user_func($controllerCallback, $input);

    // Decode if it's a JSON string
    $response = is_array($rawResponse) ? $rawResponse : json_decode($rawResponse, true);

    // Determine HTTP status code
    $status = (isset($response['status']) && $response['status'] === 'success') ? 200 : 400;

    // Set response code and log
    http_response_code($status);
    logAction($user_id, $user_type, $auditController, $endpoint, $method, $input, $response, $status);

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