{include file='modules/servers/puqWebHosting/templates/header.tpl'}
{assign var='page_icon'  value='lock'}
{assign var='page_title' value=$L.dz_custom_ssl}
{include file='modules/servers/puqWebHosting/templates/_page_header.tpl'}

<div class="puq-msg puq-msg-info" style="font-size:13px;">
    <i class="fa fa-info-circle"></i>
    {$L.dz_ssl_intro}
</div>

{foreach from=['web','mail'] item=kind}
<div class="puq-card" id="puq-css-card-{$kind}" data-puq-lock-zone="{$kind}">
    <div class="puq-card-header">
        <i class="fa fa-{if $kind eq 'web'}globe{else}envelope{/if}"></i>
        {if $kind eq 'web'}{$L.dz_web_ssl} — {$domain|escape:'html'}{else}{$L.dz_mail_ssl} — mail.{$domain|escape:'html'}{/if}
        <i class="fas fa-circle-notch fa-spin" id="puq-css-spinner-{$kind}" style="display:none;color:var(--puq-muted);margin-left:6px;font-size:12px;" title="{$L.dz_refreshing}"></i>
        <span class="puq-header-spacer"></span>
        <span class="puq-sync-toolbar" data-role="{$kind}" style="margin-right:8px;"></span>
        <span class="puq-badge puq-badge-muted" id="puq-css-pill-{$kind}">…</span>
        <button type="button" class="puq-btn puq-btn-primary puq-btn-sm puq-css-upload" data-kind="{$kind}"><i class="fa fa-upload"></i> {$L.dz_upload_certificate}</button>
    </div>
    <div class="puq-card-body" id="puq-css-body-{$kind}">
        <div class="puq-loader"><i class="fas fa-circle-notch fa-spin"></i><span class="puq-loader-caption">{$L.dz_loading_ssl_state}</span></div>
    </div>
</div>
{/foreach}

<script>
window.puqServiceId = {$service_id};
window.puqPageRoles = ['web','mail'];
</script>
{literal}
<script>
(function(){
    var TRANSIENT = ['queued','deploying','pending','pending_delete','deleting'];
    var auto = puqAutoRefresh(load);

    function pillFor(info){
        if (!info) return { cls: 'puq-badge-muted', text: puqT('dz_auto_managed') };
        var st = (info.status || 'pending').toLowerCase();
        var dst = (info.deploy_status || '').toLowerCase();
        if (TRANSIENT.indexOf(dst) >= 0) return { cls: 'puq-badge-warning', text: puqT('dz_custom_prefix') + dst.toUpperCase() };
        if (st === 'active')  return { cls: 'puq-badge-success', text: puqT('dz_custom_active') };
        if (st === 'expired') return { cls: 'puq-badge-danger',  text: puqT('dz_custom_expired') };
        if (st === 'error')   return { cls: 'puq-badge-danger',  text: puqT('dz_custom_error') };
        return { cls: 'puq-badge-warning', text: puqT('dz_custom_prefix') + st.toUpperCase() };
    }

    function renderBody(kind, info){
        var $body = $('#puq-css-body-' + kind);
        if (!info) {
            $body.html(
                '<div class="puq-msg puq-msg-info" style="font-size:13px;margin:0;">' +
                  '<i class="fa fa-magic"></i> ' +
                  puqT('dz_managed_by_auto_ssl') +
                '</div>'
            );
            return;
        }
        var rows = [];
        if (info.common_name) rows.push('<tr><th style="width:140px;">' + puqT('dz_subject_cn') + '</th><td><code>' + puqEsc(info.common_name) + '</code></td></tr>');
        if (info.issuer)      rows.push('<tr><th>' + puqT('dz_issuer') + '</th><td>' + puqEsc(info.issuer) + '</td></tr>');
        if (info.not_before)  rows.push('<tr><th>' + puqT('dz_valid_from') + '</th><td>' + puqEsc(info.not_before) + '</td></tr>');
        if (info.not_after)   rows.push('<tr><th>' + puqT('dz_valid_until') + '</th><td>' + puqEsc(info.not_after) + '</td></tr>');
        if (info.sans && info.sans.length) {
            var sansHtml = info.sans.map(function(s){ return '<code>' + puqEsc(s) + '</code>'; }).join(' ');
            rows.push('<tr><th>' + puqT('dz_san') + '</th><td style="word-break:break-all;">' + sansHtml + '</td></tr>');
        }
        if (info.deploy_status && info.deploy_status !== 'active') {
            rows.push('<tr><th>' + puqT('dz_state') + '</th><td>' + puqDeployBadge(info.deploy_status, info.deploy_error) + '</td></tr>');
        }
        var html = '<table class="table table-condensed" style="margin:0 0 8px 0;">' + rows.join('') + '</table>';
        html += '<button type="button" class="puq-btn puq-btn-outline puq-btn-sm puq-css-remove" data-kind="' + kind + '"><i class="fa fa-times"></i> ' + puqT('dz_remove_certificate') + '</button>';
        $body.html(html);
    }

    function load(){
        puqSetSpinner('#puq-css-spinner-web, #puq-css-spinner-mail', true);
        puqClientAjax('sslCustomStatus', {}, function(r){
            puqSetSpinner('#puq-css-spinner-web, #puq-css-spinner-mail', false);
            if (!r || r.status !== 'success') {
                if (window.puqToast) puqToast('error', (r && r.msg) || puqT('dz_failed_load_ssl_state'));
                auto.schedule(false);
                return;
            }
            var data = r.data || {};
            var anyPending = false;
            ['web','mail'].forEach(function(kind){
                var info = data[kind] || null;
                var pill = pillFor(info);
                $('#puq-css-pill-'+kind).removeClass().addClass('puq-badge ' + pill.cls).text(pill.text);
                renderBody(kind, info);
                if (info && TRANSIENT.indexOf((info.deploy_status || '').toLowerCase()) >= 0) anyPending = true;
            });
            auto.schedule(anyPending);
        });
    }

    $(document).on('click', '.puq-css-upload', function(e){
        e.preventDefault();
        var kind = $(this).data('kind');
        var body =
            '<div style="margin-bottom:10px;">' +
              '<label style="font-size:11px;color:var(--puq-muted);">' + puqT('dz_certificate_pem') + '</label>' +
              '<textarea name="cert_pem" class="form-control" rows="6" spellcheck="false" required style="font-family:monospace;font-size:12px;"></textarea>' +
            '</div>' +
            '<div style="margin-bottom:10px;">' +
              '<label style="font-size:11px;color:var(--puq-muted);">' + puqT('dz_private_key_pem') + '</label>' +
              '<textarea name="key_pem" class="form-control" rows="6" spellcheck="false" required style="font-family:monospace;font-size:12px;"></textarea>' +
              '<small class="text-muted">' + puqT('dz_key_not_protected') + '</small>' +
            '</div>' +
            '<div>' +
              '<label style="font-size:11px;color:var(--puq-muted);">' + puqT('dz_ca_chain') + '</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: (kind === 'web' ? puqT('dz_upload_web_cert') : puqT('dz_upload_mail_cert')),
            body: body,
            ok: '<i class="fa fa-upload"></i> ' + puqT('dz_validate_install'),
            onOpen: function(box){ $(box).find('textarea').first().focus(); },
            onConfirm: function(box){
                var data = {
                    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(puqT('dz_cert_key_required')));
                }
                return new Promise(function(resolve, reject){
                    puqClientAjax('sslCustomUpload', data, function(r){
                        if (r && r.status === 'success') { puqToast('success', r.msg || puqT('dz_cert_accepted')); load(); resolve(); }
                        else reject(new Error((r && r.msg) || puqT('dz_upload_failed')));
                    }, 'POST');
                });
            }
        });
    });

    $(document).on('click', '.puq-css-remove', function(e){
        e.preventDefault();
        var kind = $(this).data('kind');
        puqConfirm({
            type: 'warning', icon: 'fa-times',
            title: puqT('dz_resume_auto_ssl_q'),
            text: puqT('dz_remove_cert_body_pre') + '<strong>' + kind + '</strong>' + puqT('dz_remove_cert_body_post'),
            ok: puqT('dz_resume_auto_ssl'), cancel: puqT('dz_keep_custom'),
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    puqClientAjax('sslCustomRemove', { kind: kind }, function(r){
                        if (r && r.status === 'success') { puqToast('success', r.msg || puqT('dz_custom_cert_removed')); load(); resolve(); }
                        else reject(new Error((r && r.msg) || puqT('dz_remove_failed')));
                    }, 'POST');
                });
            }
        });
    });

    $(document).ready(load);
})();
</script>
{/literal}
