<?php
namespace SabaiApps\Directories\Component\System\Helper;

use SabaiApps\Directories\Application;

class CronHelper
{
    public function help(Application $application, array &$logs = null, $force = false)
    {
        // Init progress
        if (!isset($logs)) {
            $logs = ['success' => [], 'error' => [], 'warning' => [], 'info' => []];
            $log = true;
        }
        $logs['info'][] = __('Running cron...', 'directories');
        // Get timestamp of last cron
        $last_run = $application->getPlatform()->getOption('system_cron_last');
        if (!is_array($last_run)) {
            $last_run = ['' => time()];
        } else {
            $logs['info'][] = sprintf(
                __('Cron was last run at %s', 'directories'),
                $application->System_Date_datetime($last_run[''])
            );
        }
        // Invoke cron
        $application->Action('system_cron', [&$logs, &$last_run, $force]);
        // Save timestamp
        $application->getPlatform()->setOption('system_cron_last', $last_run);
        // Log
        if (!empty($log)) {
            foreach (array_keys($logs) as $level) {
                foreach ((array)$logs[$level] as $log) {
                    switch ($level) {
                        case 'success':
                            $application->logDebug(strip_tags($log));
                            break;
                        case 'info':
                        case 'notice':
                            $application->logNotice(strip_tags($log));
                            break;
                        case 'warning':
                            $application->logWarning(strip_tags($log));
                            break;
                        case 'error':
                            $application->logError(strip_tags($log));
                            break;
                        default:
                    }
                }
            }
        }
    }
}
