<?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)($_POST['account_id'] ?? 0);
    $uid = (int)($_POST['uid'] ?? 0);
    $folder = trim($_POST['folder'] ?? 'INBOX');
    if ($accountId <= 0) {
        echo json_encode(['success' => false, 'error' => 'No mailbox account selected.']);
        exit;
    }
    if ($uid <= 0) {
        echo json_encode(['success' => false, 'error' => 'Invalid message id.']);
        exit;
    }

    $mailboxService = new MailboxService($conn, $accountId);
    $mailboxService->deleteMessage($uid, $folder);

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