<?php
// prevent direct access

use classes\backup_store;
use classes\economic;
use classes\xlvask;
use objects\bookings_o;
use objects\logs_o;
use objects\users_o;

if (!defined('WD')) {
    exit;
}

// Define the warning function
function warn($message): void
{
    echo "\n\033[33m$message\033[0m\n";
}

$response_cron = [];

// Define the cron tasks
$cron_tasks = [
//    'CheckUnfulfilledBookings' => [
//        'interval' => 86400, // 24 hours
//        'last_run' => 0,
//        'next_run' => 0,
//        'time' => '15:00',
//        'function' => 'checkUnfulfilledBookings',
//    ],
//    'SyncBookings' => [
//        'interval' => 60, // 1 minute
//        'last_run' => 0,
//        'next_run' => 0,
//        'function' => 'syncBookings',
//    ],
    'SyncLogs' => [
        'interval' => 300, // 5 minutes
        'last_run' => 0,
        'next_run' => 0,
        'function' => 'syncLogsToDatabase',
    ],
    'SyncUserEconomicCustomerDiscounts' => [
        'interval' => 180, // 3 minutes
        'last_run' => 0,
        'next_run' => 0,
        'function' => 'SyncUserEconomicCustomerDiscounts',
    ],
    'SyncUserEconomicCustomerDetails' => [
        'interval' => 43200, // 12 hours
        'last_run' => 0,
        'next_run' => 0,
        'function' => 'SyncUserEconomicCustomerDetails',
    ],
    'backup' => [
        'interval' => 43200, // 12 hours
        'last_run' => 0,
        'next_run' => 0,
        'function' => 'backup',
    ],
    'SyncEconomicInvoiceStatus' => [
        'interval' => 120, // 2 minutes
        'last_run' => 0,
        'next_run' => 0,
        'function' => 'SyncEconomicInvoiceStatus',
    ],
    'SyncXLVaskModuleCron' => [
        'interval' => 3600, // 1 hour
        'last_run' => 0,
        'next_run' => 0,
        'function' => 'SyncXLVaskModuleCron',
    ],
];

function checkUnfulfilledBookings(): void
{
    // This is deactivated for now, as it is not wanted.
    // I'm saving this for later, as it is a good idea to have this in place.
    return;
    $bookings_o = new bookings_o();
    $bookings_o->checkUnfulfilledBookings();
}

function syncBookings(): void
{
    $bookings_o = new bookings_o();
    $response_cron[] = $bookings_o->syncBookings();
}

function syncLogsToDatabase(): void
{
    $logs_o = new logs_o();
    $logs_o->syncLogsToDatabase();
}

function backup(): void
{
    try {
        $backup = new backup_store();
        $backup->createBackup();
    } catch (Exception $e) {
        warn('Backup failed: ' . $e->getMessage());
    }
}

function SyncUserEconomicCustomerDiscounts(): void
{
    $users_o = new users_o();
    $users_o->clearAllUsersEconomicCustomerDiscountsFromCache();
}

function SyncUserEconomicCustomerDetails(): void
{
    $users_o = new users_o();
    $users_o->clearAllUsersEconomicCustomerDetailsFromCache();
    //$users_o->syncAllUsersEconomicCustomerDetails();
}

/**
 * @throws Exception
 */
function SyncEconomicInvoiceStatus(): void
{
    $economic = new economic();
    try {
        $economic->getTasks()->runCheckErrors();
    } catch (Exception $e) {
        // Do nothing, this is automatically running
    }
    try {
        $economic->getTasks()->runCheckDrafts();
    } catch (Exception $e) {
        // Do nothing, this is automatically running
    }
}

function SyncXLVaskModuleCron(): void
{
    $xlvask = new xlvask();
    try {
        if ($xlvask->config->enabled->isTrue()) {
            $xlvask->getTasks()->runCronTasks();
        }
    } catch (Exception $e) {
        // Do nothing, this is automatically running
    }
}

foreach ( $cron_tasks as $task => $data ) {
    $lastRun = redis->get_last_crond_run($task) === null ? 0 : redis->get_last_crond_run($task);
    $nextRun = $lastRun + $data['interval'];
    $cron_tasks[$task]['last_run'] = $lastRun;
    $cron_tasks[$task]['next_run'] = $nextRun;
    if ($nextRun <= time()) {
        $data['function']();
        redis->set_last_crond_run($task, time());
    } else {
        $response_cron[] = $task . ' is not due to run yet, next run is at ' . date('Y-m-d H:i:s', $nextRun) . ' (' . ($nextRun - time()) . ' seconds)';
    }
}