<div class="row">
    <div class="col-sm-4">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title"><i class="fa fa-list"></i> Services</h3>
            </div>
            <div class="panel-body text-center">
                <h2 id="puq-count-services"><i class="fa fa-spinner fa-spin"></i></h2>
                <a href="{$meta.admin_module_url}&page=services_summary" class="btn btn-default btn-sm puq-nav-link">View</a>
            </div>
        </div>
    </div>
    <div class="col-sm-4">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title"><i class="fa fa-server"></i> Servers</h3>
            </div>
            <div class="panel-body text-center">
                <h2 id="puq-count-servers"><i class="fa fa-spinner fa-spin"></i></h2>
                <a href="{$meta.admin_module_url}&page=web_servers" class="btn btn-default btn-sm puq-nav-link">Manage</a>
            </div>
        </div>
    </div>
    <div class="col-sm-4">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title"><i class="fa fa-tasks"></i> Task Queue</h3>
            </div>
            <div class="panel-body text-center">
                <h2 id="puq-count-tasks"><i class="fa fa-spinner fa-spin"></i></h2>
                <a href="{$meta.admin_module_url}&page=task_queue" class="btn btn-default btn-sm puq-nav-link">View</a>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-sm-4">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title"><i class="fa fa-globe"></i> DNS Zones</h3>
            </div>
            <div class="panel-body text-center">
                <h2 id="puq-count-zones"><i class="fa fa-spinner fa-spin"></i></h2>
                <a href="{$meta.admin_module_url}&page=dns_zones" class="btn btn-default btn-sm puq-nav-link">Manage</a>
            </div>
        </div>
    </div>
    <div class="col-sm-4">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title"><i class="fa fa-layer-group"></i> Server Groups</h3>
            </div>
            <div class="panel-body text-center">
                <p class="text-muted" style="margin-top:10px;">Organize servers by location or tier</p>
                <a href="{$meta.admin_module_url}&page=server_groups" class="btn btn-default btn-sm puq-nav-link">Manage</a>
            </div>
        </div>
    </div>
    <div class="col-sm-4">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title"><i class="fa fa-cog"></i> Settings</h3>
            </div>
            <div class="panel-body text-center">
                <p class="text-muted" style="margin-top:10px;">Cron, retry policy, tables</p>
                <a href="{$meta.admin_module_url}&page=settings_general" class="btn btn-default btn-sm puq-nav-link">Configure</a>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <div class="panel panel-default">
            <div class="panel-heading"><h3 class="panel-title"><i class="fa fa-server"></i> Server capacity</h3></div>
            <div class="panel-body" style="padding:0;">
                <table class="table table-condensed" id="puq-dash-servers" style="margin-bottom:0;font-size:12px;">
                    <thead><tr><th>Type</th><th>Name</th><th>Capacity</th><th>Last sync</th></tr></thead>
                    <tbody><tr><td colspan="4" class="text-center"><i class="fa fa-spinner fa-spin"></i></td></tr></tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="panel panel-default">
            <div class="panel-heading"><h3 class="panel-title"><i class="fa fa-exclamation-triangle text-danger"></i> Recent terminal errors</h3></div>
            <div class="panel-body" style="padding:0;">
                <table class="table table-condensed" id="puq-dash-errors" style="margin-bottom:0;font-size:12px;">
                    <thead><tr><th>Service</th><th>Action</th><th>Error</th></tr></thead>
                    <tbody><tr><td colspan="3" class="text-center"><i class="fa fa-spinner fa-spin"></i></td></tr></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading"><h3 class="panel-title"><i class="fa fa-clock"></i> Recent services</h3></div>
            <div class="panel-body" style="padding:0;">
                <table class="table table-condensed table-hover" id="puq-dash-recent" style="margin-bottom:0;font-size:12px;">
                    <thead><tr><th>ID</th><th>Domain</th><th>WHMCS</th><th>Deploy</th><th>Created</th></tr></thead>
                    <tbody><tr><td colspan="5" class="text-center"><i class="fa fa-spinner fa-spin"></i></td></tr></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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

    var badge = window.statusBadge;
    function capacityBar(used, max) {
        if (!max) return '<small class="text-muted">' + (used==null?'—':used) + ' / —</small>';
        var pct = Math.min(100, Math.round(used*100/max));
        var color = pct > 90 ? '#dc3545' : pct > 70 ? '#ffc107' : '#28a745';
        return '<small>' + used + ' / ' + max + '</small>' +
               '<div style="width:100%;height:6px;background:#eee;border-radius:3px;overflow:hidden;">' +
               '<div style="height:100%;width:'+pct+'%;background:'+color+';"></div></div>';
    }

    // Render a visible error across all dashboard widgets instead of leaving
    // their spinners running forever when the stats call fails (the backend
    // returns {status:error, msg, where} with HTTP 200, so the transport-level
    // error: handler never fires — we must catch status!=='success' here).
    function dashError(msg) {
        $('#puq-count-services, #puq-count-servers, #puq-count-tasks, #puq-count-zones')
            .html('<i class="fa fa-exclamation-triangle text-danger" title="' + esc(msg || 'Failed to load') + '"></i>');
        var cell = '<tr><td colspan="6" class="text-danger text-center" style="padding:14px;"><i class="fa fa-exclamation-triangle"></i> ' + esc(msg || 'Failed to load dashboard.') + '</td></tr>';
        $('#puq-dash-servers tbody, #puq-dash-errors tbody, #puq-dash-recent tbody').html(cell);
    }

    $(document).ready(function(){
        puqAjax({
            container: '#puq-dash-recent',
            loadingCaption: 'Loading dashboard…',
            url: baseUrl + 'getDashboardStats',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (!response || response.status !== 'success') {
                    dashError((response && response.msg) ? response.msg : 'Failed to load dashboard.');
                    return;
                }
                var d = response.data;

                $('#puq-count-services').text(d.services_total || 0);
                $('#puq-count-servers').text((d.servers || []).length);
                var tasksTotal = 0; Object.values(d.tasks_by_status || {}).forEach(function(n){ tasksTotal += parseInt(n,10); });
                $('#puq-count-tasks').text(tasksTotal);

                $('#puq-count-zones').text(d.zones_total || 0);

                // Server capacity table
                var $s = $('#puq-dash-servers tbody').empty();
                (d.servers || []).forEach(function(srv){
                    $s.append('<tr>'+
                        '<td><code>'+esc(srv.type)+'</code></td>'+
                        '<td>'+esc(srv.name)+'<br><small class="text-muted">'+esc(srv.hostname)+'</small></td>'+
                        '<td>'+capacityBar(srv.capacity_used, srv.capacity_max)+'</td>'+
                        '<td><small>'+esc(srv.last_sync_at||'—')+'</small></td>'+
                        '</tr>');
                });
                if (!(d.servers || []).length) $s.append('<tr><td colspan="4" class="text-muted text-center">No active servers.</td></tr>');

                // Errors
                var $e = $('#puq-dash-errors tbody').empty();
                (d.recent_errors || []).forEach(function(t){
                    $e.append('<tr>'+
                        '<td>'+(t.service_id||'—')+'</td>'+
                        '<td><code>'+esc(t.target_type)+'/'+esc(t.action)+'</code></td>'+
                        '<td class="text-danger" style="max-width:280px;word-break:break-all;">'+esc((t.error_message||'').substring(0,180))+'</td>'+
                        '</tr>');
                });
                if (!(d.recent_errors || []).length) $e.append('<tr><td colspan="3" class="text-muted text-center">No terminal errors.</td></tr>');

                // Recent services
                var $r = $('#puq-dash-recent tbody').empty();
                (d.recent_services || []).forEach(function(svc){
                    $r.append('<tr>'+
                        '<td>'+svc.id+'</td>'+
                        '<td><strong>'+esc(svc.domain)+'</strong></td>'+
                        '<td>'+badge(svc.domainstatus||'—')+'</td>'+
                        '<td>'+badge(svc.deploy_status)+'</td>'+
                        '<td><small>'+esc(svc.created_at||'')+'</small></td>'+
                        '</tr>');
                });
                if (!(d.recent_services || []).length) $r.append('<tr><td colspan="5" class="text-muted text-center">No services yet.</td></tr>');
            },
            error: function() { dashError('Request failed — could not reach the server.'); }
        });
    });
})();
</script>
{/literal}
