<?php
// GET ?import_id=... -> JSON summary for the results page.
// Decrypts mailbox temp passwords for the response (the page renders masked,
// reveals on click). The summary file on disk stays encrypted.

require_once('../auto-prepend.php');
require_once('../libs/CpanelImportSummary.php');
require_once('../libs/mysqlmgmt.php');

if (!defined('AUTH_USER')) {
    http_response_code(401); header('Content-Type: application/json');
    echo json_encode(['error' => 'Not authenticated']); exit;
}
header('Content-Type: application/json');

$importId = $_GET['import_id'] ?? '';
if (!preg_match('/^import_[A-Za-z0-9]+$/', $importId)) {
    http_response_code(400); echo json_encode(['error' => 'invalid import_id']); exit;
}

$pdo = (new mysqlmgmt())->getMySQLConnection();
$pdo->exec('USE whp');
$stmt = $pdo->prepare('SELECT username FROM cpanel_imports WHERE import_id = ?');
$stmt->execute([$importId]);
$owner = $stmt->fetchColumn();
if (!$owner || ($owner !== AUTH_USER && AUTH_USER !== 'root')) {
    http_response_code(403); echo json_encode(['error' => 'forbidden']); exit;
}

$summary = CpanelImportSummary::readSummary($importId);
if ($summary === null) {
    http_response_code(404); echo json_encode(['error' => 'summary not found (may have been swept)']); exit;
}

// Decrypt for the response. KEY GOTCHA: do NOT use `?? [] as &$mb`. PHP's
// null-coalesce produces a temporary, by-ref iter mutates the temp, and the
// real $summary['mailboxes'] never changes. Same bug we caught in Task 8.
if (isset($summary['mailboxes']) && is_array($summary['mailboxes'])) {
    foreach ($summary['mailboxes'] as &$mb) {
        if (!empty($mb['temp_password_encrypted'])) {
            try {
                $mb['temp_password'] = CpanelImportSummary::decryptTempPassword($importId, $mb['temp_password_encrypted']);
            } catch (Exception $e) {
                $mb['temp_password'] = null;
                $mb['decrypt_error'] = $e->getMessage();
            }
        }
        unset($mb['temp_password_encrypted']); // never send the ciphertext to the browser
    }
    unset($mb);
}

echo json_encode($summary);
