<?php
// ---------------------------------------------------------------
// CLOSURE REQUESTS ROUTES
// ---------------------------------------------------------------
require_once 'controllers/ClosureRequestsController.php';

$closureController = new ClosureRequestsController();

// CREATE
if ($method === 'POST' && $uri === '/closure-requests') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_role = $decoded->user_type ?? null;
    $data = json_decode(file_get_contents('php://input'), true) ?? [];
    $response = $closureController->create($data, $user_id);
    logAndRespond($user_id, $user_role, '/closure-requests', $response, 'POST', $data);
}

// LIST
if ($method === 'GET' && $uri === '/closure-requests') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_role = $decoded->user_type ?? null;
    $user_role_id = $_GET['user_role_id'] ?? null;

    $filters = $_GET;
    $response = $closureController->getList($user_id, $user_role_id, $filters);
    logAndRespond($user_id, $user_role, '/closure-requests', $response, 'GET', $_GET);
}

// GET ONE
if ($method === 'GET' && $uri === '/closure-request') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_role = $decoded->user_type ?? null;
    $user_role_id = $_GET['user_role_id'] ?? null;
    $id = $_GET['id'] ?? null;

    $response = $closureController->getOne($id, $user_id, $user_role_id);
    logAndRespond($user_id, $user_role, "/closure-request?id={$id}", $response, 'GET', []);
}

// REVIEW
if ($method === 'POST' && $uri === '/closure-review') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_role = $decoded->user_type ?? null;
    $user_name = $decoded->name ?? 'Unknown';
    $id = $_GET['id'] ?? null;

    $data = json_decode(file_get_contents('php://input'), true) ?? [];
    $response = $closureController->review($id, $data, $user_id, $user_name);
    logAndRespond($user_id, $user_role, "/closure-review?id={$id}", $response, 'POST', $data);
}

// BULK APPROVE
if ($method === 'POST' && $uri === '/closure-bulk-approve') {
    $decoded = authenticate();
    $user_id = $decoded->user_id ?? null;
    $user_role = $decoded->user_type ?? null;
    $user_name = $decoded->name ?? 'Unknown';

    $data = json_decode(file_get_contents('php://input'), true) ?? [];
    $ids = $data['ids'] ?? [];
    $comments = $data['comments'] ?? '';

    $response = $closureController->bulkApprove($ids, $comments, $user_id, $user_name);
    logAndRespond($user_id, $user_role, '/closure-bulk-approve', $response, 'POST', $data);
}