<?php
session_start();
require_once '../../config/database.php';
require_once 'csr_request_lock_helper.php';
require_once '../../includes/app_helpers.php';
header('Content-Type: application/json');

if (!isset($_SESSION['csr_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$request_id = (int)($_POST['request_id'] ?? 0);
if (!$request_id) {
    echo json_encode(['success' => false, 'message' => 'Missing request ID.']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    ensureRequestLockTable($db);
    ensureOperationalTables($db);
    ensureCsrTeamTables($db);
    requireCsrRequestAccessJson($db, (int)$_SESSION['csr_id'], $request_id);

    $stmt = $db->prepare("SELECT id, request_number FROM service_requests WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $request_id]);
    $request = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$request) {
        echo json_encode(['success' => false, 'message' => 'Request not found.']);
        exit;
    }

    $csr_name = getCurrentCSRName($db, $_SESSION['csr_id']);
    $result = acquireRequestLock($db, $request_id, $_SESSION['csr_id'], $csr_name);
    if (!$result['success']) {
        echo json_encode($result);
        exit;
    }

    logRequestAction($db, $request_id, $_SESSION['csr_id'], 'csr', 'request_claimed', null, $csr_name, 'CSR clicked Manage');
    logCSRActivity($db, $_SESSION['csr_id'], 'request_claimed', $request_id, 'Claimed request #' . $request['request_number']);

    echo json_encode(['success' => true, 'message' => 'You are now managing this request.', 'managed_by' => $csr_name]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Failed to manage request: ' . $e->getMessage()]);
}
?>
