<?php
if (!defined('AUTH_USER')) { header('Location: login.php'); exit(); }
$pageTitle  = 'cPanel Import Results';
$currentPage = 'cpanel-import-results';

$importId = $_GET['import_id'] ?? '';
if (!preg_match('/^import_[A-Za-z0-9]+$/', $importId)) {
    echo '<div class="alert alert-danger">Invalid import_id.</div>';
    return;
}
?>
<div class="container-fluid" data-import-id="<?= htmlspecialchars($importId) ?>">
    <div id="results-loading" class="alert alert-info">Loading import results…</div>
    <div id="results-error" class="alert alert-danger d-none"></div>

    <div id="results-body" class="d-none">
        <div class="row mb-4">
            <div class="col-md-3"><div class="card text-center"><div class="card-body"><h3 id="totals-sites">–</h3><div class="text-muted">Sites</div></div></div></div>
            <div class="col-md-3"><div class="card text-center"><div class="card-body"><h3 id="totals-databases">–</h3><div class="text-muted">Databases</div></div></div></div>
            <div class="col-md-3"><div class="card text-center"><div class="card-body"><h3 id="totals-mailboxes">–</h3><div class="text-muted">Mailboxes</div></div></div></div>
            <div class="col-md-3"><div class="card text-center"><div class="card-body"><h3 id="totals-forwarders">–</h3><div class="text-muted">Forwarders</div></div></div></div>
        </div>

        <div id="mx-panel" class="alert alert-warning d-none">
            <h6><i class="bi bi-arrow-repeat"></i> MX records were preserved</h6>
            <p class="mb-2">The imported domain(s) currently route mail to: <code id="mx-current-target">–</code>. The cPanel backup did not point at WHP's mail server. What would you like to do?</p>
            <button type="button" class="btn btn-primary btn-sm" id="mx-repoint">Repoint MX to WHP mail server</button>
            <button type="button" class="btn btn-outline-secondary btn-sm" id="mx-dismiss">Dismiss — this domain uses another mail provider</button>
        </div>
        <div id="mx-decided" class="text-muted small d-none"></div>

        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Mailboxes</h5>
                <div>
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="reveal-all">Reveal all passwords</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="copy-csv">Copy as CSV</button>
                </div>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead><tr><th>Email</th><th>Quota MB</th><th>Status</th><th>Temp password</th></tr></thead>
                    <tbody id="mailbox-rows"></tbody>
                </table>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header"><h5 class="mb-0">Forwarders</h5></div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead><tr><th>Source</th><th>Targets</th><th>Status</th></tr></thead>
                    <tbody id="forwarder-rows"></tbody>
                </table>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header"><h5 class="mb-0">Sites &amp; Databases</h5></div>
            <div class="card-body" id="sites-databases">…</div>
        </div>

        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Import log</h5>
                <button type="button" class="btn btn-sm btn-outline-secondary" id="log-toggle"
                        data-bs-toggle="collapse" data-bs-target="#log-body" aria-expanded="false">Show</button>
            </div>
            <div id="log-body" class="collapse">
                <pre id="import-log" class="card-body mb-0 small" style="max-height: 60vh; overflow:auto; white-space: pre-wrap;">(empty)</pre>
            </div>
        </div>

        <div id="cleared-banner" class="alert alert-secondary d-none"></div>
        <button type="button" class="btn btn-outline-danger" id="clear-credentials">I have securely stored these credentials — clear them from the server</button>
    </div>
</div>

<script>
(function () {
    const importId = document.querySelector('[data-import-id]').dataset.importId;
    const nonce = '<?= get_csrf_token() ?>';

    async function load() {
        const r = await fetch('/api/cpanel-import-summary.php?import_id=' + encodeURIComponent(importId));
        if (!r.ok) {
            document.getElementById('results-error').textContent = 'Failed to load: HTTP ' + r.status;
            document.getElementById('results-error').classList.remove('d-none');
            document.getElementById('results-loading').classList.add('d-none');
            return;
        }
        render(await r.json());
    }

    function td(text) { const el = document.createElement('td'); el.textContent = text; return el; }

    function render(s) {
        document.getElementById('results-loading').classList.add('d-none');
        document.getElementById('results-body').classList.remove('d-none');
        document.getElementById('totals-sites').textContent      = (s.totals && s.totals.sites)      || 0;
        document.getElementById('totals-databases').textContent  = (s.totals && s.totals.databases)  || 0;
        document.getElementById('totals-mailboxes').textContent  = (s.totals && s.totals.mailboxes)  || 0;
        document.getElementById('totals-forwarders').textContent = (s.totals && s.totals.forwarders) || 0;

        const tbody = document.getElementById('mailbox-rows');
        tbody.replaceChildren();
        for (const m of (s.mailboxes || [])) {
            const tr = document.createElement('tr');
            tr.appendChild(td(m.email));
            tr.appendChild(td(String(m.quota_mb || '-')));
            tr.appendChild(td(m.status));
            const pwTd = document.createElement('td');
            const pwSpan = document.createElement('code');
            const masked = m.temp_password ? '••••••••••••••••••••' : '(no password)';
            pwSpan.textContent = masked;
            const btn = document.createElement('button');
            btn.className = 'btn btn-link btn-sm';
            btn.textContent = m.temp_password ? 'Reveal' : '';
            btn.disabled = !m.temp_password;
            btn.addEventListener('click', () => {
                pwSpan.textContent = (pwSpan.textContent === masked) ? m.temp_password : masked;
            });
            pwTd.appendChild(pwSpan);
            pwTd.appendChild(document.createTextNode(' '));
            pwTd.appendChild(btn);
            tr.appendChild(pwTd);
            tbody.appendChild(tr);
        }

        const ftbody = document.getElementById('forwarder-rows');
        ftbody.replaceChildren();
        for (const f of (s.forwarders || [])) {
            const tr = document.createElement('tr');
            tr.appendChild(td(f.source));
            tr.appendChild(td((f.targets || []).join(', ')));
            tr.appendChild(td(f.status));
            ftbody.appendChild(tr);
        }

        const dns = s.dns || {};
        const mxList = (dns.original_mx || []).map(m => m.host).filter(Boolean);
        const decided = dns.mx_repoint_action;
        if (decided) {
            const banner = document.getElementById('mx-decided');
            banner.classList.remove('d-none');
            banner.textContent = 'MX ' + decided + ' by ' + (dns.mx_repoint_actor || 'unknown') + ' at ' + (dns.mx_repoint_at || '?') + '.';
        } else if (mxList.length > 0) {
            document.getElementById('mx-panel').classList.remove('d-none');
            document.getElementById('mx-current-target').textContent = mxList.join(', ');
        }

        if (s.credentials_cleared_at) {
            const cb = document.getElementById('cleared-banner');
            cb.classList.remove('d-none');
            cb.textContent = 'Credentials cleared by ' + (s.credentials_cleared_by || '?') + ' at ' + s.credentials_cleared_at + '.';
            document.getElementById('clear-credentials').disabled = true;
        }

        const sd = document.getElementById('sites-databases');
        const list = document.createElement('ul');
        for (const site of (s.sites || [])) {
            const li = document.createElement('li');
            li.textContent = site.domain + ' → ' + (site.docroot || '') + ' (PHP ' + (site.php_version || '-') + ')';
            list.appendChild(li);
        }
        for (const db of (s.databases || [])) {
            const li = document.createElement('li');
            const name = db.whp_name || db.original_name || db.name || '?';
            const sizeStr = db.size_bytes ? (' (' + db.size_bytes + ' bytes)') : '';
            li.textContent = 'Database: ' + name + sizeStr;
            list.appendChild(li);
        }
        sd.replaceChildren(list);

        const logEl = document.getElementById('import-log');
        const logLines = Array.isArray(s.log) ? s.log : [];
        if (logLines.length) {
            logEl.textContent = logLines.join('\n');
            const toggle = document.getElementById('log-toggle');
            toggle.textContent = 'Show (' + logLines.length + ' lines)';
        } else {
            logEl.textContent = '(no log entries)';
        }
    }

    document.getElementById('reveal-all').addEventListener('click', () => {
        document.querySelectorAll('#mailbox-rows code').forEach(code => {
            const btn = code.parentElement.querySelector('button');
            if (btn && !btn.disabled && code.textContent.includes('•')) btn.click();
        });
    });

    document.getElementById('copy-csv').addEventListener('click', async () => {
        const rows = [['email', 'quota_mb', 'status', 'temp_password']];
        document.querySelectorAll('#mailbox-rows tr').forEach(tr => {
            const cells = tr.querySelectorAll('td');
            if (cells.length === 4) {
                const code = cells[3].querySelector('code');
                const pw = (code && !code.textContent.includes('•')) ? code.textContent : '(masked — reveal first)';
                rows.push([cells[0].textContent, cells[1].textContent, cells[2].textContent, pw]);
            }
        });
        const csv = rows.map(r => r.map(c => '"' + String(c).replace(/"/g, '""') + '"').join(',')).join('\n');
        await navigator.clipboard.writeText(csv);
    });

    document.getElementById('clear-credentials').addEventListener('click', async () => {
        if (!confirm('Clear all temp passwords from the server? This cannot be undone.')) return;
        const r = await fetch('/api/cpanel-import-clear-credentials.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-Token': nonce},
            body: new URLSearchParams({import_id: importId}),
        });
        if (r.ok) location.reload();
        else alert('Failed: HTTP ' + r.status);
    });

    document.getElementById('mx-repoint').addEventListener('click', () => mxAction('repoint'));
    document.getElementById('mx-dismiss').addEventListener('click', () => mxAction('dismiss'));
    async function mxAction(action) {
        const r = await fetch('/api/cpanel-import-mx-action.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-Token': nonce},
            body: new URLSearchParams({import_id: importId, action: action}),
        });
        if (r.ok) location.reload();
        else alert('Failed: HTTP ' + r.status);
    }

    load();
})();
</script>
