<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title pull-left"><i class="fa fa-file-alt"></i> DNS Zone Templates</h3>
        <div class="pull-right">
            <button class="btn btn-default btn-sm" id="puq-seed-btn" title="Seed a template from a bundled .bind file"><i class="fa fa-download"></i> Seed from file…</button>
            <button class="btn btn-primary btn-sm" id="puq-add-btn"><i class="fa fa-plus"></i> Add Template</button>
        </div>
        <div class="clearfix"></div>
    </div>
    <div class="panel-body">
        <table class="table table-striped table-bordered" id="puq-data-table">
            <thead>
                <tr>
                    <th style="width:60px;">ID</th>
                    <th>Name</th>
                    <th>Description</th>
                    <th style="width:80px;">Default</th>
                    <th style="width:120px;">Actions</th>
                </tr>
            </thead>
            <tbody><tr><td colspan="5" class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading…</td></tr></tbody>
        </table>
        <div class="well well-sm" style="margin-top:15px;font-size:12px;">
            <strong>Placeholders:</strong>
            <code>{literal}{domain}{/literal}</code>
            <code>{literal}{server_ip}{/literal}</code>
            <code>{literal}{mail_server_ip}{/literal}</code>
            <code>{literal}{mail_server_hostname}{/literal}</code>
            <code>{literal}{ns1}{/literal}</code>
            <code>{literal}{ns2}{/literal}</code>
            <code>{literal}{ns3}{/literal}</code>
            <code>{literal}{ns4}{/literal}</code>
            <code>{literal}{ns5}{/literal}</code>
            <code>{literal}{ns6}{/literal}</code>
            <code>{literal}{ns7}{/literal}</code>
            <code>{literal}{ns8}{/literal}</code>
            <code>{literal}{client_id}{/literal}</code>
            <code>{literal}{service_id}{/literal}</code>
            <code>{literal}{year}{/literal}</code>
            <code>{literal}{unixtime}{/literal}</code>
        </div>
    </div>
</div>

<div class="modal fade" id="puq-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" id="puq-modal-title">DNS Zone Template</h4>
            </div>
            <div class="modal-body">
                <form id="puq-modal-form">
                    <input type="hidden" name="id" id="puq-field-id">
                    <div class="row">
                        <div class="col-md-8">
                            <div class="form-group" data-field="name">
                                <label>Name <span class="text-danger">*</span></label>
                                <input type="text" name="name" id="puq-field-name" class="form-control" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group" data-field="is_default" style="margin-top:25px;">
                                <label><input type="checkbox" name="is_default" id="puq-field-default" value="1"> Mark as default</label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group" data-field="description">
                        <label>Description</label>
                        <textarea name="description" id="puq-field-description" class="form-control" rows="2"></textarea>
                    </div>
                    <h5>Records</h5>
                    <table class="table table-condensed" id="puq-tpl-records">
                        <thead>
                            <tr>
                                <th style="width:90px;">Type</th>
                                <th style="width:130px;">Name</th>
                                <th>Value</th>
                                <th style="width:70px;">Pri</th>
                                <th style="width:90px;">TTL</th>
                                <th style="width:40px;"></th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <button type="button" class="btn btn-default btn-sm" id="puq-tpl-add-row"><i class="fa fa-plus"></i> Add row</button>
                    <input type="hidden" name="records" id="puq-tpl-records-json">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="puq-modal-save"><i class="fas fa-save"></i> Save</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="puq-seed-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"><i class="fa fa-download"></i> Seed DNS Zone Template from BIND file</h4>
            </div>
            <div class="modal-body">
                <p class="text-muted" style="margin-bottom:10px;">
                    Files live in <code>modules/addons/puq_web_hosting/dns_zone_seeds/</code>.
                    Drop additional <code>.bind</code> files there to expand the list. If a template
                    with the same name already exists, records are <strong>appended</strong>.
                </p>
                <div class="form-group">
                    <label for="puq-seed-file">Seed file</label>
                    <select id="puq-seed-file" class="form-control">
                        <option value="">— loading… —</option>
                    </select>
                </div>
                <div id="puq-seed-info" class="alert alert-info" style="display:none;"></div>
                <div class="form-group">
                    <label>Preview</label>
                    <textarea id="puq-seed-preview" class="form-control" rows="14" readonly style="font-family:monospace;font-size:12px;background:#f7f7f7;"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="puq-seed-apply"><i class="fa fa-download"></i> Seed</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="puq-delete-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Confirm Delete</h4>
            </div>
            <div class="modal-body">
                <p>Delete this DNS zone template?</p>
                <input type="hidden" id="puq-delete-id">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="puq-confirm-delete"><i class="fas fa-trash"></i> Delete</button>
            </div>
        </div>
    </div>
</div>

{literal}
<script>
(function(){
    var baseUrl = '{/literal}{$meta.admin_module_url}&ajax={literal}';
    var TYPES = ['A','AAAA','CNAME','MX','TXT','NS','SRV','CAA'];


    function load() {
        puqAjax({
            container: '#puq-data-table',
            loadingCaption: 'Loading templates…',
            url: baseUrl + 'listDnsZoneTemplates', dataType: 'json',
            success: function(r) {
                var $tbody = $('#puq-data-table tbody').empty();
                if (r.status !== 'success' || !r.data.length) {
                    $tbody.append('<tr><td colspan="5" class="text-center text-muted">No templates yet.</td></tr>');
                    return;
                }
                r.data.forEach(function(t) {
                    $tbody.append(
                        '<tr data-id="' + t.id + '">' +
                        '<td>' + t.id + '</td>' +
                        '<td><strong>' + esc(t.name) + '</strong></td>' +
                        '<td>' + esc(t.description || '') + '</td>' +
                        '<td class="text-center">' + (t.is_default == 1 ? '<i class="fa fa-check text-success"></i>' : '') + '</td>' +
                        '<td>' +
                          '<button class="btn btn-xs btn-primary puq-edit"><i class="fa fa-edit"></i></button> ' +
                          '<button class="btn btn-xs btn-danger puq-delete"><i class="fa fa-trash"></i></button>' +
                        '</td></tr>'
                    );
                });
            }
        });
    }

    function addRecordRow(r) {
        r = r || { record_type: 'A', name_pattern: '@', value_pattern: '', priority: '', ttl: 3600 };
        var typeOpts = TYPES.map(function(t){
            return '<option value="'+t+'"'+(t===r.record_type?' selected':'')+'>'+t+'</option>';
        }).join('');
        // Build the row without inlining record content into HTML attributes
        // (esc() leaves '"' intact, which breaks value="..." for TXT records
        // wrapped in double quotes). Use .val() after creation — safe for
        // any character.
        var $row = $(
            '<tr>' +
            '<td><select class="form-control input-sm rtype">' + typeOpts + '</select></td>' +
            '<td><input type="text" class="form-control input-sm rname"></td>' +
            '<td><input type="text" class="form-control input-sm rvalue"></td>' +
            '<td><input type="number" class="form-control input-sm rpri"></td>' +
            '<td><input type="number" class="form-control input-sm rttl"></td>' +
            '<td><button type="button" class="btn btn-xs btn-danger rdel"><i class="fa fa-times"></i></button></td>' +
            '</tr>'
        );
        $row.find('.rname').val(r.name_pattern || '');
        $row.find('.rvalue').val(r.value_pattern || '');
        $row.find('.rpri').val(r.priority == null ? '' : r.priority);
        $row.find('.rttl').val(r.ttl || 3600);
        $('#puq-tpl-records tbody').append($row);
    }

    function collectRecords() {
        var out = [];
        $('#puq-tpl-records tbody tr').each(function(i) {
            var $r = $(this);
            var pri = $r.find('.rpri').val();
            out.push({
                record_type: $r.find('.rtype').val(),
                name_pattern: $r.find('.rname').val(),
                value_pattern: $r.find('.rvalue').val(),
                priority: pri === '' ? null : parseInt(pri, 10),
                ttl: parseInt($r.find('.rttl').val(), 10) || 3600,
                sort_order: (i + 1) * 10
            });
        });
        return out;
    }

    function openModal(id) {
        var f = $('#puq-modal-form')[0];
        f.reset();
        formClearErrors('#puq-modal-form');
        $('#puq-tpl-records tbody').empty();
        $('#puq-field-id').val('');
        if (id) {
            $.ajax({
                url: baseUrl + 'getDnsZoneTemplate&id=' + id, dataType: 'json',
                success: function(r) {
                    if (r.status !== 'success') { showNotification(r.msg || 'Load failed.', 'error'); return; }
                    var t = r.data;
                    $('#puq-modal-title').text('Edit Template');
                    $('#puq-field-id').val(t.id);
                    $('#puq-field-name').val(t.name);
                    $('#puq-field-description').val(t.description || '');
                    $('#puq-field-default').prop('checked', t.is_default == 1);
                    (t.records || []).forEach(addRecordRow);
                    $('#puq-modal').modal('show');
                }
            });
        } else {
            $('#puq-modal-title').text('Add Template');
            addRecordRow();
            $('#puq-modal').modal('show');
        }
    }

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

        $('#puq-add-btn').on('click', function(){ openModal(null); });

        var seedFilesCache = [];

        function renderSeedInfo(file) {
            var $info = $('#puq-seed-info');
            var $preview = $('#puq-seed-preview');
            if (!file) {
                $info.hide().empty();
                $preview.val('');
                return;
            }
            $preview.val(file.content || '');
            var lines = [];
            lines.push('<strong>' + esc(file.name) + '</strong>');
            if (file.description) lines.push('<br><span>' + esc(file.description) + '</span>');
            lines.push('<br><small>' + (file.record_count || 0) + ' record(s) · ' + esc(file.filename) + '</small>');
            if (file.existing_template_id) {
                $info.removeClass('alert-info').addClass('alert-warning');
                lines.push('<br><i class="fa fa-plus-circle"></i> Template "<strong>' + esc(file.name) + '</strong>" already exists (id ' + file.existing_template_id + ') — records will be <strong>appended</strong>.');
            } else {
                $info.removeClass('alert-warning').addClass('alert-info');
                lines.push('<br><i class="fa fa-magic"></i> Will create a new template named "<strong>' + esc(file.name) + '</strong>".');
            }
            $info.html(lines.join('')).show();
        }

        function loadSeedFiles(preselect) {
            var $sel = $('#puq-seed-file');
            $sel.html('<option value="">— loading… —</option>');
            $.ajax({
                url: baseUrl + 'listDnsZoneSeeds', dataType: 'json',
                success: function(r) {
                    seedFilesCache = (r.status === 'success' && r.data) ? r.data : [];
                    if (!seedFilesCache.length) {
                        $sel.html('<option value="">— no .bind files found —</option>');
                        renderSeedInfo(null);
                        return;
                    }
                    var html = '<option value="">— choose a file —</option>';
                    seedFilesCache.forEach(function(f) {
                        var tag = f.existing_template_id ? ' [append]' : ' [new]';
                        html += '<option value="' + esc(f.filename) + '">'
                            + esc(f.name) + ' — ' + esc(f.filename)
                            + ' (' + (f.record_count || 0) + ' rec)' + tag
                            + '</option>';
                    });
                    $sel.html(html);
                    if (preselect) {
                        $sel.val(preselect).trigger('change');
                    }
                },
                error: function() {
                    $sel.html('<option value="">— load failed —</option>');
                    showNotification('Could not load seed files.', 'error');
                }
            });
        }

        $('#puq-seed-btn').on('click', function() {
            renderSeedInfo(null);
            $('#puq-seed-file').val('');
            $('#puq-seed-modal').modal('show');
            loadSeedFiles();
        });

        $('#puq-seed-file').on('change', function() {
            var fn = $(this).val();
            var file = seedFilesCache.find(function(f) { return f.filename === fn; });
            renderSeedInfo(file || null);
        });

        $('#puq-seed-apply').on('click', function() {
            var btn = this;
            var fn = $('#puq-seed-file').val();
            if (!fn) { showNotification('Please choose a seed file.', 'warning'); return; }
            btnSpinner(btn, 'Seeding...');
            $.ajax({
                url: baseUrl + 'seedDnsZoneFromFile', type: 'POST', data: { filename: fn }, dataType: 'json',
                success: function(r) {
                    showNotification(r.msg || (r.status === 'success' ? 'Seeded.' : 'Failed.'), r.status === 'success' ? 'success' : 'error');
                    if (r.status === 'success') {
                        $('#puq-seed-modal').modal('hide');
                        load();
                    }
                },
                error: function() { showNotification('Request failed.', 'error'); },
                complete: function() { btnRestore(btn, 'download', 'Seed'); }
            });
        });
        $('#puq-data-table').on('click', '.puq-edit', function() { openModal($(this).closest('tr').data('id')); });
        $('#puq-tpl-add-row').on('click', function(){ addRecordRow(); });
        $('#puq-tpl-records').on('click', '.rdel', function(){ $(this).closest('tr').remove(); });

        $('#puq-modal-save').on('click', function() {
            $('#puq-tpl-records-json').val(JSON.stringify(collectRecords()));
            formSubmit({
                btn: this, form: '#puq-modal-form', baseUrl: baseUrl, action: 'saveDnsZoneTemplate',
                onSuccess: function() { $('#puq-modal').modal('hide'); load(); }
            });
        });

        $('#puq-data-table').on('click', '.puq-delete', function() {
            $('#puq-delete-id').val($(this).closest('tr').data('id'));
            $('#puq-delete-modal').modal('show');
        });

        $('#puq-confirm-delete').on('click', function() {
            var btn = this;
            btnSpinner(btn, 'Deleting...');
            $.ajax({
                url: baseUrl + 'deleteDnsZoneTemplate', type: 'POST', data: { id: $('#puq-delete-id').val() }, dataType: 'json',
                success: function(r) {
                    if (r.status === 'success') { showNotification(r.msg || 'Template deleted.', 'success'); load(); }
                    else { showNotification(r.msg || 'Delete failed.', 'error'); }
                    $('#puq-delete-modal').modal('hide');
                },
                error: function() { showNotification('Request failed.', 'error'); $('#puq-delete-modal').modal('hide'); },
                complete: function() { btnRestore(btn, 'trash', 'Delete'); }
            });
        });
    });
})();
</script>
{/literal}
