<?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)($_GET['request_id'] ?? 0);
$last_id = (int)($_GET['last_id'] ?? 0);

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

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

    $stmt = $db->prepare("SELECT cm.*, CONCAT(cu.first_name, ' ', cu.last_name) AS csr_name
                          FROM chat_messages cm
                          LEFT JOIN csr_users cu ON cm.sender_type = 'csr' AND cu.id = cm.sender_id
                          WHERE cm.conversation_id = :conversation_id AND cm.id > :last_id
                          ORDER BY cm.created_at ASC, cm.id ASC");
    $stmt->bindValue(':conversation_id', (int)$conversation['id'], PDO::PARAM_INT);
    $stmt->bindValue(':last_id', $last_id, PDO::PARAM_INT);
    $stmt->execute();
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $db->prepare("UPDATE chat_conversations SET last_csr_read_at = NOW() WHERE id = :id")
       ->execute([':id' => $conversation['id']]);

    $assignment = getChatAssignmentInfo($db, $request_id, (int)$_SESSION['csr_id']);

    echo json_encode([
        'success' => true,
        'messages' => $messages,
        'assignment' => $assignment
    ]);
} catch(Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
