<?php echo message_box('success') ?>
<?php
$finance_indexes_summary = isset($finance_indexes_summary) && is_array($finance_indexes_summary) ? $finance_indexes_summary : array();
$finance_pending_count = (int) ($finance_indexes_summary['pending_count'] ?? 0);
$finance_total_count = (int) ($finance_indexes_summary['total_count'] ?? 0);
$finance_items = !empty($finance_indexes_summary['items']) && is_array($finance_indexes_summary['items']) ? $finance_indexes_summary['items'] : array();
?>

<form role="form" id="form" action="<?php echo base_url(); ?>admin/settings/save_cronjob"
      method="post" class="space-y-6">
    <div class="rounded-2xl border border-border bg-card shadow-sm">
        <div class="flex flex-col gap-2 border-b border-border px-5 py-4 md:flex-row md:items-center md:justify-between">
            <div>
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('settings') ?></p>
                <h2 class="text-lg font-semibold text-foreground"><?= lang('cronjob') . ' ' . lang('settings') ?></h2>
            </div>
            <a href="<?= base_url() ?>cronjob/manually" class="text-xs font-semibold text-indigo-600 hover:text-indigo-500">
                <?= lang('run_cron_manually') ?>
            </a>
        </div>
        <div class="p-5 space-y-5">
            <input type="hidden" name="settings" value="<?= $load_setting ?>">

            <div class="grid gap-4 lg:grid-cols-2">
                <div class="rounded-xl border border-border bg-muted/30 p-4">
                    <p class="text-sm font-semibold text-foreground"><?= lang('active') . ' ' . lang('cronjob') ?></p>
                    <p class="text-xs text-muted-foreground mb-3"><?= lang('cronjob_help') ?></p>
                    <label class="inline-flex items-center gap-2 text-sm text-foreground">
                        <input type="checkbox" name="active_cronjob" class="h-4 w-4 rounded border-border text-indigo-600 focus:ring-indigo-500"
                            <?php if (config_item('active_cronjob') == 'on') { echo "checked=\"checked\""; } ?>>
                        <span><?= lang('active') ?></span>
                    </label>
                </div>
                <div class="rounded-xl border border-border bg-muted/30 p-4">
                    <p class="text-sm font-semibold text-foreground"><?= lang('automatic') . ' ' . lang('database_backup') ?></p>
                    <p class="text-xs text-muted-foreground mb-3"><?= lang('database_backup_help') ?></p>
                    <label class="inline-flex items-center gap-2 text-sm text-foreground">
                        <input type="checkbox" name="automatic_database_backup" class="h-4 w-4 rounded border-border text-indigo-600 focus:ring-indigo-500"
                            <?php if (config_item('automatic_database_backup') == 'on') { echo "checked=\"checked\""; } ?>>
                        <span><?= lang('active') ?></span>
                    </label>
                </div>
            </div>

            <div class="grid gap-4 lg:grid-cols-2">
                <div class="rounded-xl border border-border bg-card p-4">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('cronjob_link') ?></p>
                    <p class="mt-2 text-sm font-semibold text-foreground"><?= base_url() ?>cronjob/index</p>
                </div>
                <div class="rounded-xl border border-border bg-card p-4">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('last_cronjob_run') ?></p>
                    <p class="mt-2 text-sm font-semibold text-foreground">
                        <?php
                            $last_cronjob_run = config_item('last_cronjob_run');
                            if (!empty($last_cronjob_run)) {
                                echo date("Y-m-d H:i", config_item('last_cronjob_run'));
                            } else {
                                echo "-";
                            }
                        ?>
                    </p>
                </div>
            </div>

            <div class="rounded-2xl border border-border bg-muted/20 p-4 space-y-4">
                <div class="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
                    <div>
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Deferred Maintenance</p>
                        <h3 class="text-base font-semibold text-foreground">Finance index cleanup</h3>
                    </div>
                    <div class="flex items-center gap-2">
                        <span class="inline-flex items-center rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700 dark:bg-slate-800 dark:text-slate-200">
                            <?= $finance_pending_count ?> pending / <?= $finance_total_count ?> total
                        </span>
                        <?php if ($finance_pending_count > 0) { ?>
                            <button type="button" id="financeIndexRun" class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-xs font-semibold text-white hover:bg-indigo-500">
                                Run Maintenance
                            </button>
                        <?php } ?>
                    </div>
                </div>

                <div id="financeIndexProgressWrap" class="<?= $finance_pending_count > 0 ? 'hidden' : '' ?> space-y-3 rounded-xl border border-border bg-card p-4">
                    <div class="flex items-center justify-between text-sm font-semibold text-foreground">
                        <span id="financeIndexLabel">Ready</span>
                        <span id="financeIndexPercent">0%</span>
                    </div>
                    <div class="h-2 overflow-hidden rounded-full bg-muted">
                        <div id="financeIndexBar" class="h-full w-0 rounded-full bg-indigo-600 transition-all duration-300"></div>
                    </div>
                    <p id="financeIndexNote" class="text-sm text-muted-foreground">
                        <?= $finance_pending_count > 0 ? 'Deferred indexes are waiting to be created.' : 'No deferred finance indexes pending.' ?>
                    </p>
                </div>

                <?php if ($finance_pending_count > 0) { ?>
                    <div class="grid gap-3 md:grid-cols-2">
                        <?php foreach ($finance_items as $item) {
                            if (!empty($item['exists'])) {
                                continue;
                            } ?>
                            <div class="rounded-xl border border-border bg-card px-4 py-3">
                                <div class="text-sm font-semibold text-foreground"><?= html_escape($item['name'] ?? '') ?></div>
                                <div class="text-xs text-muted-foreground"><?= html_escape($item['table'] ?? '') ?></div>
                            </div>
                        <?php } ?>
                    </div>
                <?php } ?>
            </div>

            <div class="flex items-center justify-end gap-2">
                <button type="submit" class="btn btn-primary btn-xs"><?= lang('save_changes') ?></button>
            </div>

            <div class="rounded-lg border border-border bg-muted/30 px-4 py-3 text-xs text-muted-foreground">
                If cronjobs are not included in your hosting subscription, you can use a free cronjob service
                like <a href="http://www.easycron.com?ref=18097" target="_blank" class="text-indigo-600 hover:text-indigo-500">Free Cronjob Service</a>
            </div>
        </div>
    </div>
</form>

<script>
    $(function () {
        var running = false;

        function setFinanceProgress(percent, label, note) {
            $('#financeIndexProgressWrap').removeClass('hidden');
            $('#financeIndexBar').css('width', percent + '%');
            $('#financeIndexPercent').text(percent + '%');
            if (label) {
                $('#financeIndexLabel').text(label);
            }
            if (note) {
                $('#financeIndexNote').text(note);
            }
        }

        function showFinanceError(message) {
            $('#financeIndexNote').html('<span class="text-rose-600 font-semibold">' + message + '</span>');
        }

        function pollFinanceStatus(token) {
            $.ajax({
                url: '<?= base_url() ?>admin/settings/finance_index_maintenance_status/' + encodeURIComponent(token),
                method: 'GET',
                dataType: 'json',
                cache: false
            }).done(function (response) {
                if (!response || response.success !== true) {
                    running = false;
                    $('#financeIndexRun').removeClass('pointer-events-none opacity-60').text('Run Maintenance');
                    showFinanceError((response && response.message) ? response.message : 'Unable to read maintenance status.');
                    return;
                }

                setFinanceProgress(response.progress || 0, 'Updating finance indexes...', response.message || 'Working...');

                if (response.done || response.status === 'done') {
                    $('#financeIndexNote').text('Finance maintenance completed successfully.');
                    setTimeout(function () {
                        window.location.reload();
                    }, 1500);
                    return;
                }

                if (response.status === 'failed') {
                    running = false;
                    $('#financeIndexRun').removeClass('pointer-events-none opacity-60').text('Run Maintenance');
                    showFinanceError(response.message || 'Maintenance failed.');
                    return;
                }

                setTimeout(function () {
                    pollFinanceStatus(token);
                }, 2500);
            }).fail(function (response) {
                running = false;
                $('#financeIndexRun').removeClass('pointer-events-none opacity-60').text('Run Maintenance');
                showFinanceError(response && response.responseText ? response.responseText : 'Unable to continue maintenance.');
            });
        }

        $('#financeIndexRun').on('click', function () {
            if (running) {
                return;
            }
            running = true;
            var button = $(this);
            button.addClass('pointer-events-none opacity-60').text('Please wait...');
            setFinanceProgress(0, 'Starting maintenance...', 'Preparing deferred index build');
            $.ajax({
                url: '<?= base_url() ?>admin/settings/start_finance_index_maintenance',
                method: 'POST',
                dataType: 'json'
            }).done(function (response) {
                if (!response || response.success !== true) {
                    running = false;
                    button.removeClass('pointer-events-none opacity-60').text('Run Maintenance');
                    showFinanceError((response && response.message) ? response.message : 'Unable to start maintenance.');
                    return;
                }

                if (response.done) {
                    setFinanceProgress(100, 'Completed', response.message || 'Nothing to do.');
                    setTimeout(function () {
                        window.location.reload();
                    }, 1200);
                    return;
                }

                if (response.busy) {
                    pollFinanceStatus(response.token);
                    return;
                }

                pollFinanceStatus(response.token);
            }).fail(function (response) {
                running = false;
                button.removeClass('pointer-events-none opacity-60').text('Run Maintenance');
                showFinanceError(response && response.responseText ? response.responseText : 'Unable to start maintenance.');
            });
        });
    });
</script>
