{* Admin SSL tab — Auto-SSL status + Issue/Renew button + Custom SSL
   upload/remove for web AND mail roles. Mirrors the customer's
   custom_ssl.tpl logic (re-uses getServiceSslStatus + getServiceSslCustom
   + uploadServiceSslCustom + removeServiceSslCustom + issueSslNow). *}
<style>
.puq-ssl-card { padding:12px 14px; background:#fff; border:1px solid #ddd; border-radius:3px; margin-bottom:12px; }
.puq-ssl-card h4 { margin:0 0 10px; font-size:14px; font-weight:600; display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
.puq-ssl-card h4 .label { margin-left:auto; }
.puq-ssl-card .ssl-section { margin-top:10px; padding-top:10px; border-top:1px solid #eee; }
.puq-ssl-card .ssl-section:first-of-type { border-top:none; padding-top:0; margin-top:0; }
.puq-ssl-row { display:flex; align-items:flex-start; gap:10px; flex-wrap:wrap; font-size:12px; }
.puq-ssl-row code { background:#f5f5f5; padding:1px 5px; border-radius:2px; font-size:11px; }
.puq-ssl-meta { margin:6px 0 0; }
.puq-ssl-meta th { width:120px; font-weight:600; color:#555; padding:2px 8px 2px 0; }
.puq-ssl-meta td { padding:2px 0; }
</style>

<div id="puq-ssl-state" class="puq-tab-loading"><i class="fa fa-spinner fa-spin"></i> Loading SSL state…</div>

<div id="puq-ssl-body" style="display:none;">
    <div class="alert alert-info" style="padding:8px 12px;font-size:12px;margin-bottom:12px;">
        <i class="fa fa-info-circle"></i>
        Auto-SSL (Let's Encrypt) is enabled by default. You can also upload a custom certificate (EV / wildcard / paid CA) — while it's installed Auto-SSL pauses for that role.
    </div>

    {if $service_row.deployment_mode eq 'vanity'}
    <div class="alert alert-warning" style="padding:8px 12px;font-size:12px;margin-bottom:12px;">
        <i class="fa fa-lock"></i> Mail SSL is managed on the provider mail domain (the mailbox lives on the shared provider mail user), so only the website certificate is shown here.
    </div>
    {/if}
    {if $service_row.deployment_mode eq 'vanity'}{assign var="sslKinds" value=['web']}{else}{assign var="sslKinds" value=['web','mail']}{/if}
    {foreach from=$sslKinds item=kind}
    <div class="puq-ssl-card" data-kind="{$kind}">
        <h4>
            <i class="fa fa-{if $kind eq 'web'}lock{else}envelope{/if}" style="color:{if $kind eq 'web'}#337ab7{else}#5cb85c{/if};"></i>
            {if $kind eq 'web'}Web role{else}Mail role{/if}
            <span class="label label-default puq-ssl-pill-{$kind}">…</span>
        </h4>

        <div class="ssl-section">
            <strong><i class="fa fa-magic"></i> Auto-SSL (Let's Encrypt)</strong>
            <div class="puq-ssl-auto-{$kind}" style="margin-top:6px;">
                <i class="fa fa-spinner fa-spin"></i> Loading…
            </div>
        </div>

        <div class="ssl-section">
            <strong><i class="fa fa-upload"></i> Custom SSL</strong>
            <div class="puq-ssl-custom-{$kind}" style="margin-top:6px;">
                <i class="fa fa-spinner fa-spin"></i> Loading…
            </div>
        </div>
    </div>
    {/foreach}
</div>

{literal}
<script>
(window.puqSvc = window.puqSvc || {}).init_ssl = function(ctx){
    var esc = ctx.esc, baseUrl = ctx.baseUrl, puqId = ctx.puqId, fmtDate = ctx.fmtDate;
    var TRANSIENT = ['queued','deploying','pending','pending_delete','deleting'];
    var pollTimer = null;

    function autoPill(row){
        if (!row) return { cls: 'label-default', text: 'NOT TRACKED' };
        var st = (row.cert_status || 'none');
        if (st === 'active')   return { cls: 'label-success', text: 'ACTIVE' };
        if (st === 'expired')  return { cls: 'label-danger',  text: 'EXPIRED' };
        if (st === 'failed')   return { cls: 'label-danger',  text: 'FAILED' };
        if (st === 'frozen')   return { cls: 'label-warning', text: 'FROZEN (rate-limit)' };
        if (st === 'managed_by_customer') return { cls: 'label-info', text: 'PAUSED — CUSTOM SSL ACTIVE' };
        return { cls: 'label-default', text: st.toUpperCase() };
    }
    function customPill(info){
        if (!info) return { cls: 'label-default', text: 'NONE' };
        var st = (info.status || 'pending').toLowerCase();
        var dst = (info.deploy_status || '').toLowerCase();
        if (TRANSIENT.indexOf(dst) >= 0) return { cls: 'label-warning', text: dst.toUpperCase() };
        if (st === 'active')  return { cls: 'label-success', text: 'ACTIVE' };
        if (st === 'expired') return { cls: 'label-danger',  text: 'EXPIRED' };
        if (st === 'error')   return { cls: 'label-danger',  text: 'ERROR' };
        return { cls: 'label-warning', text: st.toUpperCase() };
    }
    function topPill(kind, autoRow, customInfo){
        // Custom takes precedence when present (any state). Otherwise reflect Auto state.
        if (customInfo) return customPill(customInfo);
        return autoPill(autoRow);
    }

    function renderAuto(kind, row){
        var $box = $('.puq-ssl-auto-' + kind);
        if (!row) {
            $box.html('<div class="text-muted">Tracker not seeded yet — will populate after the service deploys.</div>');
            return;
        }
        var pill = autoPill(row);
        var rows = '';
        if (row.required_hosts && row.required_hosts.length) {
            rows += '<tr><th>Required hosts</th><td>' + row.required_hosts.map(function(h){ return '<code>' + esc(h) + '</code>'; }).join(' ') + '</td></tr>';
        }
        if (row.cert_subject) rows += '<tr><th>Subject</th><td><code>' + esc(row.cert_subject) + '</code></td></tr>';
        if (row.cert_issuer)  rows += '<tr><th>Issuer</th><td>' + esc(row.cert_issuer) + '</td></tr>';
        if (row.cert_expires_at) rows += '<tr><th>Expires</th><td>' + fmtDate(row.cert_expires_at) + '</td></tr>';
        if (row.last_check_at)   rows += '<tr><th>Last check</th><td>' + fmtDate(row.last_check_at) + ' · ' + (row.last_check_ok == 1 ? '<span class="label label-success">ok</span>' : '<span class="label label-warning">retry</span>') + '</td></tr>';
        if (row.next_check_at)   rows += '<tr><th>Next check</th><td>' + fmtDate(row.next_check_at) + '</td></tr>';
        if (row.consecutive_issue_failures && row.consecutive_issue_failures > 0) {
            rows += '<tr><th>Issue failures</th><td><span class="text-danger">' + esc(row.consecutive_issue_failures) + '</span></td></tr>';
        }
        if (row.issue_frozen_until) {
            rows += '<tr><th>Frozen until</th><td><span class="text-warning">' + fmtDate(row.issue_frozen_until) + '</span></td></tr>';
        }
        if (row.last_check_detail) {
            rows += '<tr><th>Detail</th><td><small class="text-muted">' + esc(row.last_check_detail) + '</small></td></tr>';
        }

        var inProgHtml = '';
        if (row.in_progress) {
            inProgHtml = ' <span class="label label-info"><i class="fa fa-spinner fa-spin"></i> ' + esc(row.in_progress.task_status) + '</span>';
        }
        var btnDisabled = !!row.in_progress;
        var html =
            '<div style="margin-bottom:6px;"><span class="label ' + pill.cls + '">' + esc(pill.text) + '</span>' + inProgHtml + '</div>' +
            '<table class="table table-condensed puq-ssl-meta" style="margin:0;">' + rows + '</table>' +
            '<div style="margin-top:8px;">' +
                '<button type="button" class="btn btn-primary btn-sm puq-ssl-issue" data-kind="' + esc(kind) + '"' + (btnDisabled ? ' disabled' : '') + '>' +
                    '<i class="fa fa-bolt"></i> Issue / Renew now' +
                '</button>' +
            '</div>';
        $box.html(html);
    }

    function renderCustom(kind, info){
        var $box = $('.puq-ssl-custom-' + kind);
        if (!info) {
            $box.html(
                '<div class="text-muted" style="margin-bottom:8px;">No custom certificate uploaded.</div>' +
                '<button type="button" class="btn btn-default btn-sm puq-ssl-upload" data-kind="' + esc(kind) + '">' +
                    '<i class="fa fa-upload"></i> Upload certificate' +
                '</button>'
            );
            return;
        }
        var pill = customPill(info);
        var rows = '';
        if (info.common_name) rows += '<tr><th>Subject (CN)</th><td><code>' + esc(info.common_name) + '</code></td></tr>';
        if (info.issuer)      rows += '<tr><th>Issuer</th><td>' + esc(info.issuer) + '</td></tr>';
        if (info.not_before)  rows += '<tr><th>Valid from</th><td>' + esc(info.not_before) + '</td></tr>';
        if (info.not_after)   rows += '<tr><th>Valid until</th><td>' + esc(info.not_after) + '</td></tr>';
        if (info.sans && info.sans.length) {
            rows += '<tr><th>SAN</th><td style="word-break:break-all;">' +
                    info.sans.map(function(s){ return '<code>' + esc(s) + '</code>'; }).join(' ') +
                    '</td></tr>';
        }
        if (info.deploy_error) {
            rows += '<tr><th>Last error</th><td><small class="text-danger">' + esc(info.deploy_error) + '</small></td></tr>';
        }
        var html =
            '<div style="margin-bottom:6px;"><span class="label ' + pill.cls + '">' + esc(pill.text) + '</span></div>' +
            '<table class="table table-condensed puq-ssl-meta" style="margin:0;">' + rows + '</table>' +
            '<div style="margin-top:8px;display:flex;gap:6px;flex-wrap:wrap;">' +
                '<button type="button" class="btn btn-primary btn-sm puq-ssl-upload" data-kind="' + esc(kind) + '">' +
                    '<i class="fa fa-upload"></i> Replace certificate' +
                '</button>' +
                '<button type="button" class="btn btn-warning btn-sm puq-ssl-remove" data-kind="' + esc(kind) + '">' +
                    '<i class="fa fa-times"></i> Remove (resume Auto-SSL)' +
                '</button>' +
            '</div>';
        $box.html(html);
    }

    function load(){
        var done = 0; var autoData = null; var customData = null;
        function tryRender(){
            if (done < 2) return;
            ['web','mail'].forEach(function(kind){
                var autoRow    = autoData ? autoData[kind] : null;
                var customInfo = customData ? customData[kind] : null;
                renderAuto(kind, autoRow);
                renderCustom(kind, customInfo);
                var top = topPill(kind, autoRow, customInfo);
                $('.puq-ssl-pill-' + kind).removeClass().addClass('label puq-ssl-pill-' + kind + ' ' + top.cls).text(top.text);
            });
            $('#puq-ssl-state').hide();
            $('#puq-ssl-body').show();

            // Auto-poll while any role has an in-flight task / transient deploy_status.
            var pending = false;
            ['web','mail'].forEach(function(kind){
                var a = autoData ? autoData[kind] : null;
                var c = customData ? customData[kind] : null;
                if (a && a.in_progress) pending = true;
                if (c && TRANSIENT.indexOf((c.deploy_status || '').toLowerCase()) >= 0) pending = true;
            });
            if (pollTimer) { clearTimeout(pollTimer); pollTimer = null; }
            if (pending) pollTimer = setTimeout(load, 5000);
        }
        $.getJSON(baseUrl + 'getServiceSslStatus&id=' + puqId, function(r){
            autoData = (r.status === 'success' && r.data) ? r.data : { web: null, mail: null };
            done++; tryRender();
        }).fail(function(){ autoData = { web: null, mail: null }; done++; tryRender(); });
        $.getJSON(baseUrl + 'getServiceSslCustom&id=' + puqId, function(r){
            customData = (r.status === 'success' && r.data) ? r.data : { web: null, mail: null };
            done++; tryRender();
        }).fail(function(){ customData = { web: null, mail: null }; done++; tryRender(); });
    }

    $('#tab-ssl').on('click', '.puq-ssl-issue', function(){
        var $btn = $(this); var kind = $btn.data('kind');
        btnSpinner(this, 'Queuing…');
        $.ajax({ url: baseUrl + 'issueSslNow', type: 'POST',
            data: { id: puqId, kind: kind }, dataType: 'json',
            success: function(r){
                if (r.status === 'success') { showNotification(r.msg || 'Issue queued', 'success'); load(); }
                else { btnRestore($btn[0], 'bolt', 'Issue / Renew now'); showNotification(r.msg || 'Failed', 'error'); }
            },
            error: function(){ btnRestore($btn[0], 'bolt', 'Issue / Renew now'); showNotification('Request failed', 'error'); }
        });
    });

    $('#tab-ssl').on('click', '.puq-ssl-upload', function(){
        var kind = $(this).data('kind');
        var body =
            '<div style="margin-bottom:10px;">' +
              '<label style="font-size:11px;color:#777;">Certificate (PEM)</label>' +
              '<textarea name="cert_pem" class="form-control" rows="6" spellcheck="false" style="font-family:monospace;font-size:12px;"></textarea>' +
            '</div>' +
            '<div style="margin-bottom:10px;">' +
              '<label style="font-size:11px;color:#777;">Private key (PEM, <strong>unencrypted</strong>)</label>' +
              '<textarea name="key_pem" class="form-control" rows="6" spellcheck="false" style="font-family:monospace;font-size:12px;"></textarea>' +
              '<small class="text-muted">Key must NOT be password-protected.</small>' +
            '</div>' +
            '<div>' +
              '<label style="font-size:11px;color:#777;">CA chain (optional)</label>' +
              '<textarea name="chain_pem" class="form-control" rows="4" spellcheck="false" style="font-family:monospace;font-size:12px;"></textarea>' +
            '</div>';
        puqModal({
            type: 'info', icon: 'fa-upload',
            title: 'Upload ' + kind + ' certificate',
            body: body,
            ok: '<i class="fa fa-upload"></i> Validate & install',
            onOpen: function(box){ $(box).find('textarea').first().focus(); },
            onConfirm: function(box){
                var data = {
                    id: puqId, kind: kind,
                    cert_pem:  ($(box).find('[name=cert_pem]').val()  || '').trim(),
                    key_pem:   ($(box).find('[name=key_pem]').val()   || '').trim(),
                    chain_pem: ($(box).find('[name=chain_pem]').val() || '').trim()
                };
                if (!data.cert_pem || !data.key_pem) {
                    return Promise.reject(new Error('Certificate and private key are required.'));
                }
                return new Promise(function(resolve, reject){
                    $.ajax({ url: baseUrl + 'uploadServiceSslCustom', type: 'POST', data: data, dataType: 'json',
                        success: function(r){
                            if (r.status === 'success') { showNotification(r.msg || 'Certificate accepted', 'success'); load(); resolve(); }
                            else reject(new Error(r.msg || 'Upload failed'));
                        },
                        error: function(){ reject(new Error('Request failed')); }
                    });
                });
            }
        });
    });

    $('#tab-ssl').on('click', '.puq-ssl-remove', function(){
        var kind = $(this).data('kind');
        puqConfirm({
            type: 'warning', icon: 'fa-times',
            title: 'Resume Auto-SSL?',
            text: 'Custom <strong>' + kind + '</strong> certificate will be removed. Auto-SSL will resume on the next cron tick.',
            ok: 'Remove', cancel: 'Keep custom',
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    $.ajax({ url: baseUrl + 'removeServiceSslCustom', type: 'POST',
                        data: { id: puqId, kind: kind }, dataType: 'json',
                        success: function(r){
                            if (r.status === 'success') { showNotification(r.msg || 'Custom certificate removed', 'success'); load(); resolve(); }
                            else reject(new Error(r.msg || 'Failed'));
                        },
                        error: function(){ reject(new Error('Request failed')); }
                    });
                });
            }
        });
    });

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