{* Statistics admin page. Pure DB read from puqWebHosting_services.usage
   + .limits JSON. The "Refresh all usage" button enqueues server.syncUsage
   tasks (one per server, not per service); cron drains and writes back. *}
<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title pull-left"><i class="fa fa-chart-bar"></i> Statistics</h3>
        <div class="pull-right">
            <button class="btn btn-default btn-sm" id="puq-stats-refresh"><i class="fa fa-redo"></i> Reload</button>
            <button class="btn btn-warning btn-sm" id="puq-stats-sync-all" title="Enqueue server.syncUsage for every server (one task per server, batch fetch)"><i class="fa fa-sync"></i> Refresh all usage</button>
        </div>
        <div class="clearfix"></div>
    </div>
    <div class="panel-body">

        <div style="overflow-x:auto;" id="puq-stats-wrap">
        <table class="table table-striped table-condensed table-hover" id="puq-stats-table" style="width:100%;">
            <thead>
                <tr class="active">
                    <th rowspan="2">Domain</th>
                    <th rowspan="2">Status</th>
                    <th colspan="7" class="text-center" style="background:#eef5fb;">Web</th>
                    <th colspan="4" class="text-center" style="background:#eef8ee;">Mail</th>
                    <th rowspan="2">Updated</th>
                </tr>
                <tr>
                    <th style="background:#eef5fb;" title="Web disk usage">Disk</th>
                    <th style="background:#eef5fb;" title="Web bandwidth this period">Bandwidth</th>
                    <th style="background:#eef5fb;" title="DNS records across all zones">DNS rec</th>
                    <th style="background:#eef5fb;" title="MySQL/PostgreSQL databases">DBs</th>
                    <th style="background:#eef5fb;" title="FTP accounts">FTP</th>
                    <th style="background:#eef5fb;" title="Cron jobs">Cron</th>
                    <th style="background:#eef5fb;" title="Web backups">Backups</th>
                    <th style="background:#eef8ee;" title="Mail disk usage">Disk</th>
                    <th style="background:#eef8ee;" title="Mailboxes">Accounts</th>
                    <th style="background:#eef8ee;" title="Mail backups">Backups</th>
                </tr>
            </thead>
            <tbody><tr><td colspan="13" class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading…</td></tr></tbody>
        </table>
        </div>
    </div>
</div>

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


    // Format MB → "1.0 GB" / "500 MB" / "0".
    function fmtMB(v){
        if (v == null || v === '') return '0';
        var n = parseFloat(v);
        if (!isFinite(n) || n === 0) return '0';
        if (n >= 1024) return (n/1024).toFixed(1) + ' GB';
        return Math.round(n) + ' MB';
    }
    function fmtLimitMB(lim){
        lim = parseFloat(lim) || 0;
        if (lim <= 0) return '<span style="font-size:14px;">∞</span>';
        if (lim >= 1024) return (lim/1024).toFixed(1) + ' GB';
        return Math.round(lim) + ' MB';
    }
    function fmtLimitCount(lim){
        lim = parseInt(lim, 10) || 0;
        return lim > 0 ? String(lim) : '<span style="font-size:14px;">∞</span>';
    }

    // Used / limit cell for MB-valued metrics. Pill color reflects %.
    function mbCell(used, lim){
        used = parseFloat(used) || 0;
        lim  = parseFloat(lim)  || 0;
        var pctHtml = '';
        if (lim > 0) {
            var pct = Math.round((used / lim) * 100);
            var cls = pct >= 90 ? 'danger' : (pct >= 75 ? 'warning' : 'success');
            pctHtml = ' <small class="label label-' + cls + '">' + pct + '%</small>';
        }
        return '<span class="text-nowrap">' + fmtMB(used) + ' <small class="text-muted">/</small> '
             + fmtLimitMB(lim) + pctHtml + '</span>';
    }

    // Used / limit cell for plain counter metrics.
    function countCell(used, lim){
        used = parseInt(used, 10) || 0;
        lim  = parseInt(lim, 10)  || 0;
        var pctHtml = '';
        if (lim > 0) {
            var pct = Math.round((used / lim) * 100);
            var cls = pct >= 90 ? 'danger' : (pct >= 75 ? 'warning' : 'success');
            pctHtml = ' <small class="label label-' + cls + '">' + pct + '%</small>';
        }
        return '<span class="text-nowrap">' + used + ' <small class="text-muted">/</small> '
             + fmtLimitCount(lim) + pctHtml + '</span>';
    }

    function load() {
        puqAjax({ container: '#puq-stats-wrap', loadingCaption: 'Loading statistics…',
            url: baseUrl + 'getStatisticsSnapshot', dataType: 'json',
            success: function(r){
                if (r.status !== 'success' || !r.data) {
                    $('#puq-stats-table tbody').html('<tr><td colspan="13" class="text-danger">' + esc(r.msg || 'Load failed') + '</td></tr>');
                    return;
                }
                if (dt) { dt.destroy(); }
                $('#puq-stats-table tbody').empty();
                (r.data.services || []).forEach(function(s){
                    var depCls = ({active:'success',error:'danger',queued:'warning',deploying:'info',pending_terminate:'warning',terminating:'warning'})[s.deploy_status] || 'default';
                    var svcUrl = 'clientsservices.php?id=' + s.whmcs_service_id;
                    $('#puq-stats-table tbody').append('<tr>' +
                        '<td><a href="' + svcUrl + '" target="_blank"><strong>' + esc(s.domain) + '</strong></a></td>' +
                        '<td><span class="label label-' + depCls + '">' + esc(s.deploy_status) + '</span></td>' +
                        // Web group
                        '<td>' + mbCell(s.disk_web_mb,    s.disk_web_limit)    + '</td>' +
                        '<td>' + mbCell(s.bw_web_mb,      s.bw_web_limit)      + '</td>' +
                        '<td>' + countCell(s.dns_records, s.dns_records_limit) + '</td>' +
                        '<td>' + countCell(s.databases,   s.databases_limit)   + '</td>' +
                        '<td>' + countCell(s.ftp_accounts,s.ftp_limit)         + '</td>' +
                        '<td>' + countCell(s.cron_jobs,   s.cron_limit)        + '</td>' +
                        '<td>' + countCell(s.backups_web, s.backups_web_limit) + '</td>' +
                        // Mail group (no bandwidth — not tracked)
                        '<td>' + mbCell(s.disk_mail_mb,   s.disk_mail_limit)   + '</td>' +
                        '<td>' + countCell(s.mail_accounts, s.mail_acc_limit)  + '</td>' +
                        '<td>' + countCell(s.backups_mail,s.backups_mail_limit)+ '</td>' +
                        '<td><small class="text-muted text-nowrap">' + esc(String(s.usage_updated || '').substring(0,16)) + '</small></td>' +
                        '</tr>');
                });
                // Guard the DataTable init: if the library isn't available (or
                // throws), a thrown success callback would skip jQuery's
                // complete() and leave the puqAjax spinner stuck forever. The
                // plain table still renders without it.
                try {
                    dt = $('#puq-stats-table').DataTable({
                        order: [[0, 'asc']], pageLength: 50, autoWidth: false,
                        columnDefs: [{ orderable: false, targets: [12] }]
                    });
                } catch (e) {
                    if (window.console) console.error('Statistics DataTable init failed:', e);
                }
            },
            error: function(){
                $('#puq-stats-table tbody').html('<tr><td colspan="13" class="text-danger">Request failed.</td></tr>');
            }
        });
    }

    $('#puq-stats-refresh').on('click', load);
    $('#puq-stats-sync-all').on('click', function(){
        puqConfirm({
            type: 'info', icon: 'fa-sync',
            title: 'Refresh usage for all servers?',
            text: 'A single sync task is queued per server (one SSH round-trip each) to fetch fresh disk/bandwidth metrics for all users on that server.',
            ok: 'Queue refresh', cancel: 'Cancel',
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    $.ajax({ url: baseUrl + 'refreshAllUsage', type: 'POST', dataType: 'json',
                        success: function(r){
                            if (r.status === 'success') { showNotification(r.msg || 'Queued.', 'success'); resolve(); }
                            else reject(new Error(r.msg || 'Failed'));
                        },
                        error: function(){ reject(new Error('Request failed')); }
                    });
                });
            }
        });
    });

    $(document).ready(load);
})();
</script>
{/literal}
