<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title pull-left"><i class="fa fa-layer-group"></i> Server Groups</h3>
        <a class="btn btn-primary btn-sm pull-right" href="{$meta.admin_module_url}&page=group_edit"><i class="fa fa-plus"></i> Add Server Group</a>
        <div class="clearfix"></div>
    </div>
    <div class="panel-body">
        <p class="text-muted small">
            Click a row's <em>Open</em> button to manage the group: actions / Hestia config / standard files.
            <span class="label label-warning">H</span> = managed Hestia config keys.
        </p>
        <table class="table table-striped table-bordered" id="puq-data-table" style="width:100%;">
            <thead>
                <tr>
                    <th style="width:70px;">ID</th>
                    <th>Name</th>
                    <th>Description</th>
                    <th style="width:90px;">Managed</th>
                    <th style="width:220px;">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>
</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 server group? Cannot be undone.</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>

<div class="modal fade" id="puq-apply-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">Apply Hestia config</h4>
            </div>
            <div class="modal-body">
                <p>Push this group's Hestia config to every active server (skips keys already in sync)?</p>
                <input type="hidden" id="puq-apply-id">
            </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-confirm-apply"><i class="fas fa-magic"></i> Apply</button>
            </div>
        </div>
    </div>
</div>

{literal}
<script>
(function(){
    var baseUrl = '{/literal}{$meta.admin_module_url}&ajax={literal}';
    var pageUrl = '{/literal}{$meta.admin_module_url}{literal}';

    function countObjKeys(jsonStr) {
        if (!jsonStr) return 0;
        try { var o = JSON.parse(jsonStr); return (o && typeof o === 'object') ? Object.keys(o).length : 0; } catch(e) { return 0; }
    }

    function loadGroups() {
        puqAjax({
            container: '#puq-data-table',
            loadingCaption: 'Loading groups…',
            url: baseUrl + 'listServerGroups', 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 server groups yet — click <em>Add Server Group</em> to create one.</td></tr>');
                    return;
                }
                r.data.forEach(function(g) {
                    var hestiaKeys = countObjKeys(g.config_hestia);
                    var badges = '<small>H:' + (hestiaKeys > 0 ? '<span class="label label-warning">' + hestiaKeys + '</span>' : '<span class="text-muted">—</span>') + '</small>';
                    var openHref = pageUrl + '&page=group_edit&id=' + g.id;
                    $tbody.append(
                        '<tr data-id="' + g.id + '">' +
                          '<td>' + g.id + '</td>' +
                          '<td><strong>' + esc(g.name) + '</strong></td>' +
                          '<td>' + esc(g.description || '') + '</td>' +
                          '<td>' + badges + '</td>' +
                          '<td>' +
                            '<a class="btn btn-xs btn-primary" href="' + openHref + '"><i class="fa fa-folder-open"></i> Open</a> ' +
                            '<button class="btn btn-xs btn-warning puq-apply-cfg" title="Apply Hestia config to every active server"><i class="fa fa-magic"></i> Apply</button> ' +
                            '<button class="btn btn-xs btn-danger puq-delete"><i class="fa fa-trash"></i></button>' +
                          '</td>' +
                        '</tr>'
                    );
                });
            }
        });
    }

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

        $('#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 + 'deleteServerGroup', type: 'POST', data: { id: $('#puq-delete-id').val() }, dataType: 'json',
                success: function(r){
                    if (r.status === 'success') { showNotification(r.msg || 'Deleted.', 'success'); loadGroups(); }
                    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'); }
            });
        });

        $('#puq-data-table').on('click', '.puq-apply-cfg', function(){
            $('#puq-apply-id').val($(this).closest('tr').data('id'));
            $('#puq-apply-modal').modal('show');
        });
        $('#puq-confirm-apply').on('click', function(){
            var btn = this; btnSpinner(btn, 'Queuing...');
            $.ajax({
                url: baseUrl + 'applyGroupConfigToAllServers', type: 'POST', data: { group_id: $('#puq-apply-id').val() }, dataType: 'json',
                success: function(r){
                    showNotification(r.msg || (r.status === 'success' ? 'Queued.' : 'Apply failed.'), r.status === 'success' ? 'success' : 'error');
                    $('#puq-apply-modal').modal('hide');
                },
                error: function(){ showNotification('Request failed.', 'error'); $('#puq-apply-modal').modal('hide'); },
                complete: function(){ btnRestore(btn, 'magic', 'Apply'); }
            });
        });
    });
})();
</script>
{/literal}
