{* Simplified services list. Each row links to WHMCS clientsservices.php
   (where the full service_details UI is embedded via the addon hook).
   Per-row: Redeploy + Force-delete local row (escape hatch). *}
<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title pull-left"><i class="fa fa-list"></i> Services</h3>
        <div class="pull-right">
            <input type="text" id="puq-search" class="input-sm" placeholder="Search domain…" style="width:180px;margin-right:6px;">
            <select id="puq-filter-deploy" class="input-sm" style="margin-right:6px;">
                <option value="">All deploy</option>
                <option value="queued">queued</option>
                <option value="deploying">deploying</option>
                <option value="rolling_back">rolling_back</option>
                <option value="active">active</option>
                <option value="error">error</option>
                <option value="pending_terminate">pending_terminate</option>
                <option value="terminating">terminating</option>
            </select>
            <select id="puq-filter-dns" class="input-sm" style="margin-right:6px;" title="Filter by DNS mode">
                <option value="">All DNS</option>
                <option value="0">Our DNS</option>
                <option value="1">External DNS</option>
            </select>
            <button class="btn btn-default btn-sm" id="puq-refresh"><i class="fa fa-sync"></i></button>
            <button class="btn btn-info btn-sm" id="puq-bulk-verify" title="Run verify on selected (or all visible if none selected)"><i class="fa fa-stethoscope"></i> Verify</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:24px;"><input type="checkbox" id="puq-select-all" title="Select visible"></th>
                    <th>ID</th>
                    <th>Domain</th>
                    <th>Client</th>
                    <th>WHMCS</th>
                    <th>Deploy</th>
                    <th>Mode</th>
                    <th>DNS</th>
                    <th style="width:200px;">Actions</th>
                </tr>
            </thead>
            <tbody><tr><td colspan="9" class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading…</td></tr></tbody>
        </table>
    </div>
</div>

{literal}
<script>
(function(){
    var baseUrl = '{/literal}{$meta.admin_module_url}{literal}';
    var whmcsBase = '{/literal}{$before_path}/{$admin_path}{literal}';

    var badge = window.statusBadge;
    function load() {
        var params = {
            deploy_status: $('#puq-filter-deploy').val(),
            external_dns: $('#puq-filter-dns').val(),
            search: $('#puq-search').val(),
        };
        puqAjax({
            container: '#puq-data-table',
            loadingCaption: 'Loading services…',
            url: baseUrl + '&ajax=servicesList', data: params,
            success: function(r) {
                var $tbody = $('#puq-data-table tbody').empty();
                if (r.status !== 'success' || !r.data.length) {
                    $tbody.append('<tr><td colspan="9" class="text-center text-muted">No services.</td></tr>');
                    return;
                }
                r.data.forEach(function(s) {
                    var clientHtml = s.client_name ? esc(s.client_name) + '<br><small class="text-muted">' + esc(s.email || '') + '</small>' : '—';
                    var svcUrl = whmcsBase + '/clientsservices.php?userid=' + s.client_id + '&id=' + s.whmcs_service_id;
                    var domainCell = s.domain
                        ? '<a href="' + svcUrl + '"><strong>' + esc(s.domain) + '</strong></a>'
                        : '<span class="label label-warning" title="Customer has not set a domain yet">no domain</span>';
                    var dnsCell = '';
                    if (parseInt(s.external_dns, 10) === 1) {
                        dnsCell += '<span class="label label-default" title="Customer manages DNS on their own registrar">external</span>';
                        if (s.dns_verified_at) {
                            dnsCell += '<br><small class="text-muted" title="Last successful DNS-record verification">' + esc(s.dns_verified_at.substring(0, 16)) + '</small>';
                        }
                    } else {
                        dnsCell += '<span class="label label-info">ours</span>';
                        if (s.ns_verified_at) {
                            dnsCell += '<br><small class="text-muted" title="Last successful NS-records verification">NS ' + esc(s.ns_verified_at.substring(0, 16)) + '</small>';
                        }
                    }
                    var modeCell;
                    if (s.deployment_mode === 'vanity') {
                        modeCell = '<span class="label" style="background:#8e44ad;" title="Per-service web account + one mailbox on the shared provider mail user">vanity</span>';
                    } else if (s.deployment_mode === 'unified') {
                        modeCell = '<span class="label label-info" title="One Hestia user holds web+mail (+dns when local)">unified</span>';
                    } else {
                        modeCell = '<span class="label label-default" title="One Hestia user per role">split</span>';
                    }
                    $tbody.append(
                        '<tr data-whmcs-id="' + s.whmcs_service_id + '" data-puq-id="' + s.id + '" data-domain="' + esc(s.domain || '') + '">' +
                        '<td><input type="checkbox" class="puq-row-check" value="' + s.id + '"></td>' +
                        '<td>' + s.id + '<br><small class="text-muted">whmcs #' + s.whmcs_service_id + '</small></td>' +
                        '<td>' + domainCell + '</td>' +
                        '<td>' + clientHtml + '</td>' +
                        '<td>' + badge(s.whmcs_status) + '<br>' + badge(s.status) + '</td>' +
                        '<td>' + badge(s.deploy_status) +
                            (s.deploy_error ? '<br><small class="text-danger">' + esc(s.deploy_error.substring(0, 80)) + '</small>' : '') +
                        '</td>' +
                        '<td>' + modeCell + '</td>' +
                        '<td>' + dnsCell + '</td>' +
                        '<td>' +
                          '<a class="btn btn-xs btn-primary" href="' + svcUrl + '" title="Open in WHMCS service page (full panel)"><i class="fa fa-external-link-alt"></i> Open</a> ' +
                          '<button class="btn btn-xs btn-warning puq-redeploy" title="Redeploy errored tasks"><i class="fa fa-redo"></i></button> ' +
                          '<button class="btn btn-xs btn-default puq-unlock" title="Unlock stuck tasks"><i class="fa fa-unlock"></i></button> ' +
                          '<button class="btn btn-xs btn-danger puq-force-delete" title="Force-delete local row (Hestia accounts not touched)"><i class="fa fa-trash"></i></button>' +
                        '</td></tr>'
                    );
                });
            }
        });
    }

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

        $('#puq-filter-deploy, #puq-filter-dns, #puq-search').on('change keyup', load);
        $('#puq-refresh').on('click', function() {
            var btn = this;
            btnSpinner(btn);
            setTimeout(function(){ load(); btnRestore(btn, 'sync', ''); }, 200);
        });

        $('#puq-select-all').on('change', function(){
            $('#puq-data-table .puq-row-check').prop('checked', this.checked);
        });

        $('#puq-bulk-verify').on('click', function() {
            var ids = $('#puq-data-table .puq-row-check:checked').map(function(){ return this.value; }).get();
            var bulkAll = false;
            if (ids.length === 0) {
                ids = $('#puq-data-table .puq-row-check').map(function(){ return this.value; }).get();
                if (ids.length === 0) { showNotification('Nothing to verify.', 'error'); return; }
                bulkAll = true;
            }
            var msg = bulkAll
                ? 'Verify ALL <strong>' + ids.length + '</strong> visible service(s)? One SSH + DNS round-trip per service — this may take a while.'
                : 'Verify <strong>' + ids.length + '</strong> selected service(s)?';
            puqConfirm({
                type: 'info', icon: 'fa-stethoscope',
                title: 'Verify services?', text: msg,
                ok: 'Verify', cancel: 'Cancel',
                onConfirm: function(){
                    return new Promise(function(resolve, reject){
                        $.ajax({ url: baseUrl + '&ajax=bulkVerifyServices', type: 'POST', data: { ids: ids.join(',') }, dataType: 'json',
                            success: function(r){
                                if (r.status === 'success') { showNotification(r.msg || 'Done.', 'success'); load(); resolve(); }
                                else reject(new Error(r.msg || 'Verify failed'));
                            },
                            error: function(){ reject(new Error('Request failed')); }
                        });
                    });
                }
            });
        });

        $('#puq-data-table').on('click', '.puq-redeploy', function() {
            var id = $(this).closest('tr').data('whmcs-id');
            puqConfirm({
                type: 'danger', icon: 'fa-sync',
                title: 'Hard-reset redeploy?',
                text: 'This deletes the panel user(s) for this service and re-runs the full provisioning chain from scratch. <strong>Only works when the service is in error state.</strong>',
                ok: 'Redeploy', cancel: 'Cancel',
                onConfirm: function(){
                    return new Promise(function(resolve, reject){
                        $.ajax({ url: baseUrl + '&ajax=redeployService', type: 'POST', data: { service_id: id }, dataType: 'json',
                            success: function(r){
                                if (r.status === 'success') { showNotification(r.msg || 'Queued.', 'success'); load(); resolve(); }
                                else reject(new Error(r.msg || 'Redeploy failed'));
                            },
                            error: function(){ reject(new Error('Request failed')); }
                        });
                    });
                }
            });
        });
        $('#puq-data-table').on('click', '.puq-unlock', function() {
            var id = $(this).closest('tr').data('whmcs-id');
            puqConfirm({
                type: 'warning', icon: 'fa-unlock',
                title: 'Unlock service?',
                text: 'Reclaim stuck tasks and flip any rows still in <code>deploying</code> back to <code>error</code> so a fresh attempt can run.',
                ok: 'Unlock', cancel: 'Cancel',
                onConfirm: function(){
                    return new Promise(function(resolve, reject){
                        $.ajax({ url: baseUrl + '&ajax=servicesUnlock', type: 'POST', data: { service_id: id }, dataType: 'json',
                            success: function(r){
                                if (r.status === 'success') { showNotification(r.msg || 'Done.', 'success'); load(); resolve(); }
                                else reject(new Error(r.msg || 'Unlock failed'));
                            },
                            error: function(){ reject(new Error('Request failed')); }
                        });
                    });
                }
            });
        });
        $('#puq-data-table').on('click', '.puq-force-delete', function() {
            var $row = $(this).closest('tr');
            var puqId = $row.data('puq-id');
            var domain = $row.data('domain');
            puqPrompt({
                type: 'danger', icon: 'fa-trash',
                title: 'Force-delete LOCAL rows?',
                text: 'This drops only the <strong>local</strong> database rows for <code>' + esc(domain) + '</code>. ' +
                      'Panel accounts on the server are NOT touched — clean them manually.<br><br>' +
                      'Type the domain exactly to confirm:',
                placeholder: domain, ok: 'Force delete',
                validator: function(v){ return v === domain; },
                validatorMsg: 'Domain does not match.',
                onSubmit: function(){
                    return new Promise(function(resolve, reject){
                        $.ajax({ url: baseUrl + '&ajax=forceDeleteService', type: 'POST',
                            data: { puq_id: puqId, confirm: 'yes' }, dataType: 'json',
                            success: function(r){
                                if (r.status === 'success') { showNotification(r.msg || 'Deleted.', 'success'); load(); resolve(); }
                                else reject(new Error(r.msg || 'Delete failed'));
                            },
                            error: function(){ reject(new Error('Request failed')); }
                        });
                    });
                }
            });
        });
    });
})();
</script>
{/literal}
