<?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;
    }

    $messaging = new Messaging($conn);
    $conversations = $messaging->getAllConversationsForAdmin();

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