{include file='modules/servers/puqWebHosting/templates/header.tpl'}
{assign var='page_icon'  value='clock'}
{assign var='page_title' value=$L.mc_cron_jobs_title}
{include file='modules/servers/puqWebHosting/templates/_page_header.tpl'}

<div class="puq-card">
    <div class="puq-card-header">
        <i class="fa fa-info-circle"></i> {$L.mc_useful_paths}
        <span class="puq-header-spacer"></span>
        <small style="color:var(--puq-muted);">{$L.mc_click_to_copy_hint}</small>
    </div>
    <div class="puq-card-body" style="padding:8px 16px;">
        <table class="table" style="margin-bottom:0;font-size:12px;">
            <thead><tr><th style="width:34%;">{$L.mc_what}</th><th style="width:33%;">{$L.mc_short_cron_friendly}</th><th>{$L.mc_full_path}</th></tr></thead>
            <tbody>
                <tr>
                    <td>{$L.mc_home_directory}</td>
                    <td><code class="puq-copy" title="{$L.mc_click_to_copy}">~</code></td>
                    <td><code class="puq-copy" title="{$L.mc_click_to_copy}">/home/{$web_username|escape:'html'}</code></td>
                </tr>
                <tr>
                    <td>{$L.mc_website_docroot}</td>
                    <td><code class="puq-copy" title="{$L.mc_click_to_copy}">~/web/{$domain|escape:'html'}/public_html</code></td>
                    <td><code class="puq-copy" title="{$L.mc_click_to_copy}">/home/{$web_username|escape:'html'}/web/{$domain|escape:'html'}/public_html</code></td>
                </tr>
                <tr>
                    <td>{$L.mc_logs_directory}</td>
                    <td><code class="puq-copy" title="{$L.mc_click_to_copy}">~/web/{$domain|escape:'html'}/logs</code></td>
                    <td><code class="puq-copy" title="{$L.mc_click_to_copy}">/home/{$web_username|escape:'html'}/web/{$domain|escape:'html'}/logs</code></td>
                </tr>
                <tr>
                    <td>{$L.mc_php_cli_binary}</td>
                    <td colspan="2"><code class="puq-copy" title="{$L.mc_click_to_copy}">/usr/bin/php</code> &nbsp;<small style="color:var(--puq-muted);">— {$L.mc_php_cli_hint_before}<code>/usr/bin/php8.2</code>{$L.mc_php_cli_hint_after}</small></td>
                </tr>
            </tbody>
        </table>
        <div class="puq-msg puq-msg-info" style="margin:10px 0 0;font-size:12px;">
            <i class="fa fa-lightbulb"></i> {$L.mc_cron_runs_as}<code>{$web_username|escape:'html'}</code>{$L.mc_cron_with}<code>$HOME=/home/{$web_username|escape:'html'}</code>.
            {$L.mc_cron_abs_paths}(<code>/usr/bin/php</code>, <code>/usr/bin/curl</code>){$L.mc_cron_abs_paths_2}<code>~</code>{$L.mc_cron_abs_paths_3}
            {$L.mc_cron_redirect}(<code>&gt;&gt; ~/web/{$domain|escape:'html'}/logs/cron.log 2&gt;&amp;1</code>){$L.mc_cron_redirect_2}
        </div>
    </div>
</div>

<div class="puq-card" data-puq-lock-zone="web">
    <div class="puq-card-header">
        <i class="fa fa-list"></i> {$L.mc_scheduled_jobs}
        <i class="fas fa-circle-notch fa-spin" id="puq-cron-spinner" style="display:none;color:var(--puq-muted);margin-left:6px;font-size:12px;" title="{$L.mc_refreshing}"></i>
        <span class="puq-header-spacer"></span>
        <span class="puq-sync-toolbar" data-role="web" style="margin-right:8px;"></span>
        <span id="puq-cron-usage" class="puq-badge puq-badge-muted" title="{$L.mc_used_limit}">…</span>
        <button type="button" class="puq-btn puq-btn-primary puq-btn-sm" id="puq-cron-add"><i class="fa fa-plus"></i> {$L.mc_add_cron_job}</button>
    </div>
    <div class="puq-card-body">
        <div id="puq-cron-create" class="puq-msg puq-msg-info" style="display:none;">
            <form id="puq-cron-form" autocomplete="off">
                <div class="puq-row" style="gap:8px;">
                    <div class="puq-col" style="min-width:180px;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.mc_preset_optional}</label>
                        <select id="puq-cron-preset" class="form-control">
                            <option value="">{$L.mc_preset_custom}</option>
                            <option value="* * * * *">{$L.mc_every_minute}</option>
                            <option value="*/5 * * * *">{$L.mc_every_5_minutes}</option>
                            <option value="*/15 * * * *">{$L.mc_every_15_minutes}</option>
                            <option value="0 * * * *">{$L.mc_hourly}</option>
                            <option value="0 */6 * * *">{$L.mc_every_6_hours}</option>
                            <option value="0 2 * * *">{$L.mc_daily_at}</option>
                            <option value="0 2 * * 0">{$L.mc_weekly}</option>
                            <option value="0 2 1 * *">{$L.mc_monthly}</option>
                        </select>
                    </div>
                    <div class="puq-col" style="min-width:200px;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.mc_schedule} <small>({$L.mc_schedule_fields})</small></label>
                        <input type="text" name="schedule" class="form-control" required placeholder="0 * * * *" style="font-family:monospace;">
                    </div>
                </div>
                <div style="margin-top:8px;">
                    <label style="font-size:11px;color:var(--puq-muted);">{$L.mc_command}</label>
                    <textarea name="command" class="form-control" rows="2" required placeholder="/usr/bin/php ~/web/{$domain|escape:'html'}/public_html/cron.php >> ~/web/{$domain|escape:'html'}/logs/cron.log 2>&1" style="font-family:monospace;font-size:12px;"></textarea>
                </div>
                <div style="margin-top:10px;display:flex;gap:6px;">
                    <button type="submit" class="puq-btn puq-btn-success puq-btn-sm"><i class="fa fa-check"></i> {$L.mc_create}</button>
                    <button type="button" class="puq-btn puq-btn-outline puq-btn-sm" id="puq-cron-cancel">{$L.mc_cancel}</button>
                </div>
            </form>
        </div>

        <table class="table table-striped table-hover" id="puq-cron-table" style="width:100%;">
            <thead><tr><th style="width:160px;white-space:nowrap;">{$L.mc_schedule}</th><th>{$L.mc_command}</th><th style="width:160px;">{$L.mc_status}</th><th style="width:120px;">{$L.mc_actions}</th></tr></thead>
            <tbody><tr><td colspan="4" class="puq-loader"><i class="fas fa-circle-notch fa-spin"></i><span class="puq-loader-caption">{$L.mc_loading_cron_jobs}</span></td></tr></tbody>
        </table>
    </div>
</div>

<script>
window.puqServiceId = {$service_id};
window.puqPageRoles = ['web'];
window.puqCronLimit = {if isset($limits.web_cron_jobs)}{$limits.web_cron_jobs|intval}{else}0{/if};
</script>
{literal}
<script>
(function(){
    var $form = $('#puq-cron-form');
    var $createBox = $('#puq-cron-create');
    var TRANSIENT = ['queued','deploying','pending_delete','deleting'];
    var auto = puqAutoRefresh(load);

    function load(){
        puqInitialTableLoader('#puq-cron-table tbody', 'data-remote-id', 4, puqT('mc_loading_cron_jobs'));
        puqSetSpinner('#puq-cron-spinner', true);
        puqClientAjax('cronList', {}, function(r){
            puqSetSpinner('#puq-cron-spinner', false);
            var $t = $('#puq-cron-table tbody');
            if (r.status !== 'success') {
                if (!$t.children('tr[data-remote-id]').length) {
                    $t.html('<tr><td colspan="4" class="text-danger text-center" style="padding:18px;">' + puqEsc(r.msg||puqT('mc_error')) + '</td></tr>');
                } else if (window.puqToast) puqToast('error', r.msg || puqT('mc_refresh_failed'));
                auto.schedule(false);
                return;
            }
            var rows = r.data || [];
            var aliveCount = rows.filter(function(d){ return d.deploy_status !== 'pending_delete' && d.deploy_status !== 'deleting'; }).length;
            puqUpdateQuotaBadge('#puq-cron-usage', '#puq-cron-add', aliveCount, window.puqCronLimit || 0, puqT('mc_add_cron_job'));

            var html = '';
            if (!rows.length) {
                html = '<tr><td colspan="4" class="text-muted text-center" style="padding:24px;">' + puqEsc(puqT('mc_no_cron_jobs')) + '</td></tr>';
            } else {
                rows.forEach(function(d){
                    var ed = puqIsEditable(d.deploy_status);
                    var op = d.remote_id ? 'update' : 'create';
                    html += '<tr data-remote-id="' + puqEscAttr(d.remote_id || '') + '"'
                          + ' data-schedule="' + puqEscAttr(d.schedule) + '"'
                          + ' data-command="' + puqEscAttr(d.command) + '">' +
                        '<td style="white-space:nowrap;"><code>' + puqEsc(d.schedule) + '</code></td>' +
                        '<td style="word-break:break-all;font-family:monospace;font-size:11px;">' + puqEsc(d.command) + '</td>' +
                        '<td>' + puqDeployBadge(d.deploy_status, d.deploy_error, op) + '</td>' +
                        '<td>' +
                            (ed ? '<button type="button" class="puq-btn puq-btn-danger puq-btn-sm puq-del" title="' + puqEscAttr(puqT('mc_delete')) + '"><i class="fa fa-trash"></i></button>' : '') +
                        '</td></tr>';
                });
            }
            $t.html(html);
            var anyPending = rows.some(function(d){ return TRANSIENT.indexOf(d.deploy_status) >= 0; });
            if (window.puqClientNotifyTransitions) puqClientNotifyTransitions('cron', rows, 'remote_id', 'deploy_status', 'cron job', 'schedule');
            auto.schedule(anyPending);
        });
    }

    function atLimit(){
        var lim = window.puqCronLimit || 0;
        if (lim <= 0) return false;
        return $('#puq-cron-table tbody tr[data-remote-id]').length >= lim;
    }

    $('#puq-cron-preset').on('change', function(){
        var v = $(this).val();
        if (v) $form.find('[name=schedule]').val(v);
    });
    $('#puq-cron-add').on('click', function(e){
        e.preventDefault();
        if (atLimit()) {
            puqConfirm({
                type:'warning', icon:'fa-ban', title:puqT('mc_cron_limit_reached'),
                text:puqT('mc_limit_text_before')+'<strong>'+(window.puqCronLimit||0)+'</strong>'+puqT('mc_cron_limit_text_after'),
                ok:puqT('mc_got_it'), cancel:puqT('mc_close')
            });
            return;
        }
        $form[0].reset(); puqClearInputErrors($form); $createBox.show();
        $form.find('[name=schedule]').focus();
    });
    $('#puq-cron-cancel').on('click', function(e){ e.preventDefault(); $createBox.hide(); });

    $(document).on('click', '#puq-cron-table .puq-del', function(e){
        e.preventDefault();
        var $tr = $(this).closest('tr');
        var rid = String($tr.data('remote-id') || '');
        var schedule = String($tr.data('schedule') || '');
        var cmd = String($tr.data('command') || '');
        puqConfirm({
            type:'danger', icon:'fa-trash-alt', title:puqT('mc_delete_cron_q'),
            text:'<code>' + puqEsc(schedule) + '</code><br><small style="color:var(--puq-muted);">' + puqEsc(cmd.length > 80 ? cmd.substring(0,80)+'…' : cmd) + '</small>',
            ok:puqT('mc_delete'), cancel:puqT('mc_keep'),
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    puqClientAjax('cronDelete', { remote_id: rid, schedule: schedule, command: cmd }, function(r){
                        if (r.status === 'success') { puqToast('success', puqT('mc_cron_queued_delete')); load(); resolve(); }
                        else reject(new Error(r.msg || puqT('mc_delete_failed')));
                    }, 'POST');
                });
            }
        });
    });

    $form.on('submit', function(e){
        e.preventDefault();
        puqClearInputErrors($form);
        var sched = ($form.find('[name=schedule]').val() || '').trim();
        var cmd   = ($form.find('[name=command]').val() || '').trim();
        var ok = true;
        if (!puqValidate.cronSchedule(sched)) { puqShowInputError($form.find('[name=schedule]'), puqT('mc_schedule_error')); ok = false; }
        if (!cmd) { puqShowInputError($form.find('[name=command]'), puqT('mc_command_required')); ok = false; }
        if (!ok) return;
        var $btn = $form.find('button[type=submit]'); puqBtnSpin($btn, puqT('mc_creating'));
        puqClientAjax('cronCreate', $form.serialize(), function(r){
            puqBtnRestore($btn);
            if (r.status === 'success') {
                puqToast('success', puqT('mc_cron_creation_queued'));
                $createBox.hide(); load();
            } else {
                puqToast('error', r.msg || puqT('mc_create_failed'));
            }
        }, 'POST');
    });

    load();
})();
</script>
{/literal}
