<?php
// routes.php
require_once 'controllers/UsersController.php';
require_once 'helpers/auth_helper.php';
require_once 'helpers/audit_trail.php';
require_once 'helpers/response_helper.php';

$usersController = new UsersController();

// Authenticate for all other routes

// User Management Routes
if ($method === 'POST' && $uri === '/users') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $data = json_decode(file_get_contents('php://input'), true);
    $response = $usersController->createUser($data);
    logAndRespond($user_id, $user_type, '/users', $response, 'POST', $data);
}
if ($method === 'GET' && $uri === '/get-users') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $response = $usersController->getAllUsers($_GET);
    logAndRespond($user_id, $user_type, '/get-users', $response, 'GET', $_GET);
}

if ($method === 'GET' && $uri === '/get-user') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $response = $usersController->getUserById($_GET['id']);
    logAndRespond($user_id, $user_type, '/get-user', $response, 'GET', $_GET['id']);
}

if ($method === 'PUT' && $uri === '/update-user') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $userId = $_GET['id'];
    $data = json_decode(file_get_contents('php://input'), true);
    $data['id'] = $userId;
    $response = $usersController->updateUser($data);
    logAndRespond($user_id, $user_type, $uri, $response, 'PUT', $data);
}

if ($method === 'POST' && $uri === '/toggle-status') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $userId = $_GET['id'];
    $data = ['id' => $userId];
    $response = $usersController->toggleUserStatus($data);
    logAndRespond($user_id, $user_type, $uri, $response, 'POST', $data);
}

if ($method === 'GET' && $uri === '/get-users-statistics') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_type = $decoded->user_type ?? null;
    $response = $usersController->getUsersStatistics();
    logAndRespond($user_id, $user_type, 'get-users-statistics', $response, 'GET', []);
}
?>