<?php

namespace Extension\CbUtilityPackage;

use Application\Config;
use Database\Connectors\ConnectionFactory;
use DateTime;
use Exception;

class Crons
{
    private $currentDateTime, $config;

    public function __construct()
    {
        $this->config          = Config::extensionsConfig('CbUtilityPackage');
        $dateTime              = new DateTime();
        $this->currentDateTime = $dateTime->format('Y-m-d H:i:s');
    }

    public function clearCronLogs()
    {
        try {
            $purgeLogs = $this->config['enable_logs_purge'];
            if (empty($purgeLogs)) {
                return;
            }

            $deleteRange =  date("Y-m-d\TH:i:s.000\Z", strtotime("-3 Months"));

            $dbConnection = $this->getDatabaseConnection();
            $dbConnection->table('scheduler_log')
                ->where('event_at', '<', $deleteRange)
                ->delete();


            if (DEV_MODE) {
                echo "<pre>\nCron logs cleared successfully. Thank you.\n";
            }
        } catch (Exception $ex) {
            print_r($ex->getMessage());
        }
    }

    private function getDatabaseConnection()
    {
        $factory = new ConnectionFactory();
        return $factory->make(array(
            'driver'   => 'sqlite',
            'database' => STORAGE_DIR . DS . 'cronlogs.sqlite',
        ));
    }
}
