{* Overview tab — status, limits, timestamps. Driven by ajax getServiceOverview
   (read-only). Header card on the shell already shows servers/usernames; this
   tab focuses on configoption-resolved limits and timestamps. *}
<div id="puq-no-domain-banner" class="alert alert-warning" style="display:none;">
    <div style="display:flex; align-items:center; gap:12px;">
        <i class="fa fa-exclamation-triangle fa-2x"></i>
        <div style="flex:1;">
            <strong>Domain not set.</strong> The service is provisioned but no
            domain is attached — customer should set one through the client
            area, or you can set it here.
        </div>
        <button type="button" class="btn btn-warning" id="puq-set-domain-admin">
            <i class="fa fa-globe"></i> Set domain
        </button>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <h4><i class="fa fa-info-circle"></i> Resolved limits</h4>
        <p class="text-muted small">Limits resolved at create-time (configoptions + Configurable Options overlay). Stored verbatim in <code>puqWebHosting_services.limits</code>.</p>
        <table class="table table-bordered table-condensed" id="puq-svc-limits-table">
            <thead><tr><th>Key</th><th>Value</th></tr></thead>
            <tbody><tr><td colspan="2" class="text-muted text-center"><i class="fa fa-spinner fa-spin"></i> Loading…</td></tr></tbody>
        </table>
    </div>
    <div class="col-md-6">
        <h4><i class="fa fa-chart-bar"></i> Usage</h4>
        <p class="text-muted small">Latest snapshot in <code>puqWebHosting_services.usage</code>. Synced by cron <code>syncServerStatus</code> (enqueues <code>server.syncUsage</code> per active server).</p>
        <table class="table table-bordered table-condensed" id="puq-svc-usage-table">
            <thead><tr><th>Metric</th><th>Value</th></tr></thead>
            <tbody><tr><td colspan="2" class="text-muted text-center"><i class="fa fa-spinner fa-spin"></i> Loading…</td></tr></tbody>
        </table>
        <button type="button" class="btn btn-default btn-xs" id="puq-svc-usage-refresh"><i class="fa fa-sync"></i> Force usage sync</button>
    </div>
</div>
<div class="row" style="margin-top:18px;">
    <div class="col-md-12">
        <div class="panel panel-default" id="puq-verify-panel">
            <div class="panel-heading">
                <strong><i class="fa fa-stethoscope"></i> Verify &amp; Repair</strong>
                <span class="pull-right">
                    <label style="font-weight:normal; margin-right:12px;">
                        <input type="checkbox" id="puq-toggle-external-dns"> External DNS (client manages on registrar)
                    </label>
                    <button type="button" class="btn btn-sm btn-primary" id="puq-verify-run">
                        <i class="fa fa-search"></i> Run verification
                    </button>
                </span>
            </div>
            <div class="panel-body">
                <div id="puq-verify-meta" class="text-muted small" style="margin-bottom:8px;"></div>
                <div id="puq-verify-result" class="text-muted">Click "Run verification" to probe panels and DNS.</div>
            </div>
        </div>
    </div>
</div>

<div class="row" style="margin-top:14px;">
    <div class="col-md-12">
        <h4><i class="fa fa-clock"></i> Recent activity</h4>
        <table class="table table-striped table-condensed" id="puq-svc-recent-table">
            <thead><tr>
                <th style="width:60px;">Task</th>
                <th>Action</th>
                <th style="width:90px;">Status</th>
                <th style="width:140px;">Started</th>
                <th style="width:140px;">Finished</th>
                <th></th>
            </tr></thead>
            <tbody><tr><td colspan="6" class="text-muted text-center"><i class="fa fa-spinner fa-spin"></i> Loading…</td></tr></tbody>
        </table>
    </div>
</div>
{literal}
<script>
(window.puqSvc = window.puqSvc || {}).init_overview = function(ctx){
    var esc = ctx.esc, baseUrl = ctx.baseUrl, puqId = ctx.puqId, fmtDate = ctx.fmtDate;
    function load() {
        puqAjax({
            container: '#tab-overview',
            loadingCaption: 'Loading overview…',
            url: baseUrl + 'getServiceOverview&id=' + puqId,
            success: function(r){
                if (r.status !== 'success' || !r.data) {
                    $('#puq-svc-limits-table tbody').html('<tr><td colspan="2" class="text-danger">' + esc(r.msg || 'Load failed') + '</td></tr>');
                    return;
                }
                var d = r.data;
                // Domain-empty banner
                $('#puq-no-domain-banner').toggle(!d.domain || d.domain === '');
                // Verify panel header line
                var modeLabel = parseInt(d.external_dns, 10) === 1
                    ? '<span class="label label-default">external DNS</span>'
                    : '<span class="label label-info">our DNS</span>';
                var meta = 'Domain: <code>' + (d.domain ? esc(d.domain) : '<em>not set</em>') + '</code> &nbsp;·&nbsp; ' + modeLabel;
                if (d.ns_verified_at)  meta += ' &nbsp;·&nbsp; NS verified ' + esc(d.ns_verified_at);
                if (d.dns_verified_at) meta += ' &nbsp;·&nbsp; DNS records verified ' + esc(d.dns_verified_at);
                $('#puq-verify-meta').html(meta);
                $('#puq-toggle-external-dns').prop('checked', parseInt(d.external_dns, 10) === 1);
                var $lim = $('#puq-svc-limits-table tbody').empty();
                var keys = Object.keys(d.limits || {}).sort();
                if (!keys.length) {
                    $lim.append('<tr><td colspan="2" class="text-muted">(empty)</td></tr>');
                } else {
                    keys.forEach(function(k){
                        $lim.append('<tr><td><code>' + esc(k) + '</code></td><td>' + esc(d.limits[k]) + '</td></tr>');
                    });
                }
                var $u = $('#puq-svc-usage-table tbody').empty();
                var ukeys = Object.keys(d.usage || {}).sort();
                if (!ukeys.length) {
                    $u.append('<tr><td colspan="2" class="text-muted">(no sync yet)</td></tr>');
                } else {
                    ukeys.forEach(function(k){
                        $u.append('<tr><td><code>' + esc(k) + '</code></td><td>' + esc(d.usage[k]) + '</td></tr>');
                    });
                }
                var $rt = $('#puq-svc-recent-table tbody').empty();
                (d.recent_tasks || []).forEach(function(t){
                    var cls = ({queued:'default',running:'info',success:'success',error:'danger',cancelled:'warning'})[t.status] || 'default';
                    $rt.append('<tr>' +
                        '<td>#' + esc(t.id) + '</td>' +
                        '<td><code>' + esc(t.action) + '</code></td>' +
                        '<td><span class="label label-' + cls + '">' + esc(t.status) + '</span></td>' +
                        '<td>' + fmtDate(t.started_at) + '</td>' +
                        '<td>' + fmtDate(t.finished_at) + '</td>' +
                        '<td><button class="btn btn-xs btn-default puq-task-log" data-id="' + esc(t.id) + '"><i class="fa fa-search"></i></button></td>' +
                        '</tr>');
                });
                if (!(d.recent_tasks || []).length) {
                    $rt.append('<tr><td colspan="6" class="text-muted">No recent tasks.</td></tr>');
                }
            }
        });
    }
    // Auto-refresh while any task is queued/running. Stops on tab leave.
    load = ctx.armAutoRefresh('overview', {
        selector: '#puq-svc-recent-table',
        load: load,
        states: ['queued','running']
    });
    load();
    $('#puq-svc-usage-refresh').on('click', function(){
        var btn = this; btnSpinner(btn, 'Queuing sync...');
        $.ajax({ url: baseUrl + 'syncServiceUsageNow', type: 'POST', data: { id: puqId }, dataType: 'json',
            success: function(r){
                showNotification(r.msg || 'Done', r.status === 'success' ? 'success' : 'error');
                // Tasks tab auto-refresh will pick up the server.syncUsage task
                // and the Overview will reload its counts when the task finishes.
                if (r.status === 'success' && typeof load === 'function') load();
            },
            complete: function(){ btnRestore(btn, 'sync', 'Force usage sync'); }
        });
    });
    $('#tab-overview').on('click', '.puq-task-log', function(){
        var id = $(this).data('id'); if (typeof puqOpenTaskLog === 'function') puqOpenTaskLog(id);
    });

    // ----- Verify & Repair -----
    function statusBadge(s, ok, bad){
        var label = 'default', text = s;
        if (s === ok) label = 'success';
        else if (s === bad) label = 'danger';
        else if (s === 'error') label = 'warning';
        return '<span class="label label-' + label + '">' + esc(text) + '</span>';
    }

    function renderVerify(d){
        var html = '';
        // Web
        if (d.web) {
            html += '<div style="margin-bottom:10px;"><strong>Web domain</strong> <code>' + esc(d.domain) + '</code> on <em>' + esc(d.web.server_name) + '</em> &nbsp; ' +
                statusBadge(d.web.status, 'found', 'not_found');
            if (d.web.error) html += ' <span class="text-danger small">' + esc(d.web.error) + '</span>';
            if (d.web.status !== 'found') {
                html += ' <button class="btn btn-xs btn-warning puq-recreate" data-kind="web-domain" style="margin-left:6px;"><i class="fa fa-plus"></i> Create</button>';
            }
            html += ' <button class="btn btn-xs btn-default puq-recreate" data-kind="web-package" title="Rewrite .pkg + re-apply"><i class="fa fa-archive"></i> Re-apply package</button>';
            html += '</div>';
        }
        // Mail
        if (d.mail) {
            html += '<div style="margin-bottom:10px;"><strong>Mail domain</strong> <code>' + esc(d.domain) + '</code> on <em>' + esc(d.mail.server_name) + '</em> &nbsp; ' +
                statusBadge(d.mail.status, 'found', 'not_found');
            if (d.mail.error) html += ' <span class="text-danger small">' + esc(d.mail.error) + '</span>';
            if (d.mail.status !== 'found') {
                html += ' <button class="btn btn-xs btn-warning puq-recreate" data-kind="mail-domain" style="margin-left:6px;"><i class="fa fa-plus"></i> Create</button>';
            }
            html += ' <button class="btn btn-xs btn-default puq-recreate" data-kind="mail-package"><i class="fa fa-archive"></i> Re-apply package</button>';
            html += '</div>';
        }
        // DNS zones
        if (d.dns && d.dns.length) {
            html += '<div style="margin-top:14px;"><strong>DNS zones (' + d.dns.length + ' server' + (d.dns.length === 1 ? '' : 's') + ')</strong></div>';
            html += '<table class="table table-condensed" style="margin-top:6px;"><thead><tr><th>Server</th><th>Panel status</th><th>Local zone</th><th>Records (local)</th><th>Actions</th></tr></thead><tbody>';
            d.dns.forEach(function(z){
                html += '<tr>' +
                    '<td><em>' + esc(z.server_name) + '</em></td>' +
                    '<td>' + statusBadge(z.status, 'found', 'not_found') + (z.error ? ' <small class="text-danger">' + esc(z.error) + '</small>' : '') + '</td>' +
                    '<td>' + esc(z.local_status) + '</td>' +
                    '<td>' + esc(z.records_local) + '</td>' +
                    '<td>' +
                        '<button class="btn btn-xs btn-warning puq-recreate" data-kind="dns-zone" data-sid="' + esc(z.server_id) + '" title="Re-fire dns.addZone"><i class="fa fa-globe"></i> Recreate zone</button> ' +
                        '<button class="btn btn-xs btn-default puq-recreate" data-kind="dns-package" data-sid="' + esc(z.server_id) + '" title="Rewrite Hestia DNS .pkg"><i class="fa fa-archive"></i> Re-pkg</button>' +
                    '</td></tr>';
            });
            html += '</tbody></table>';
        }
        // NS
        if (d.ns) {
            html += '<div style="margin-top:14px;"><strong>NS records</strong> for <code>' + esc(d.domain) + '</code>: ' +
                (d.ns.match ? '<span class="label label-success">match</span>' :
                  (d.ns.actual.length === 0 ? '<span class="label label-default">no NS resolved</span>' :
                  '<span class="label label-warning">mismatch</span>')) + '</div>';
            html += '<div class="small text-muted">Expected: <code>' + d.ns.expected.map(esc).join(', ') + '</code></div>';
            html += '<div class="small text-muted">Actual: <code>' + d.ns.actual.map(esc).join(', ') + '</code></div>';
            if (d.ns.error) html += '<div class="text-danger small">' + esc(d.ns.error) + '</div>';
        }
        // External-DNS verifier
        if (d.external_records) {
            html += '<div style="margin-top:14px;"><strong>External DNS records (client-managed)</strong></div>';
            html += '<table class="table table-condensed" style="margin-top:6px;"><thead><tr><th>Type</th><th>Name</th><th>Expected</th><th>Actual</th><th>Match</th></tr></thead><tbody>';
            d.external_records.forEach(function(r){
                html += '<tr>' +
                    '<td>' + esc(r.type) + '</td>' +
                    '<td><code>' + esc(r.fqdn) + '</code></td>' +
                    '<td><code>' + esc(r.expected) + '</code></td>' +
                    '<td>' + (r.actual && r.actual.length ? r.actual.map(function(v){ return '<code>' + esc(v) + '</code>'; }).join('<br>') : '<em class="text-muted">(empty)</em>') + '</td>' +
                    '<td>' + (r.match ? '<span class="label label-success">ok</span>' : '<span class="label label-danger">no</span>') + (r.error ? ' <small class="text-danger">' + esc(r.error) + '</small>' : '') + '</td>' +
                    '</tr>';
            });
            html += '</tbody></table>';
        }
        $('#puq-verify-result').html(html || '<em class="text-muted">No applicable checks.</em>');
    }

    $('#puq-verify-run').on('click', function(){
        var btn = this; btnSpinner(btn, 'Probing...');
        $('#puq-verify-result').html('<i class="fa fa-spinner fa-spin"></i> Querying panels and DNS resolvers (may take 10–30s)...');
        $.ajax({ url: baseUrl + 'verifyServiceComponents', type: 'POST', data: { id: puqId }, dataType: 'json',
            success: function(r){
                if (r.status !== 'success') {
                    $('#puq-verify-result').html('<span class="text-danger">' + esc(r.msg || 'Failed') + '</span>');
                    return;
                }
                $('#puq-toggle-external-dns').prop('checked', !!r.data.external_dns);
                renderVerify(r.data);
            },
            error: function(xhr){ $('#puq-verify-result').html('<span class="text-danger">HTTP ' + xhr.status + '</span>'); },
            complete: function(){ btnRestore(btn, 'search', 'Run verification'); }
        });
    });

    $('#puq-toggle-external-dns').on('change', function(){
        var enabled = $(this).is(':checked') ? 1 : 0;
        $.ajax({ url: baseUrl + 'toggleExternalDns', type: 'POST', data: { id: puqId, enabled: enabled }, dataType: 'json',
            success: function(r){
                var kind = r.status === 'success' ? 'success' : 'error';
                showNotification(r.msg || 'Toggled', kind);
                if (r.status === 'success' && enabled && r.data && r.data.zones_remain > 0) {
                    puqConfirm({
                        type: 'warning', icon: 'fa-trash',
                        title: 'Clean up our DNS zones?',
                        text: 'Service still has <strong>' + r.data.zones_remain + '</strong> active DNS zone(s) on our nameservers. Delete them now?',
                        ok: 'Delete zones', cancel: 'Keep',
                        onConfirm: function(){
                            return new Promise(function(resolve, reject){
                                $.ajax({ url: baseUrl + 'cleanupDnsZones', type: 'POST', data: { id: puqId }, dataType: 'json',
                                    success: function(rr){
                                        if (rr.status === 'success') { showNotification(rr.msg || 'Cleanup queued', 'success'); resolve(); }
                                        else reject(new Error(rr.msg || 'Cleanup failed'));
                                    },
                                    error: function(){ reject(new Error('Request failed')); }
                                });
                            });
                        }
                    });
                }
            }
        });
    });

    $('#puq-set-domain-admin').on('click', function(){
        puqPrompt({
            type: 'info', icon: 'fa-globe',
            title: 'Set service domain',
            text: 'Enter the domain for this service (e.g. <code>example.com</code>):',
            placeholder: 'example.com', ok: 'Save & deploy',
            validator: function(v){
                v = String(v || '').trim().toLowerCase();
                return /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/.test(v);
            },
            validatorMsg: 'Invalid domain.',
            onSubmit: function(val){
                var d = String(val).trim().toLowerCase();
                return new Promise(function(resolve, reject){
                    $.ajax({ url: baseUrl + 'setServiceDomain', type: 'POST', data: { id: puqId, domain: d, deploy: 1 }, dataType: 'json',
                        success: function(r){
                            if (r.status === 'success') {
                                showNotification(r.msg || 'Domain set', 'success');
                                setTimeout(function(){ load(); }, 800);
                                resolve();
                            } else {
                                reject(new Error(r.msg || 'Failed'));
                            }
                        },
                        error: function(){ reject(new Error('Request failed')); }
                    });
                });
            }
        });
    });

    $('#puq-verify-panel').on('click', '.puq-recreate', function(){
        var $b = $(this), kind = $b.data('kind'), sid = $b.data('sid') || 0;
        var url, data = { id: puqId };
        if (kind === 'web-domain')  { url = 'recreateRoleDomain';   data.role = 'web'; }
        else if (kind === 'mail-domain') { url = 'recreateRoleDomain'; data.role = 'mail'; }
        else if (kind === 'web-package') { url = 'recreateRolePackage'; data.role = 'web'; }
        else if (kind === 'mail-package'){ url = 'recreateRolePackage'; data.role = 'mail'; }
        else if (kind === 'dns-zone')    { url = 'recreateDnsZone';   data.server_id = sid; }
        else if (kind === 'dns-package') { url = 'recreateRolePackage'; data.role = 'dns'; data.server_id = sid; }
        else return;

        btnSpinner($b[0], '');
        $.ajax({ url: baseUrl + url, type: 'POST', data: data, dataType: 'json',
            success: function(r){ showNotification(r.msg || (r.status === 'success' ? 'Queued' : 'Failed'), r.status === 'success' ? 'success' : 'error'); },
            complete: function(){ btnRestore($b[0], $b.find('i').attr('class').replace('fa fa-',''), $b.text().trim()); }
        });
    });
};
</script>
{/literal}
