<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title pull-left"><i class="fa fa-globe"></i> DNS Zones</h3>
        <div class="pull-right">
            <input type="text" id="puq-search" class="input-sm" placeholder="Search zone…" style="width:180px;margin-right:6px;">
            <button class="btn btn-default btn-sm" id="puq-refresh"><i class="fa fa-sync"></i></button>
        </div>
        <div class="clearfix"></div>
    </div>
    <div class="panel-body">
        <p class="text-muted" style="margin-bottom:8px;font-size:12px;">
            One row per LOGICAL zone. The "Cluster" column shows the deploy
            state on each DNS server the zone is replicated to.
        </p>
        <table class="table table-striped table-bordered" id="puq-data-table">
            <thead>
                <tr>
                    <th style="width:60px;">ID</th>
                    <th>Zone</th>
                    <th>Service</th>
                    <th>Cluster</th>
                    <th style="width:100px;">Records</th>
                    <th style="width:140px;">Actions</th>
                </tr>
            </thead>
            <tbody><tr><td colspan="6" class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading…</td></tr></tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="puq-records-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">DNS records — <span id="puq-records-zone"></span></h4>
            </div>
            <div class="modal-body">
                <table class="table table-condensed table-bordered" id="puq-records-tbl">
                    <thead><tr><th>Type</th><th>Name</th><th>Value</th><th>Pri</th><th>TTL</th></tr></thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="puq-confirm-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Redeploy Zone</h4>
            </div>
            <div class="modal-body">
                <p>Recreate this zone on the selected server(s)?</p>
                <input type="hidden" id="puq-confirm-id">
                <div class="form-group">
                    <label>Target</label>
                    <select id="puq-confirm-server" class="form-control">
                        <option value="0">— all attached DNS servers —</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-warning" id="puq-confirm-redeploy"><i class="fas fa-redo"></i> Redeploy</button>
            </div>
        </div>
    </div>
</div>

{literal}
<script>
(function(){
    var baseUrl = '{/literal}{$meta.admin_module_url}&ajax={literal}';
    var badge = window.statusBadge;
    function clusterCell(servers){
        if (!servers || !servers.length) return '<span class="text-muted">— no server —</span>';
        return servers.map(function(s){
            var tt = s.deploy_error ? escAttr(s.deploy_error) : (s.last_synced_at ? 'synced ' + escAttr(s.last_synced_at) : '');
            return '<span class="label label-'
                + ({active:'success',queued:'warning',deploying:'info',error:'danger',pending_delete:'default',deleting:'default'}[s.deploy_status] || 'default')
                + '" title="' + tt + '" style="margin-right:4px;">'
                + esc(s.name) + ': ' + esc(s.deploy_status) + '</span>';
        }).join('');
    }

    function load() {
        var params = { search: $('#puq-search').val() };
        puqAjax({
            container: '#puq-data-table',
            loadingCaption: 'Loading zones…',
            url: baseUrl + 'listDnsZones', data: params, dataType: 'json',
            success: function(r) {
                var $tbody = $('#puq-data-table tbody').empty();
                if (r.status !== 'success' || !r.data.length) {
                    $tbody.append('<tr><td colspan="6" class="text-center text-muted">No zones.</td></tr>');
                    return;
                }
                r.data.forEach(function(z) {
                    var serversJson = escAttr(JSON.stringify(z.servers || []));
                    $tbody.append(
                        '<tr data-id="' + z.id + '" data-zone="' + esc(z.zone) + '" data-servers=\'' + serversJson + '\'>' +
                        '<td>' + z.id + '</td>' +
                        '<td><strong>' + esc(z.zone) + '</strong></td>' +
                        '<td>' + esc(z.service_domain || '—') + '</td>' +
                        '<td>' + clusterCell(z.servers) + '</td>' +
                        '<td class="text-center"><a href="#" class="puq-records">' + z.record_count + '</a></td>' +
                        '<td><button class="btn btn-xs btn-warning puq-redeploy" title="Redeploy zone"><i class="fa fa-redo"></i> Redeploy</button></td>' +
                        '</tr>'
                    );
                });
            }
        });
    }

    $(document).ready(function(){
        load();

        $('#puq-search').on('keyup', load);
        $('#puq-refresh').on('click', function() {
            var btn = this; btnSpinner(btn);
            setTimeout(function(){ load(); btnRestore(btn, 'sync', ''); }, 200);
        });

        $('#puq-data-table').on('click', '.puq-records', function(e) {
            e.preventDefault();
            var $row = $(this).closest('tr');
            var zoneId = $row.data('id');
            $('#puq-records-zone').text($row.data('zone'));
            puqAjax({
                container: '#puq-records-tbl',
                loadingCaption: 'Loading records…',
                url: baseUrl + 'zoneRecords&zone_id=' + zoneId, dataType: 'json',
                success: function(r) {
                    var $t = $('#puq-records-tbl tbody').empty();
                    if (r.status !== 'success') { $t.append('<tr><td colspan="5" class="text-danger">' + esc(r.msg || '') + '</td></tr>'); return; }
                    if (!r.data.length) { $t.append('<tr><td colspan="5" class="text-muted text-center">No records.</td></tr>'); return; }
                    r.data.forEach(function(rec) {
                        $t.append('<tr>' +
                            '<td><code>' + esc(rec.record_type) + '</code></td>' +
                            '<td>' + esc(rec.name) + '</td>' +
                            '<td style="max-width:350px;word-break:break-all;"><code>' + esc(rec.value) + '</code></td>' +
                            '<td>' + (rec.priority == null ? '—' : esc(rec.priority)) + '</td>' +
                            '<td>' + esc(rec.ttl) + '</td>' +
                            '</tr>');
                    });
                    $('#puq-records-modal').modal('show');
                }
            });
        });

        $('#puq-data-table').on('click', '.puq-redeploy', function() {
            var $row = $(this).closest('tr');
            $('#puq-confirm-id').val($row.data('id'));
            var servers = $row.data('servers') || [];
            var $sel = $('#puq-confirm-server');
            $sel.find('option:not([value="0"])').remove();
            servers.forEach(function(s) {
                $sel.append('<option value="' + s.server_id + '">' + esc(s.name) + ' (current: ' + esc(s.deploy_status) + ')</option>');
            });
            $('#puq-confirm-modal').modal('show');
        });

        $('#puq-confirm-redeploy').on('click', function() {
            var btn = this;
            btnSpinner(btn, 'Queuing...');
            $.ajax({
                url: baseUrl + 'redeployZone', type: 'POST',
                data: { zone_id: $('#puq-confirm-id').val(), server_id: $('#puq-confirm-server').val() || 0 },
                dataType: 'json',
                success: function(r) {
                    if (r.status === 'success') { showNotification(r.msg || 'Queued.', 'success'); load(); }
                    else { showNotification(r.msg || 'Failed.', 'error'); }
                    $('#puq-confirm-modal').modal('hide');
                },
                error: function() { showNotification('Request failed.', 'error'); $('#puq-confirm-modal').modal('hide'); },
                complete: function() { btnRestore(btn, 'redo', 'Redeploy'); }
            });
        });
    });
})();
</script>
{/literal}
