<?php
    /*
        *****************************************************************************
        * MEGA Digital Space - by MEGA Digital Studio                               *
        * ------------------------------------------------------------------------- *
        * CMS Website:  https://megadigital.space                                   *
        * License:  https://megadigital.space/license                               *
        * Owner:  Giorgi Basharuli                                                  *
        * Contact:  online@megadigital.studio                                       *
        * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
        * Website:  https://megadigital.studio                                      *
        * ------------------------------------------------------------------------- *
        * Description: This file is a part of the MEGA Digital Space CMS system.    *
        * Unauthorized distribution, modification, or commercial use is strictly -  *
        * prohibited without prior written permission.                              *
        * ------------------------------------------------------------------------- *
        * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
        * All rights reserved.                                                      *
        *****************************************************************************
    */

    require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/config.php');
    require_once($_SERVER["DOCUMENT_ROOT"] . "/engine/data/dbconfig.php");

    $editId = isset($_POST['edit_id']) ? intval($_POST['edit_id']) : null;

    $min = $_POST['min'] ?? '*';
    $hour = $_POST['hour'] ?? '*';
    $day = $_POST['day'] ?? '*';
    $month = $_POST['month'] ?? '*';
    $weekday = $_POST['weekday'] ?? '*';
    $command = trim($_POST['command'] ?? '');

    if (!$command) {
        exit("Ошибка: команда не указана.");
    }

    $line = "$min $hour $day $month $weekday $command\n";
    $lines = file($_SERVER["DOCUMENT_ROOT"] . "/engine/data/cron-jobs.txt", FILE_IGNORE_NEW_LINES);
    $lines = array_filter($lines, fn($line) => trim($line) !== '');

    if ($editId !== null && isset($lines[$editId])) {
        $lines[$editId] = trim($line);
    } else {
        $lines[] = trim($line);
    }
    file_put_contents($_SERVER["DOCUMENT_ROOT"] . "/engine/data/cron-jobs.txt", implode("\n", $lines) . "\n");

    // Обновить системный крон
    $output = true;//shell_exec('sudo /usr/bin/crontab /var/www/megadigital.space/engine/data/cron-jobs.txt 2>&1');
    echo "Задача добавлена. Ответ crontab:\n$output";
