{* DNS tab — ONE panel per logical zone. Records are logical (one row each);
   per-server state lives on rec.server_states[] (one entry per attached DNS
   server) and is rolled up into rec.deploy_status (the worst). The panel
   heading shows the cluster member list with per-server pills. *}
<div style="margin-bottom:8px;">
    <button type="button" class="btn btn-default btn-xs" id="puq-svc-dns-reload"><i class="fa fa-sync"></i> Reload</button>
    <span class="text-muted small" id="puq-svc-dns-summary" style="margin-left:8px;"></span>
    <div class="pull-right">
        <button type="button" class="btn btn-danger btn-sm" id="puq-svc-dns-redeploy-tpl" title="WIPE every record and re-render the configured zone template — destructive">
            <i class="fa fa-undo"></i> Redeploy from template
        </button>
        <button type="button" class="btn btn-warning btn-sm" id="puq-svc-dns-redeploy-all" title="Redeploy current records to every attached DNS server (non-destructive)">
            <i class="fa fa-rocket"></i> Redeploy ALL zones
        </button>
    </div>
    <div class="clearfix"></div>
</div>
<div id="puq-svc-dns-zones"><div class="text-muted text-center" style="padding:30px;"><i class="fa fa-spinner fa-spin"></i> Loading…</div></div>
{literal}
<script>
(window.puqSvc = window.puqSvc || {}).init_dns = function(ctx){
    var esc = ctx.esc, baseUrl = ctx.baseUrl, puqId = ctx.puqId;
    var dtRegistry = {};

    function lblCls(s){
        return ({queued:'default',deploying:'info',active:'success',error:'danger',pending_delete:'warning',deleting:'warning'})[s] || 'default';
    }
    function statusLabel(s){
        return '<span class="label label-' + lblCls(s) + '">' + esc(s || '—') + '</span>';
    }
    function recordServerCell(serverStates) {
        if (!serverStates || !serverStates.length) {
            return '<span class="text-muted">— pending —</span>';
        }
        return serverStates.map(function(st){
            var tt = st.deploy_error ? esc(st.deploy_error) : (st.remote_id ? 'remote_id=' + esc(st.remote_id) : '');
            return '<span class="label label-' + lblCls(st.deploy_status) + '" title="' + tt + '" style="margin-right:3px;">'
                + esc(st.server_name) + '</span>';
        }).join('');
    }

    function load() {
        puqAjax({ container: '#puq-svc-dns-zones', loadingCaption: 'Loading DNS zones…',
            url: baseUrl + 'listServiceDns&id=' + puqId, dataType: 'json',
            success: function(r){
                var zones = (r.status === 'success' && r.data) ? r.data : [];
                Object.keys(dtRegistry).forEach(function(k){ try { dtRegistry[k].destroy(); } catch(e){} });
                dtRegistry = {};

                var $host = $('#puq-svc-dns-zones').empty();
                if (!zones.length) {
                    $host.html('<div class="alert alert-info">No DNS zones for this service.</div>');
                    $('#puq-svc-dns-summary').text('0 zones, 0 records');
                    return;
                }

                var totalRec = 0;
                zones.forEach(function(z){
                    totalRec += (z.records || []).length;
                    var serversHtml = (z.servers || []).map(function(s){
                        var tt = s.deploy_error ? ' title="' + esc(s.deploy_error) + '"' : '';
                        // "@username" is meaningful for HestiaCP (per-user DNS
                        // scope). PowerDNS has no users — render the driver
                        // label instead so admins can tell at a glance which
                        // server backs the zone replica.
                        var idTag;
                        if (s.server_driver === 'powerdns') {
                            idTag = ' <span class="label label-warning" style="font-size:10px;">PowerDNS API</span>';
                        } else if (s.username) {
                            idTag = ' <small class="text-muted">@</small> <code>' + esc(s.username) + '</code>';
                        } else {
                            idTag = '';
                        }
                        return esc(s.server_name) + idTag + ' '
                            + '<span class="label label-' + lblCls(s.deploy_status) + '" style="font-size:10px;"' + tt + '>'
                            + esc(s.deploy_status) + '</span>';
                    }).join(' &nbsp;·&nbsp; ') || '<span class="text-muted">no servers</span>';

                    var panel =
                        '<div class="panel panel-default">' +
                          '<div class="panel-heading">' +
                            '<strong><i class="fa fa-globe"></i> ' + esc(z.zone) + '</strong> ' +
                            statusLabel(z.deploy_status) + ' ' +
                            '<div style="margin-top:6px;font-size:12px;color:#555;">' +
                              '<i class="fa fa-server"></i> Cluster: ' + serversHtml +
                            '</div>' +
                          '</div>' +
                          '<div class="panel-body" style="padding:6px;">' +
                            '<table class="table table-condensed table-striped" id="puq-svc-dns-zone-' + z.id + '" style="width:100%;margin:0;">' +
                              '<thead><tr><th>ID</th><th>Type</th><th>Name</th><th>Value</th><th>Pri</th><th>TTL</th><th>Servers</th><th>Status</th></tr></thead>' +
                              '<tbody></tbody>' +
                            '</table>' +
                          '</div>' +
                        '</div>';
                    $host.append(panel);

                    var $tbody = $('#puq-svc-dns-zone-' + z.id + ' tbody');
                    (z.records || []).forEach(function(rec){
                        $tbody.append('<tr>' +
                            '<td>' + esc(rec.id) + '</td>' +
                            '<td><span class="label label-default">' + esc(rec.record_type) + '</span></td>' +
                            '<td><code>' + esc(rec.name) + '</code></td>' +
                            '<td style="max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="' + esc(rec.value) + '"><code>' + esc(rec.value) + '</code></td>' +
                            '<td>' + esc(rec.priority == null ? '' : rec.priority) + '</td>' +
                            '<td>' + esc(rec.ttl) + '</td>' +
                            '<td>' + recordServerCell(rec.server_states) + '</td>' +
                            '<td>' + statusLabel(rec.deploy_status) + '</td>' +
                            '</tr>');
                    });
                    if (!(z.records || []).length) {
                        $tbody.append('<tr><td colspan="8" class="text-muted text-center">(no records)</td></tr>');
                    }
                    dtRegistry[z.id] = $('#puq-svc-dns-zone-' + z.id).DataTable({ order: [[0, 'asc']], pageLength: 25, autoWidth: false });
                });
                $('#puq-svc-dns-summary').text(zones.length + ' zone(s), ' + totalRec + ' record(s) total');
            },
            error: function(){ $('#puq-svc-dns-zones').html('<div class="alert alert-danger">Request failed.</div>'); }
        });
    }

    $('#puq-svc-dns-reload').on('click', load);
    load = ctx.armAutoRefresh('dns', { selector: '#puq-svc-dns-zones', load: load });

    $('#puq-svc-dns-redeploy-all').on('click', function(){
        puqConfirm({
            type: 'warning', icon: 'fa-rocket',
            title: 'Redeploy ALL zones?',
            text: 'Redeploy every DNS zone of this service on every attached cluster member. Existing records are preserved.',
            ok: 'Redeploy', cancel: 'Cancel',
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    $.ajax({ url: baseUrl + 'redeployAllDnsRecords', type: 'POST', data: { id: puqId }, dataType: 'json',
                        success: function(r){
                            if (r.status === 'success') { showNotification(r.msg || 'Queued.', 'success'); load(); resolve(); }
                            else reject(new Error(r.msg || 'Redeploy failed'));
                        },
                        error: function(){ reject(new Error('Request failed')); }
                    });
                });
            }
        });
    });

    $('#puq-svc-dns-redeploy-tpl').on('click', function(){
        puqConfirm({
            type: 'danger', icon: 'fa-undo',
            title: 'Redeploy from template?',
            text: '<strong>Destructive.</strong> All current DNS records for this service will be deleted, then re-created from the configured zone template. Any manual edits will be lost.',
            ok: 'Reset & redeploy', cancel: 'Cancel',
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    $.ajax({ url: baseUrl + 'redeployDnsFromTemplate', type: 'POST', data: { id: puqId }, dataType: 'json',
                        success: function(r){
                            if (r.status === 'success') { showNotification(r.msg || 'Queued.', 'success'); load(); resolve(); }
                            else reject(new Error(r.msg || 'Reset failed'));
                        },
                        error: function(){ reject(new Error('Request failed')); }
                    });
                });
            }
        });
    });

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