<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title pull-left"><i class="fa fa-sync"></i> Cron Settings</h3>
        <button type="button" class="btn btn-primary btn-sm pull-right" id="puq-cron-save"><i class="fas fa-save"></i> Save</button>
        <div class="clearfix"></div>
    </div>
    <div class="panel-body" style="position:relative;">
        <div id="puq-cron-overlay" style="display:block;position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,0.9);z-index:9999;border-radius:4px;">
            <div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;">
                <i class="fa fa-spinner fa-spin fa-3x text-primary"></i>
                <div style="margin-top:10px;font-size:16px;">Loading...</div>
            </div>
        </div>

        <form id="puq-cron-form">
            <div class="form-group" data-field="cron_mode">
                <label>Cron Mode</label>
                <div class="radio">
                    <label>
                        <input type="radio" name="cron_mode" value="whmcs_hook" id="cron-mode-hook">
                        <strong>WHMCS Hook</strong> — Cron tasks run automatically via WHMCS AfterCronJob hook (~every 5 min)
                    </label>
                </div>
                <div class="radio">
                    <label>
                        <input type="radio" name="cron_mode" value="standalone" id="cron-mode-standalone">
                        <strong>Standalone Cron File</strong> — Add cron.php to system crontab (runs every minute, intervals managed internally)
                    </label>
                </div>
            </div>

            <div id="puq-cron-standalone-info" class="alert alert-info" style="display:none;">
                <h5><i class="fa fa-terminal"></i> Crontab Setup</h5>
                <p>Add the following line to your system crontab (<code>crontab -e</code>):</p>
                <pre id="puq-cron-command" style="background:#f5f5f5;padding:10px;border-radius:4px;"></pre>
                <p class="text-muted" style="margin-bottom:0;">
                    <small>
                        CLI usage: <code>php cron.php --help</code> for all options.
                        Show status: <code>php cron.php --list</code>.
                        Each tick the runner evaluates the interval table below
                        (auto-enqueuers) and then drains the task queue end-to-end.
                    </small>
                </p>
            </div>

            <hr>

            <h5><i class="fa fa-clock"></i> Task Intervals</h5>
            <p class="text-muted"><small>
                Auto-enqueue jobs that periodically push work into the task queue. Set the interval (minutes) for each, or <strong>0</strong> to disable.
                Independently, the queue itself is drained end-to-end on every cron tick — there is no separate setting for that.
            </small></p>
            <table class="table table-bordered table-condensed" style="margin-bottom:15px;">
                <thead>
                    <tr>
                        <th style="width:40%;">Task</th>
                        <th style="width:120px;">Interval (min)</th>
                        <th style="width:160px;">Last Run</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody id="puq-cron-tasks-tbody"></tbody>
            </table>

            <hr>

            <h5><i class="fa fa-lock"></i> Concurrency Protection</h5>
            <div class="form-group" data-field="cron_lock_timeout">
                <label>Lock Timeout (seconds)</label>
                <input type="number" name="cron_lock_timeout" id="puq-lock-timeout" class="form-control" style="width:200px;" min="60" max="3600" value="600">
                <span class="help-block">If a cron process runs longer than this, the lock is considered stale and auto-removed. Default: 600 (10 min).</span>
            </div>
        </form>
    </div>
</div>

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

    function toggleCronInfo() {
        $('#puq-cron-standalone-info').toggle($('#cron-mode-standalone').is(':checked'));
    }

    function buildTasksTable(cronTasks) {
        var $tbody = $('#puq-cron-tasks-tbody').empty();
        if (!cronTasks) return;
        Object.keys(cronTasks).forEach(function(taskName) {
            var task = cronTasks[taskName];
            var lastRun = task.last_run || 'never';
            var disabled = (task.interval === 0);
            var statusHtml = disabled
                ? '<span class="label label-default">disabled</span>'
                : '<span class="label label-success">active</span>';
            $tbody.append(
                '<tr data-task="' + taskName + '">' +
                '<td><strong>' + esc(task.label) + '</strong><br><small class="text-muted"><code>' + esc(taskName) + '</code> — default: ' + task.default_interval + 'm</small></td>' +
                '<td><input type="number" name="interval[' + taskName + ']" class="form-control input-sm" min="0" max="10080" value="' + task.interval + '"></td>' +
                '<td><small>' + esc(lastRun) + '</small></td>' +
                '<td>' + statusHtml + '</td>' +
                '</tr>'
            );
        });
    }

    $.ajax({
        url: baseUrl + 'getSettingsCron', dataType: 'json',
        success: function(r) {
            if (r.status === 'success' && r.data) {
                var d = r.data;
                $('input[name="cron_mode"][value="' + d.cron_mode + '"]').prop('checked', true);
                $('#puq-lock-timeout').val(d.cron_lock_timeout);
                $('#puq-cron-command').text('* * * * * php ' + d.cron_path + ' > /dev/null 2>&1');
                buildTasksTable(d.tasks);
                toggleCronInfo();
            } else {
                showNotification(r.msg || 'Failed to load cron settings', 'error');
            }
            $('#puq-cron-overlay').hide();
        },
        error: function() {
            showNotification('Failed to load cron settings', 'error');
            $('#puq-cron-overlay').hide();
        }
    });

    $(document).on('change', 'input[name="cron_mode"]', toggleCronInfo);

    $('#puq-cron-save').on('click', function() {
        formSubmit({
            btn: this,
            form: '#puq-cron-form',
            baseUrl: baseUrl,
            action: 'saveSettingsCron',
            onSuccess: function() {}
        });
    });
})();
</script>
{/literal}
