<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/cron/cron_functions.php';

if (!isset($con) || !($con instanceof mysqli)) {
    echo '<div class="alert alert-danger">Database connection is not available.</div>';
    return;
}

if (!defined('TENANT_URL')) {
    echo '<div class="alert alert-danger">TENANT_URL is not defined.</div>';
    return;
}

$tableExists = cronDbTableExists($con);
$jobs = cronBuildJobList($con);
$tenantClean = ltrim((string)TENANT_URL, '/');

function cronSafeId(string $filename): string {
    return preg_replace('/[^a-zA-Z0-9_-]/', '_', $filename);
}
?>

<div class="container-fluid py-4" id="cronManager">

    <div class="row mb-4">
        <div class="col-12">
            <div class="card shadow-2">
                <div class="card-body d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3">
                    <div>
                        <h3 class="mb-1">
                            <i class="fad fa-clock me-2"></i>Cron Manager
                        </h3>
                        <p class="text-muted mb-0">
                            Manage automation jobs stored in
                            <strong><?= htmlspecialchars($tenantClean, ENT_QUOTES, 'UTF-8') ?>/automation</strong>.
                        </p>
                    </div>

                    <span class="badge <?= $tableExists ? 'badge-success' : 'badge-danger' ?>">
                        <?= $tableExists ? 'Scheduler table ready' : 'Scheduler table missing' ?>
                    </span>
                </div>
            </div>
        </div>
    </div>

    <?php if (!$tableExists): ?>
        <div class="alert alert-danger">
            <strong>Missing database table.</strong><br>
            Create <code>automation_jobs</code> manually before using the scheduler.
        </div>
    <?php endif; ?>

    <div class="row">
        <div class="col-12">
            <div class="card shadow-2">
                <div class="card-body">

                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead>
                            <tr>
                                <th>Job</th>
                                <th>Status</th>
                                <th>Send time</th>
                                <th>Last run</th>
                                <th>Recipients</th>
                                <th class="text-end">Actions</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php if (count($jobs) === 0): ?>
                                <tr>
                                    <td colspan="6" class="text-muted">No automation jobs found.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($jobs as $job): ?>
                                    <?php
                                        $safeId = cronSafeId((string)$job['filename']);
                                        $filenameEsc = htmlspecialchars((string)$job['filename'], ENT_QUOTES, 'UTF-8');
                                    ?>
                                    <tr id="cron-row-<?= $safeId ?>" data-cron-filename="<?= $filenameEsc ?>">
                                        <td>
                                            <div class="fw-bold">
                                                <?= htmlspecialchars($job['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </div>
                                            <div class="small text-muted">
                                                <?= $filenameEsc ?>
                                            </div>
                                        </td>

                                        <td id="cron-status-<?= $safeId ?>">
                                            <?php if ($job['active']): ?>
                                                <span class="badge badge-success">Active</span>
                                            <?php elseif ($job['db_exists']): ?>
                                                <span class="badge badge-secondary">Disabled</span>
                                            <?php else: ?>
                                                <span class="badge badge-warning">Not configured</span>
                                            <?php endif; ?>
                                        </td>

                                        <td id="cron-time-<?= $safeId ?>">
                                            <?= $job['time'] !== '' ? htmlspecialchars($job['time'], ENT_QUOTES, 'UTF-8') : '<span class="text-muted">Not set</span>' ?>
                                        </td>

                                        <td id="cron-last-run-<?= $safeId ?>">
                                            <?= $job['last_run'] > 0 ? date('d-m-Y H:i', $job['last_run']) : '<span class="text-muted">Never</span>' ?>
                                        </td>

                                        <td id="cron-recipients-<?= $safeId ?>">
                                            <?php if (count($job['recipients']) > 0): ?>
                                                <span class="small">
                                                    <?= htmlspecialchars(implode(', ', $job['recipients']), ENT_QUOTES, 'UTF-8') ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted small">No recipients</span>
                                            <?php endif; ?>
                                        </td>

                                        <td class="text-end" id="cron-actions-<?= $safeId ?>">
                                            <button
                                                type="button"
                                                class="btn btn-info btn-sm"
                                                onclick="openCronEdit('<?= $filenameEsc ?>')"
                                                data-mdb-tooltip-init
                                                data-mdb-placement="top"
                                                data-mdb-trigger="hover"
                                                title="Edit cron job">
                                                <i class="fad fa-edit me-1"></i>Edit
                                            </button>

                                            <?php if ($job['db_exists']): ?>
                                                <?php if ($job['active']): ?>
                                                    <button
                                                        type="button"
                                                        class="btn btn-warning btn-sm ms-1"
                                                        onclick="toggleCronJob('<?= $filenameEsc ?>', 0)"
                                                        data-mdb-tooltip-init
                                                        data-mdb-placement="top"
                                                        data-mdb-trigger="hover"
                                                        title="Disable cron job">
                                                        <i class="fad fa-pause me-1"></i>Disable
                                                    </button>
                                                <?php else: ?>
                                                    <button
                                                        type="button"
                                                        class="btn btn-success btn-sm ms-1"
                                                        onclick="toggleCronJob('<?= $filenameEsc ?>', 1)"
                                                        data-mdb-tooltip-init
                                                        data-mdb-placement="top"
                                                        data-mdb-trigger="hover"
                                                        title="Enable cron job">
                                                        <i class="fad fa-play me-1"></i>Enable
                                                    </button>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<script>
function cronTenantClean() {
    return String(TENANT_URL || '').replace(/^\/+/, '');
}

function cronProcessEndpoint() {
    return ROOT_URL + '/includes/cron/cron_process.php';
}

function cronSafeId(filename) {
    return String(filename || '').replace(/[^a-zA-Z0-9_-]/g, '_');
}

function initCronTooltips(container) {
    const scope = container || document;
    scope.querySelectorAll('[data-mdb-tooltip-init]').forEach((el) => {
        try {
            const existing = mdb.Tooltip.getInstance(el);
            if (existing) existing.dispose();
            new mdb.Tooltip(el);
        } catch (e) {}
    });
}

function openCronEdit(filename) {
    const dest = ROOT_URL
        + '/includes/cron/cron_edit.php?tenant='
        + encodeURIComponent(cronTenantClean())
        + '&filename='
        + encodeURIComponent(filename);

    loadModalContent(
        dest,
        'popupBox',
        'modal-lg',
        1060,
        'true',
        'Edit Cron Job',
        'cancelConfirm',
        () => saveCronJob()
    );
}

function saveCronJob() {
    const form = document.getElementById('cronEditForm');

    if (!form) {
        showResponse('danger', 'Cron edit form not found.');
        return;
    }

    const formData = new FormData(form);
    const filename = formData.get('filename');

    formData.append('cron_action', 'save_job');
    formData.append('tenant', cronTenantClean());

    const xhr = new XMLHttpRequest();
    xhr.open('POST', cronProcessEndpoint(), true);

    xhr.onload = function () {
        let res;

        try {
            res = JSON.parse(xhr.responseText);
        } catch (e) {
            console.error(xhr.responseText);
            showResponse('danger', 'Cron processor returned invalid JSON.');
            return;
        }

        if (!res.ok) {
            showResponse('danger', res.message || 'Cron job could not be saved.');
            return;
        }

        updateCronRowAfterSave(String(filename), formData);

        showResponse('success', res.message || 'Cron job saved.');
        killModal('popupBox');
    };

    xhr.send(formData);
}

function toggleCronJob(filename, status) {
    const formData = new FormData();
    formData.append('cron_action', 'toggle_job');
    formData.append('filename', filename);
    formData.append('status', status);
    formData.append('tenant', cronTenantClean());

    const xhr = new XMLHttpRequest();
    xhr.open('POST', cronProcessEndpoint(), true);

    xhr.onload = function () {
        let res;

        try {
            res = JSON.parse(xhr.responseText);
        } catch (e) {
            console.error(xhr.responseText);
            showResponse('danger', 'Cron processor returned invalid JSON.');
            return;
        }

        if (!res.ok) {
            showResponse('danger', res.message || 'Cron job status could not be updated.');
            return;
        }

        updateCronRowStatus(filename, status);
        showResponse('success', res.message || 'Cron job status updated.');
    };

    xhr.send(formData);
}

function updateCronRowAfterSave(filename, formData) {
    const safeId = cronSafeId(filename);
    const time = String(formData.get('time') || '');
    const recipients = String(formData.get('recipients') || '');

    const timeEl = document.getElementById('cron-time-' + safeId);
    const recipsEl = document.getElementById('cron-recipients-' + safeId);

    if (timeEl) {
        timeEl.innerHTML = escapeHtmlCron(time);
    }

    if (recipsEl) {
        const list = recipients
            .split(/[\n,;]+/)
            .map((email) => email.trim())
            .filter((email) => email !== '');

        recipsEl.innerHTML = list.length
            ? '<span class="small">' + escapeHtmlCron(list.join(', ')) + '</span>'
            : '<span class="text-muted small">No recipients</span>';
    }

    updateCronRowStatus(filename, 1);
}

function updateCronRowStatus(filename, status) {
    const safeId = cronSafeId(filename);
    const statusEl = document.getElementById('cron-status-' + safeId);
    const actionsEl = document.getElementById('cron-actions-' + safeId);

    if (!statusEl || !actionsEl) return;

    if (parseInt(status, 10) === 1) {
        statusEl.innerHTML = '<span class="badge badge-success">Active</span>';

        actionsEl.innerHTML = `
            <button
                type="button"
                class="btn btn-info btn-sm"
                onclick="openCronEdit('${escapeJsCron(filename)}')"
                data-mdb-tooltip-init
                data-mdb-placement="top"
                data-mdb-trigger="hover"
                title="Edit cron job">
                <i class="fad fa-edit me-1"></i>Edit
            </button>

            <button
                type="button"
                class="btn btn-warning btn-sm ms-1"
                onclick="toggleCronJob('${escapeJsCron(filename)}', 0)"
                data-mdb-tooltip-init
                data-mdb-placement="top"
                data-mdb-trigger="hover"
                title="Disable cron job">
                <i class="fad fa-pause me-1"></i>Disable
            </button>
        `;
    } else {
        statusEl.innerHTML = '<span class="badge badge-secondary">Disabled</span>';

        actionsEl.innerHTML = `
            <button
                type="button"
                class="btn btn-info btn-sm"
                onclick="openCronEdit('${escapeJsCron(filename)}')"
                data-mdb-tooltip-init
                data-mdb-placement="top"
                data-mdb-trigger="hover"
                title="Edit cron job">
                <i class="fad fa-edit me-1"></i>Edit
            </button>

            <button
                type="button"
                class="btn btn-success btn-sm ms-1"
                onclick="toggleCronJob('${escapeJsCron(filename)}', 1)"
                data-mdb-tooltip-init
                data-mdb-placement="top"
                data-mdb-trigger="hover"
                title="Enable cron job">
                <i class="fad fa-play me-1"></i>Enable
            </button>
        `;
    }

    initCronTooltips(actionsEl);
    flashCronRow(filename);
}

function flashCronRow(filename) {
    const row = document.getElementById('cron-row-' + cronSafeId(filename));
    if (!row) return;

    row.classList.add('table-success');

    setTimeout(() => {
        row.classList.remove('table-success');
    }, 900);
}

function escapeHtmlCron(value) {
    return String(value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

function escapeJsCron(value) {
    return String(value)
        .replace(/\\/g, '\\\\')
        .replace(/'/g, "\\'")
        .replace(/"/g, '&quot;')
        .replace(/\n/g, '\\n')
        .replace(/\r/g, '');
}

initCronTooltips(document);
</script>