<?php

namespace CleantalkSP\SpbctWP\Scanner\OSCron;

use CleantalkSP\SpbctWP\Scanner\OSCron\Storages\OsCronTasksStorage;
use CleantalkSP\SpbctWP\Scanner\OSCron\View\OSCronLocale;

class OSCronController
{
    /**
     * Updates the status of a task and rewrites the cron tab file.
     *
     * @param string $uid The unique identifier of the task.
     * @param string $status The new status of the task.
     * @return string|true True if the operation is successful, error string otherwise
     * @throws \Exception If an error occurs during the update.
     */
    private static function updateTask($uid, $status)
    {
        $task_to_change = OSCronTasksStorage::getById($uid);
        $task_to_change->setStatus($status);
        $result = OSCronModel::updateTaskOfStorageById($uid, $task_to_change);
        if (false === $result) {
            return OSCronLocale::getInstance()->error__task_not_found;
        }
        return OSCronModel::writeEnvCron();
    }

    /**
     * Enables a task by its unique identifier.
     *
     * @param string $uid The unique identifier of the task.
     * @return string|true True if the operation is successful, error string otherwise
     * @throws \Exception If an error occurs during the approval.
     */
    public static function enableTask($uid)
    {
        return static::updateTask($uid, 'enabled');
    }

    /**
     * Disables a task by its unique identifier.
     *
     * @param string $uid The unique identifier of the task.
     * @return string|true True if the operation is successful, error string otherwise
     * @throws \Exception If an error occurs during the disablement.
     */
    public static function disableTask($uid)
    {
        return static::updateTask($uid, 'disabled');
    }
}
