<?php
include realpath(dirname(__DIR__) . '/include/header.php');
?>

<?php

$newCrons = [
    "*/5 * * * * cd /var/www/html/nux/system/ && /usr/bin/php cron.php",
    "0 * * * * cd /var/www/html/nux/system/ && /usr/bin/php cron.php",
    "0 7 * * * cd /var/www/html/nux/system/ && /usr/bin/php cron_reminder.php"
];

$backupFile = '/tmp/cron_backup.txt';
$removed = false;

function getCurrentCrontab(): array
{
    exec('crontab -l 2>/dev/null', $output, $exitCode);
    return $exitCode === 0 ? $output : [];
}

function saveCrontab(array $crons): bool
{
    $crontabText = implode(PHP_EOL, $crons) . PHP_EOL;
    $tempFile = tempnam(sys_get_temp_dir(), 'cron_');
    file_put_contents($tempFile, $crontabText);
    exec("crontab $tempFile", $output, $returnCode);
    unlink($tempFile);
    return $returnCode === 0;
}

function logToFile(string $message, string $type = 'info'): void
{
    $logFile = '/tmp/cron_update_log.txt';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp][$type] $message" . PHP_EOL, FILE_APPEND);
}

function parseCronToRow(string $cron): array
{
    $parts = preg_split('/\s+/', $cron, 6);
    if (count($parts) < 6) {
        return ['-', '-', '-', '-', '-', $cron];
    }
    return $parts;
}

// Handle remove cron job
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_cron'])) {
    $cronToRemove = trim($_POST['remove_cron']);
    $currentCrons = getCurrentCrontab();

    // Save backup
    file_put_contents($backupFile, implode(PHP_EOL, $currentCrons));

    // Remove the cron job
    $updatedCrons = array_filter($currentCrons, function ($cron) use ($cronToRemove) {
        return trim($cron) !== $cronToRemove;
    });

    // Check if the cron job was removed successfully
   
    if (saveCrontab($updatedCrons)) {
        $statusMsg = "🗑️ Removed cron job: <code>$cronToRemove</code>";
        logToFile("Removed cron job: $cronToRemove");
        $removed = true;
    } else {
        $statusMsg = "❌ Failed to remove cron job.";
        logToFile("Failed to remove cron job: $cronToRemove", "error");
    }
}

if (!$removed) {
    $currentCrons = getCurrentCrontab();
    $addedCrons = [];
    // Save current crontab as backup before modifying
    file_put_contents($backupFile, implode(PHP_EOL, $currentCrons));
    foreach ($newCrons as $cronJob) {
        if (!in_array($cronJob, $currentCrons)) {
            $currentCrons[] = $cronJob;
            $addedCrons[] = $cronJob;
        }
    }
    $currentCrons = getCurrentCrontab();
}

?>
<div class="col-xl-12">
    <div class="card">
        <div class="card-body">
            <h4 class="card-title">Cron Jobs</h4>
            <p class="card-title-desc">List of all cron jobs created in the system.</p>
            <div class="status">
                <?= $statusMsg ?>
            </div>
            <div class="table-container">
                <div class="table-responsive">
                    <table class="table mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Minute</th>
                                <th>Hour</th>
                                <th>Day</th>
                                <th>Month</th>
                                <th>Weekday</th>
                                <th>Command</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($currentCrons as $cron): ?>
                                <?php $row = parseCronToRow($cron); ?>
                                <tr>
                                    <td><?= htmlspecialchars($row[0]) ?></td>
                                    <td><?= htmlspecialchars($row[1]) ?></td>
                                    <td><?= htmlspecialchars($row[2]) ?></td>
                                    <td><?= htmlspecialchars($row[3]) ?></td>
                                    <td><?= htmlspecialchars($row[4]) ?></td>
                                    <td><?= htmlspecialchars($row[5]) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </div>
</div>
<?php include realpath(dirname(__DIR__) . '/include/footer.php'); ?>