<?php
// web-files/libs/CpanelImportEmailTemplate.php
//
// Renders the post-cPanel-import summary email body. Decrypts each mailbox's
// temp password just before render, so the template is the only spot in the
// codebase where plaintexts hit a string buffer.

require_once __DIR__ . '/CpanelImportSummary.php';

class CpanelImportEmailTemplate {

    /** Returns ['subject' => ..., 'html' => ..., 'text' => ...] */
    public static function render(array $summary, string $resultsUrl): array {
        $importId = $summary['import_id'];
        $username = $summary['username'] ?? 'unknown';
        $totals   = $summary['totals'] ?? [];
        $mb       = $summary['mailboxes'] ?? [];
        $fwd      = $summary['forwarders'] ?? [];

        $subject = sprintf(
            'WHP cPanel import for %s — %d mailboxes, %d sites',
            $username, count($mb), $totals['sites'] ?? 0
        );

        $rows = [];
        foreach ($mb as $m) {
            $pw = '';
            if (!empty($m['temp_password_encrypted'])) {
                try {
                    $pw = CpanelImportSummary::decryptTempPassword($importId, $m['temp_password_encrypted']);
                } catch (Exception $e) {
                    $pw = '(decryption failed)';
                }
            }
            $rows[] = ['email' => $m['email'], 'quota' => $m['quota_mb'] ?? '-', 'pw' => $pw, 'status' => $m['status']];
        }

        $text = self::renderText($summary, $rows, $fwd, $resultsUrl);
        $html = self::renderHtml($summary, $rows, $fwd, $resultsUrl);
        return ['subject' => $subject, 'html' => $html, 'text' => $text];
    }

    private static function renderText(array $summary, array $rows, array $fwd, string $resultsUrl): string {
        $lines = [];
        $lines[] = "WHP cPanel import complete";
        $lines[] = str_repeat('=', 26);
        $lines[] = "";
        $lines[] = "Username:       " . ($summary['username'] ?? '-');
        $lines[] = "Import ID:      " . $summary['import_id'];
        $lines[] = "Completed at:   " . ($summary['completed_at'] ?? '-');
        $lines[] = "";
        $t = $summary['totals'] ?? [];
        $lines[] = sprintf('Sites: %d   Databases: %d   Mailboxes: %d   Forwarders: %d',
            $t['sites'] ?? 0, $t['databases'] ?? 0, $t['mailboxes'] ?? 0, $t['forwarders'] ?? 0);
        $lines[] = "";
        $lines[] = "Mailboxes (temp passwords expire in 24h or when cleared via the results page):";
        $lines[] = str_repeat('-', 70);
        foreach ($rows as $r) {
            $lines[] = sprintf('%-40s %5s MB   %s   %s',
                $r['email'], (string)$r['quota'], $r['status'], $r['pw']);
        }
        $lines[] = "";
        $lines[] = "Forwarders:";
        $lines[] = str_repeat('-', 70);
        foreach ($fwd as $f) {
            $lines[] = sprintf('%-40s -> %s   [%s]',
                $f['source'], implode(', ', $f['targets']), $f['status']);
        }
        $lines[] = "";
        $lines[] = "View / clear credentials / repoint MX: $resultsUrl";
        return implode("\n", $lines) . "\n";
    }

    private static function renderHtml(array $summary, array $rows, array $fwd, string $resultsUrl): string {
        $h = function (string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); };
        $t = $summary['totals'] ?? [];
        ob_start();
        ?>
<html><body style="font-family:system-ui,sans-serif;max-width:800px;margin:auto">
    <h2>WHP cPanel import complete</h2>
    <p>
        <strong>Username:</strong> <?= $h($summary['username'] ?? '-') ?><br>
        <strong>Import ID:</strong> <?= $h($summary['import_id']) ?><br>
        <strong>Completed at:</strong> <?= $h($summary['completed_at'] ?? '-') ?>
    </p>
    <p>
        Sites: <strong><?= (int)($t['sites'] ?? 0) ?></strong>,
        Databases: <strong><?= (int)($t['databases'] ?? 0) ?></strong>,
        Mailboxes: <strong><?= (int)($t['mailboxes'] ?? 0) ?></strong>,
        Forwarders: <strong><?= (int)($t['forwarders'] ?? 0) ?></strong>
    </p>
    <h3>Mailboxes</h3>
    <p style="color:#a00">Temp passwords expire after 24 h (or when cleared via the results page).</p>
    <table cellspacing="0" cellpadding="6" border="1" style="border-collapse:collapse;font-family:ui-monospace,monospace;font-size:13px">
        <tr style="background:#eee"><th>Email</th><th>Quota MB</th><th>Status</th><th>Temp password</th></tr>
        <?php foreach ($rows as $r): ?>
        <tr><td><?= $h($r['email']) ?></td><td><?= $h((string)$r['quota']) ?></td><td><?= $h($r['status']) ?></td><td><code><?= $h($r['pw']) ?></code></td></tr>
        <?php endforeach; ?>
    </table>
    <h3>Forwarders</h3>
    <table cellspacing="0" cellpadding="6" border="1" style="border-collapse:collapse;font-size:13px">
        <tr style="background:#eee"><th>Source</th><th>→</th><th>Targets</th><th>Status</th></tr>
        <?php foreach ($fwd as $f): ?>
        <tr><td><?= $h($f['source']) ?></td><td>→</td><td><?= $h(implode(', ', $f['targets'])) ?></td><td><?= $h($f['status']) ?></td></tr>
        <?php endforeach; ?>
    </table>
    <p><a href="<?= $h($resultsUrl) ?>">View results / clear credentials / repoint MX</a></p>
</body></html>
        <?php
        return (string) ob_get_clean();
    }
}
