<?php
session_start();
require_once '../../config/database.php';
require_once '../../includes/chat_helper.php';
require_once '../../includes/csr_report_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);
$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();
    ensureCsrRoleSchema($db);
    ensureChatTables($db);

    $managerId = (int)$_SESSION['csr_id'];
    if (getCsrRoleForReport($db, $managerId) !== 'csr_manager') {
        echo json_encode(['success' => false, 'message' => 'Only CSR Manager can assign chats from this page.']);
        exit;
    }

    $agentStmt = $db->prepare("SELECT cu.id, CONCAT(cu.first_name, ' ', cu.last_name) AS name,
                                     COALESCE(MIN(t.id), 0) AS team_id,
                                     COALESCE(GROUP_CONCAT(DISTINCT t.team_name ORDER BY t.team_name SEPARATOR ', '), 'No Team') AS team_name
                              FROM csr_users cu
                              LEFT JOIN csr_team_members ctm ON ctm.csr_id = cu.id
                              LEFT JOIN csr_teams t ON t.id = ctm.team_id AND t.is_active = 1
                              WHERE cu.id = :csr_id
                                AND cu.is_active = 1
                                AND COALESCE(cu.role, 'csr') = 'csr'
                              GROUP BY cu.id, cu.first_name, cu.last_name
                              LIMIT 1");
    $agentStmt->execute([':csr_id' => $csr_id]);
    $agent = $agentStmt->fetch(PDO::FETCH_ASSOC);
    if (!$agent) {
        echo json_encode(['success' => false, 'message' => 'Selected agent is not active or does not exist.']);
        exit;
    }

    $conversation = getOrCreateConversation($db, $request_id, null);
    if (!$conversation) {
        echo json_encode(['success' => false, 'message' => 'Conversation not found.']);
        exit;
    }

    $teamId = (int)($agent['team_id'] ?? 0);
    $stmt = $db->prepare("UPDATE chat_conversations
                          SET assigned_team_id = :team_id,
                              assigned_manager_id = :manager_id,
                              assigned_csr_id = :csr_id,
                              csr_id = :csr_id2,
                              assigned_at = NOW(),
                              first_response_at = NULL,
                              assignment_status = 'waiting_first_response',
                              returned_to_queue_at = NULL,
                              assignment_note = :note,
                              updated_at = NOW()
                          WHERE id = :conversation_id");
    $stmt->execute([
        ':team_id' => $teamId > 0 ? $teamId : null,
        ':manager_id' => $managerId,
        ':csr_id' => $csr_id,
        ':csr_id2' => $csr_id,
        ':note' => 'Assigned by CSR Manager to ' . ($agent['name'] ?? 'CSR'),
        ':conversation_id' => (int)$conversation['id']
    ]);

    addChatMessage($db, (int)$conversation['id'], $request_id, 'system', null, 'CSR Manager assigned this chat to ' . ($agent['name'] ?? 'CSR') . '.', 'system', true);
    createCsrNotificationForOne($db, $csr_id, $request_id, 'Chat Assigned', 'CSR Manager assigned a customer chat to you.', 'primary');

    echo json_encode([
        'success' => true,
        'message' => 'Chat assigned successfully.',
        'assignment' => getChatAssignmentInfo($db, $request_id, $managerId)
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
