<?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'] ?? [];
        $dbs      = $summary['databases'] ?? [];
        $dbUsers  = $summary['mysql_users'] ?? [];

        // DB count for the subject; only appended when > 0 so existing-shape
        // emails (no databases) keep the old subject line and downstream
        // mail-rule matchers don't break.
        $dbCount = count($dbs);
        $subject = sprintf(
            'WHP cPanel import for %s — %d mailboxes, %d sites',
            $username, count($mb), $totals['sites'] ?? 0
        );
        if ($dbCount > 0) {
            $subject .= sprintf(', %d databases', $dbCount);
        }

        $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']];
        }

        // Decrypt DB-user temp passwords once, in the same posture as mailboxes.
        $dbUserRows = [];
        foreach ($dbUsers as $u) {
            $pw = '';
            if (!empty($u['temp_password_encrypted'])) {
                try {
                    $pw = CpanelImportSummary::decryptTempPassword($importId, $u['temp_password_encrypted']);
                } catch (Exception $e) {
                    $pw = '(decryption failed)';
                }
            }
            $dbUserRows[] = [
                'original_name' => $u['original_name'] ?? '',
                'whp_name'      => $u['whp_name'] ?? '',
                'host'          => $u['host'] ?? '%',
                'pw'            => $pw,
                'databases'     => is_array($u['databases'] ?? null) ? $u['databases'] : [],
                'status'        => $u['status'] ?? '',
            ];
        }

        // Build database rows. Engine fields are optional — importer doesn't
        // currently track engine-swap state, so they only appear if present.
        $dbRows = [];
        $anyEngine = false;
        foreach ($dbs as $d) {
            $row = [
                'original_name' => $d['original_name'] ?? ($d['name'] ?? ''),
                'whp_name'      => $d['whp_name'] ?? ($d['name'] ?? ''),
                'engine_pre'    => $d['engine_pre']  ?? null,
                'engine_post'   => $d['engine_post'] ?? null,
            ];
            if ($row['engine_pre'] !== null || $row['engine_post'] !== null) {
                $anyEngine = true;
            }
            $dbRows[] = $row;
        }

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

    private static function renderText(
        array $summary, array $rows, array $fwd,
        array $dbRows, array $dbUserRows, bool $anyEngine,
        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[] = "";
        if ($dbRows) {
            $lines[] = "Databases:";
            $lines[] = str_repeat('-', 70);
            if ($anyEngine) {
                foreach ($dbRows as $d) {
                    $engine = $d['engine_post'] ?? ($d['engine_pre'] ?? '-');
                    $lines[] = sprintf('%-30s -> %-30s   [%s]',
                        $d['original_name'], $d['whp_name'], (string)$engine);
                }
            } else {
                foreach ($dbRows as $d) {
                    $lines[] = sprintf('%-30s -> %s',
                        $d['original_name'], $d['whp_name']);
                }
            }
            $lines[] = "";
        }
        if ($dbUserRows) {
            $lines[] = "Database users (temp passwords expire after 24h or when cleared via the results page):";
            $lines[] = str_repeat('-', 70);
            foreach ($dbUserRows as $u) {
                $grantList = $u['databases'] ? implode(', ', $u['databases']) : '(none)';
                $lines[] = sprintf('%-25s -> %-25s @ %-3s   %-34s   grants: %s',
                    $u['original_name'], $u['whp_name'], $u['host'], $u['pw'], $grantList);
            }
            $lines[] = "";
            $lines[] = "Connect string format: mysql -h <panel-host> -u <new user> -p<temp password> <database>";
            $lines[] = "";
        }
        $lines[] = "View / clear credentials / repoint MX: $resultsUrl";
        return implode("\n", $lines) . "\n";
    }

    private static function renderHtml(
        array $summary, array $rows, array $fwd,
        array $dbRows, array $dbUserRows, bool $anyEngine,
        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>
    <?php if ($dbRows): ?>
    <h3>Databases</h3>
    <table cellspacing="0" cellpadding="6" border="1" style="border-collapse:collapse;font-family:ui-monospace,monospace;font-size:13px">
        <tr style="background:#eee">
            <th>Original name</th>
            <th>New name</th>
            <?php if ($anyEngine): ?><th>Engine</th><?php endif; ?>
        </tr>
        <?php foreach ($dbRows as $d): ?>
        <tr>
            <td><?= $h($d['original_name']) ?></td>
            <td><?= $h($d['whp_name']) ?></td>
            <?php if ($anyEngine): ?>
                <td><?= $h((string)($d['engine_post'] ?? $d['engine_pre'] ?? '-')) ?></td>
            <?php endif; ?>
        </tr>
        <?php endforeach; ?>
    </table>
    <?php endif; ?>
    <?php if ($dbUserRows): ?>
    <h3>Database users</h3>
    <p style="color:#a00">Temp passwords expire after 24 h (or when cleared via the results page). Use these to update connection strings in non-WordPress applications — WordPress wp-config files were already rewritten automatically.</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>Original user</th>
            <th>New user</th>
            <th>Host</th>
            <th>Temp password</th>
            <th>Has grants on</th>
        </tr>
        <?php foreach ($dbUserRows as $u): ?>
        <tr>
            <td><?= $h($u['original_name']) ?></td>
            <td><?= $h($u['whp_name']) ?></td>
            <td><?= $h($u['host']) ?></td>
            <td><code><?= $h($u['pw']) ?></code></td>
            <td><?= $u['databases'] ? $h(implode(', ', $u['databases'])) : '<em>(none)</em>' ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
    <?php endif; ?>
    <p><a href="<?= $h($resultsUrl) ?>">View results / clear credentials / repoint MX</a></p>
</body></html>
        <?php
        return (string) ob_get_clean();
    }
}
