<?php
session_start();
require_once '../../config/database.php';
require_once '../../includes/chat_helper.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);
$csr_id = (int)($_POST['csr_id'] ?? 0);
if (!$request_id || !$csr_id) {
    echo json_encode(['success' => false, 'message' => 'Request and CSR are required.']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    ensureChatTables($db);

    if (!isCsrManagerForChat($db, (int)$_SESSION['csr_id'])) {
        echo json_encode(['success' => false, 'message' => 'Only CSR Managers / Team Leaders can assign team chats.']);
        exit;
    }

    $result = assignConversationToTeamCsr($db, $request_id, (int)$_SESSION['csr_id'], $csr_id);
    if ($result['success']) {
        $result['assignment'] = getChatAssignmentInfo($db, $request_id, (int)$_SESSION['csr_id']);
    }
    echo json_encode($result);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
