<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 8/18/17
 * Time: 8:49 AM
 */

namespace IMATHUZH\Qfq\External;


use IMATHUZH\Qfq\Core\Database\Database;
use IMATHUZH\Qfq\Core\Evaluate;
use IMATHUZH\Qfq\Core\Helper\DownloadPage;
use IMATHUZH\Qfq\Core\Helper\Logger;
use IMATHUZH\Qfq\Core\Helper\Path;
use IMATHUZH\Qfq\Core\Helper\Support;
use IMATHUZH\Qfq\Core\Report\SendMail;
use IMATHUZH\Qfq\Core\Store\Store;

/**
 * Class AutoCron
 * @package qfq
 */
class AutoCron {

    /**
     * @var Store
     */
    protected $store = null;

    /**
     * @var Evaluate
     */
    protected $evaluate = null;

    /**
     * @var bool
     */
    private $phpUnit = false;

    /**
     * @var Database[] - Array of Database instantiated class
     */
    private $dbArray = array();

    private $dbIndexQfq = '';

    private $verbose = '';


    /**
     * AutoCron constructor.
     *
     * @param bool $verbose
     * @param bool $phpUnit
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    public function __construct($verbose = false, $phpUnit = false) {

        #TODO: rewrite $phpUnit to: "if (!defined('PHPUNIT_QFQ')) {...}"
        $this->verbose = $verbose;
        $this->phpUnit = $phpUnit;

        mb_internal_encoding("UTF-8");

//        set_error_handler("\\IMATHUZH\\Qfq\\Core\\Exception\\ErrorHandler::exception_error_handler");

        $this->store = Store::getInstance();
        $this->store->fillStoreSystemBySql(); // Do this after the DB-update

        // Set Log Mode for AutoCron updates
        $sqlLogMode = $this->store->getVar(SYSTEM_SQL_LOG_MODE_AUTOCRON, STORE_SYSTEM);
        $this->store->setVar(SYSTEM_SQL_LOG_MODE, $sqlLogMode, STORE_SYSTEM);

        $this->dbIndexQfq = $this->store->getVar(SYSTEM_DB_INDEX_QFQ, STORE_SYSTEM);

        $this->dbArray[$this->dbIndexQfq] = new Database($this->dbIndexQfq);

        $this->evaluate = new Evaluate($this->store, $this->dbArray[$this->dbIndexQfq]);
    }

    /**
     * Check if there are started cronJobs, older than $ageMaxMinutes.
     *
     * @param int $ageMaxMinutes
     *
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     */
    private function checkForOldJobs($ageMaxMinutes) {

        $sql = "SELECT CONCAT('AutoCron: cron.id=', c.id, ' in progress since: ', c.inProgress, ' - older than 10 mins') FROM Cron AS c WHERE DATE_ADD(c.inProgress, INTERVAL $ageMaxMinutes MINUTE)<NOW() AND c.status='enable' ";

        // If there are too long running jobs: throw an exception
        $rows = $this->dbArray[$this->dbIndexQfq]->sql($sql, ROW_REGULAR);
        if (!empty($rows)) {
            echo 'Fix problem on the following AutoCron job and clear cron.inProgress of that job.';
            echo implode(PHP_EOL, $rows[0]);
        }
    }

    /**
     * Check if $job has expired. If yes, calculate next run and set $job[AUTOCRON_NEXT_RUN].
     *
     * @param array $job
     *
     * @return array
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     */
    private function calcNextRun(array $job) {

        $sql = "SELECT NOW() AS now"; // use mysql date in case php server time(zone) is different from mysql server time
        $row = $this->dbArray[$this->dbIndexQfq]->sql($sql, ROW_EXPECT_1);
        // If nextRun is already in the future, do nothing.
        if ($row["now"] < $job[AUTOCRON_NEXT_RUN]) {
            return $job;
        }

        // With no frequency: stop future repeating by setting nextRun=0
        if ($job[AUTOCRON_FREQUENCY] == '') {
            $job[AUTOCRON_NEXT_RUN] = 0;

            return $job;
        }

        // '1 DAY', '15 MINUTE', '6 MONTH', or empty
        $job[AUTOCRON_FREQUENCY] = trim($job[AUTOCRON_FREQUENCY]);

        $arr = explode(' ', $job[AUTOCRON_FREQUENCY]);
        $count = empty($arr[0]) ? '1' : $arr[0];
        $unit = empty($arr[1]) ? 'DAY' : $arr[1];

        // Regular: nextRun is in the past and +frequency is in the future
        // Late:   nextRun is so much behind that +frequency is still in the past. Calculate nextRun for the future with respect to the given shedule/frequency (skip lost past actions)
        // Do the calculation with MySQL to stay in the MySQL date/time calculation world.
        $sql = "SELECT DATE_ADD('" . $job[AUTOCRON_NEXT_RUN] . "', INTERVAL CEILING( ( 1 + TIMESTAMPDIFF($unit, '" .
            $job[AUTOCRON_NEXT_RUN] . "', NOW() ) ) / $count ) * " . $job[AUTOCRON_FREQUENCY] . ") AS " . AUTOCRON_NEXT_RUN;
        $row = $this->dbArray[$this->dbIndexQfq]->sql($sql, ROW_EXPECT_1);  // frequency, nextRun, unit, count

        $job[AUTOCRON_NEXT_RUN] = $row[AUTOCRON_NEXT_RUN];

        return $job;
    }

    /**
     * Call the web page given in $job[AUTOCRON_CONTENT].
     *
     * @param array $job
     *
     * @return array $job, updated with AUTOCRON_LAST_STATUS
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    private function doJobWebsite(array $job) {

        $job[AUTOCRON_LAST_STATUS] = 'nothing done';
        $job[AUTOCRON_CONTENT] = trim($job[AUTOCRON_CONTENT]);

        if (!empty($job[AUTOCRON_CONTENT])) {

            $baseUrl = $this->store->getVar(SYSTEM_BASE_URL, STORE_SYSTEM);

            $page = DownloadPage::getContent($job[AUTOCRON_CONTENT], $baseUrl);
            if ($page === false) {
                $job[AUTOCRON_LAST_STATUS] = htmlspecialchars(AUTOCRON_STATUS_ERROR . 'failed to fetch "' . $job[AUTOCRON_CONTENT] . '"');

                return $job;
            }

            // If configured, log the download content
            if (!empty($job[AUTOCRON_OUTPUT_FILE])) {

                $job[AUTOCRON_OUTPUT_FILE] = Support::joinPath(Path::absoluteApp(), $job[AUTOCRON_OUTPUT_FILE], FILE_PRIORITY);

                Logger::logMessage($page, $job[AUTOCRON_OUTPUT_FILE], $job[AUTOCRON_OUTPUT_MODE] == 'append' ? FILE_MODE_APPEND : FILE_MODE_WRITE);
            }

            $job[AUTOCRON_LAST_STATUS] = AUTOCRON_STATUS_OK . $page;

            // Check for pattern?
            if (!empty($job[AUTOCRON_OUTPUT_PATTERN])) {

                $rc = preg_match($job[AUTOCRON_OUTPUT_PATTERN], $page);

                if ($rc === false) {
                    $job[AUTOCRON_LAST_STATUS] = AUTOCRON_STATUS_ERROR . 'preg_match() failed - "' . $job[AUTOCRON_OUTPUT_PATTERN] . '"';
                }

                if ($rc === 0) {
                    $job[AUTOCRON_LAST_STATUS] = AUTOCRON_STATUS_ERROR . 'pattern not found - "' . $job[AUTOCRON_OUTPUT_PATTERN] . '"';
                }
            }
        }

        $job[AUTOCRON_LAST_STATUS] = htmlspecialchars($job[AUTOCRON_LAST_STATUS]);

        return $job;
    }

    /**
     * Fill all necessary elements.
     *
     * @param array $mailEntry
     *
     * @return array
     */
    private function mailEntryFill(array $mailEntry) {
        foreach ([FE_SENDMAIL_TO, FE_SENDMAIL_CC, FE_SENDMAIL_BCC, FE_SENDMAIL_FROM, FE_SENDMAIL_SUBJECT,
                     FE_SENDMAIL_REPLY_TO, FE_SENDMAIL_FLAG_AUTO_SUBMIT, FE_SENDMAIL_GR_ID, FE_SENDMAIL_X_ID,
                     FE_SENDMAIL_X_ID2, FE_SENDMAIL_X_ID3, FE_SENDMAIL_BODY_MODE,
                     FE_SENDMAIL_BODY_HTML_ENTITY, FE_SENDMAIL_SUBJECT_HTML_ENTITY] as $key) {
            if (!isset($mailEntry[$key])) {
                $mailEntry[$key] = '';
            }
        }

        return $mailEntry;
    }

    /**
     * Send as many emails as $job[AUTOCRON_SQL1] has records.
     * Do not send mails if: no record OR no receiver OR empty body
     *
     * @param array $job
     *
     * @return array $job, updated with AUTOCRON_LAST_STATUS
     * @throws \CodeException
     * @throws \DbException
     * @throws \DownloadException
     * @throws \UserFormException
     * @throws \UserReportException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    private function doJobMail(array $job) {

        $mailArr = $this->evaluate->parse($job[AUTOCRON_SQL1]);

        $sendMail = new SendMail();

        $mailCount = 0;
        foreach ($mailArr as $mailEntry) {

            $this->store->setStore($mailEntry, STORE_PARENT_RECORD, true);

            $mailEntry = $this->mailEntryFill($mailEntry);

            $content = $this->evaluate->parse($job[AUTOCRON_CONTENT]);
            if ($content == '' || ($mailEntry[FE_SENDMAIL_TO] == '' && $mailEntry[FE_SENDMAIL_CC] == '' && $mailEntry[FE_SENDMAIL_BCC] == '')) {
                continue; // no receiver: skip
            }
            $mail[SENDMAIL_TOKEN_RECEIVER] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_TO]);
            $mail[SENDMAIL_TOKEN_SENDER] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_FROM]);
            $mail[SENDMAIL_TOKEN_SUBJECT] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_SUBJECT]);
            $mail[SENDMAIL_TOKEN_BODY] = $content;
            $mail[SENDMAIL_TOKEN_REPLY_TO] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_REPLY_TO]);
            $mail[SENDMAIL_TOKEN_FLAG_AUTO_SUBMIT] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_FLAG_AUTO_SUBMIT]) === 'off' ? 'off' : 'on';
            $mail[SENDMAIL_TOKEN_GR_ID] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_GR_ID]);
            $mail[SENDMAIL_TOKEN_X_ID] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_X_ID]);
            $mail[SENDMAIL_TOKEN_RECEIVER_CC] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_CC]);
            $mail[SENDMAIL_TOKEN_RECEIVER_BCC] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_BCC]);
            $mail[SENDMAIL_TOKEN_X_ID2] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_X_ID2]);
            $mail[SENDMAIL_TOKEN_X_ID3] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_X_ID3]);
            $mail[SENDMAIL_TOKEN_BODY_MODE] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_BODY_MODE]);
            $mail[SENDMAIL_TOKEN_BODY_HTML_ENTITY] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_BODY_HTML_ENTITY]);
            $mail[SENDMAIL_TOKEN_SUBJECT_HTML_ENTITY] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_SUBJECT_HTML_ENTITY]);

            $mail[SENDMAIL_TOKEN_SRC] = "AutoCron: Cron.id=" . $job[COLUMN_ID];

            // Mail: send
            $sendMail->process($mail);
            $mailCount++;
        }

        $job[AUTOCRON_LAST_STATUS] = "OK: $mailCount mails sent";

        return $job;
    }

    /**
     * Iterates over all AutoCron jobs and fire pending.
     *
     * @throws \CodeException
     * @throws \DbException
     * @throws \DownloadException
     * @throws \ShellException
     * @throws \UserFormException
     * @throws \UserReportException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function process() {

        // Select pending jobs
        $sql = "SELECT * FROM Cron AS c WHERE c.status='enable' AND c.nextRun < NOW() AND c.nextRun!=0 AND c.inProgress=0";
        $jobs = $this->dbArray[$this->dbIndexQfq]->sql($sql);

        // Iterate over all AutoCron Jobs
        foreach ($jobs as $job) {

            $this->store->setStore($job, STORE_PARENT_RECORD, true);
            $nextRun = $job[AUTOCRON_NEXT_RUN];

            // Start progress counter
            $this->dbArray[$this->dbIndexQfq]->sql("UPDATE Cron SET inProgress=NOW() WHERE id=? LIMIT 1", ROW_REGULAR, [$job[COLUMN_ID]]);

            switch ($job[AUTOCRON_TYPE]) {
                case AUTOCRON_TYPE_WEBSITE:
                    $job = $this->doJobWebsite($job);
                    break;
                case AUTOCRON_TYPE_MAIL:
                    $job = $this->doJobMail($job);
                    break;
                default:
                    throw new \ShellException('Unknown cron.type value: ' . $job[AUTOCRON_TYPE], ERROR_UNKNOWN_MODE);
            }

            $job = $this->calcNextRun($job);

            // Check 'asynchronous' job if they have been triggered during processing: prepare to be fired during the next cron turn again.
            if ($job[AUTOCRON_FREQUENCY] == '') {
                // Get latest c.nextRun to compare and check for an update in between
                $rowCheckAsynchronous = $this->dbArray[$this->dbIndexQfq]->sql("SELECT c.nextRun FROM Cron AS c WHERE id=? LIMIT 1", ROW_EXPECT_1, [$job[COLUMN_ID]]);
                if (strcmp($nextRun, $rowCheckAsynchronous[AUTOCRON_NEXT_RUN]) < 0) {
                    // There was an update on the current job in between: preserve 'nextRun' to fire the job on the next system cron turn.
                    $job[AUTOCRON_NEXT_RUN] = $rowCheckAsynchronous[AUTOCRON_NEXT_RUN];
                }
            }

            // Finish Job
            $sql = "UPDATE Cron SET lastRun=inProgress, lastStatus=?, nextRun=?, inProgress=0 WHERE id=? LIMIT 1";
            $this->dbArray[$this->dbIndexQfq]->sql($sql, ROW_REGULAR, [$job[AUTOCRON_LAST_STATUS], $job[AUTOCRON_NEXT_RUN], $job[COLUMN_ID]]);
        }

        $this->checkForOldJobs(AUTOCRON_MAX_AGE_MINUTES);
    }
}
