{* Tasks tab — all puqWebHosting_tasks for this service. DataTable + retry. *}
<div style="margin-bottom:8px;">
    <button type="button" class="btn btn-default btn-xs" id="puq-svc-tasks-reload"><i class="fa fa-sync"></i> Reload</button>
    <span class="text-muted small" id="puq-svc-tasks-count" style="margin-left:8px;"></span>
</div>
<table class="table table-striped table-condensed" id="puq-svc-tasks-table" style="width:100%;">
    <thead><tr>
        <th>ID</th><th>Action</th><th>Target</th><th>Server</th><th>Status</th><th>Attempts</th>
        <th>Created</th><th>Started</th><th>Finished</th><th>Error</th><th>Actions</th>
    </tr></thead>
    <tbody></tbody>
</table>
{literal}
<script>
(window.puqSvc = window.puqSvc || {}).init_tasks = function(ctx){
    var esc = ctx.esc, baseUrl = ctx.baseUrl, puqId = ctx.puqId, fmtDate = ctx.fmtDate;
    var dt = null;

    function load() {
        puqAjax({ container: '#puq-svc-tasks-table', loadingCaption: 'Loading tasks…',
            url: baseUrl + 'listServiceTasks&id=' + puqId, dataType: 'json',
            success: function(r){
                var rows = (r.status === 'success' && r.data) ? r.data : [];
                $('#puq-svc-tasks-count').text(rows.length + ' task(s)');
                if (dt) { dt.destroy(); $('#puq-svc-tasks-table tbody').empty(); }
                rows.forEach(function(t){
                    var statusCls = ({queued:'default',running:'info',success:'success',error:'danger',cancelled:'warning'})[t.status] || 'default';
                    var retry = (t.status === 'error' || t.status === 'cancelled')
                        ? '<button class="btn btn-xs btn-warning puq-task-retry" data-id="' + esc(t.id) + '" title="Retry"><i class="fa fa-redo"></i></button> '
                        : '';
                    var cancel = (t.status === 'queued' || t.status === 'running')
                        ? '<button class="btn btn-xs btn-danger puq-task-cancel" data-id="' + esc(t.id) + '" title="Cancel"><i class="fa fa-times"></i></button> '
                        : '';
                    $('#puq-svc-tasks-table tbody').append('<tr>' +
                        '<td>#' + esc(t.id) + '</td>' +
                        '<td><code>' + esc(t.action) + '</code></td>' +
                        '<td><small>' + esc(t.target_type) + ' #' + esc(t.target_id) + '</small></td>' +
                        '<td>' + (t.server_id ? '#' + esc(t.server_id) : '—') + '</td>' +
                        '<td><span class="label label-' + statusCls + '">' + esc(t.status) + '</span></td>' +
                        '<td>' + esc(t.attempts) + '/' + esc(t.max_attempts) + '</td>' +
                        '<td>' + fmtDate(t.created_at) + '</td>' +
                        '<td>' + fmtDate(t.started_at) + '</td>' +
                        '<td>' + fmtDate(t.finished_at) + '</td>' +
                        '<td><small class="text-danger" style="display:inline-block;max-width:280px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="' + esc(t.error_message || '') + '">' + esc(t.error_message || '') + '</small></td>' +
                        '<td>' + retry + cancel +
                          '<button class="btn btn-xs btn-default puq-task-log" data-id="' + esc(t.id) + '" title="View log"><i class="fa fa-file-alt"></i></button>' +
                        '</td></tr>');
                });
                dt = $('#puq-svc-tasks-table').DataTable({
                    order: [[0, 'desc']],
                    pageLength: 25,
                    autoWidth: false
                });
            }
        });
    }

    $('#puq-svc-tasks-reload').on('click', load);
    load = ctx.armAutoRefresh('tasks', {
        selector: '#puq-svc-tasks-table',
        load: load,
        states: ['queued','running']
    });
    $('#tab-tasks').on('click', '.puq-task-retry', function(){
        var id = $(this).data('id'); var btn = this; btnSpinner(btn);
        $.ajax({ url: baseUrl + 'retryTask', type: 'POST', data: { task_id: id }, dataType: 'json',
            success: function(r){ showNotification(r.msg || 'Retry queued', r.status === 'success' ? 'success' : 'error'); load(); },
            error: function(){ showNotification('Request failed.', 'error'); }
        });
    });
    $('#tab-tasks').on('click', '.puq-task-cancel', function(){
        var id = $(this).data('id');
        puqConfirm({
            type: 'warning', icon: 'fa-ban',
            title: 'Cancel task?',
            text: 'Cancel task <code>#' + id + '</code>?',
            ok: 'Cancel task', cancel: 'Keep',
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    $.ajax({ url: baseUrl + 'cancelTask', type: 'POST', data: { task_id: id }, dataType: 'json',
                        success: function(r){
                            if (r.status === 'success') { showNotification(r.msg || 'Cancelled', 'success'); load(); resolve(); }
                            else reject(new Error(r.msg || 'Failed'));
                        },
                        error: function(){ reject(new Error('Request failed')); }
                    });
                });
            }
        });
    });
    $('#tab-tasks').on('click', '.puq-task-log', function(){
        var id = $(this).data('id'); if (typeof puqOpenTaskLog === 'function') puqOpenTaskLog(id);
    });
    load();
};
</script>
{/literal}
