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

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/MailboxService.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;
    }

    $accountId = (int)($_GET['account_id'] ?? 0);
    if ($accountId <= 0) {
        echo json_encode(['success' => false, 'error' => 'No mailbox account selected.']);
        exit;
    }

    $mailboxService = new MailboxService($conn, $accountId);
    $folders = $mailboxService->listFolders();

    echo json_encode(['success' => true, 'folders' => $folders]);
} catch (Throwable $e) {
    error_log('Mailbox list folders failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
