<?php
header('Content-Type: application/json');

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Messaging.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Login required.']);
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();

    $auth = new Auth($conn);
    if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized.']);
        exit;
    }

    $conversationId = (int)($_GET['conversation_id'] ?? 0);
    if (!$conversationId) {
        echo json_encode(['success' => false, 'error' => 'Conversation not found.']);
        exit;
    }

    $messaging = new Messaging($conn);
    $messages = $messaging->getAllMessagesForAdmin($conversationId);

    echo json_encode(['success' => true, 'messages' => $messages]);
} catch (Throwable $e) {
    error_log('Admin messages monitor thread failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Unable to load messages.']);
}
