<?php
namespace App\Cron\Job;

/**
 * The class will search for overdue events in the TINA Calendar that have email alerts configured, and sends the emails
 * @author Dan
 */
class SendCalendarEventsEmails extends \App\Cron\Job\Utils\GeneralAbstract
{
	/**
	 * Cronjob category: {system|operational|financial|reporting}
	 * @var string
	 */
	protected $category = 'operational';


	/**
	 * (non-PHPdoc)
	 * @see \App\Cron\Job\Utils\GeneralAbstract::executeJob()
	 */
	protected function executeJob()
	{
		// TODO just modify it to add at a certain time in the queue
		// GET LIST OF CALENDAR EVENTS TO BE SENT
		$CalendarEventList = new \App\EntityList\CalendarEvents();
		$CalendarEventList->setFilter('alertDateTime', '!=', DATETIME_LIMIT_MIN);
		$CalendarEventList->setFilter('alertDateTime', '<', DATETIME);
		$CalendarEventList->setFilter('dismissDateTime', '=', DATETIME_LIMIT_MIN);
		$CalendarEventList->setFilter('mailStatus', '=', 1);
		$CalendarEventList->setOrderBy('startDateTime', 'ASC');
		$CalendarEventList->setOrderBy('endDateTime', 'ASC');

		$remindersList = $CalendarEventList->exportRecords();

		// alerts to be e-mailed found
		if ($remindersList) {

			$sentCount = 0;
			$notSentCount = 0;

			foreach ($remindersList as $reminder) {

				\DB::startTransaction();
				try {

					// send email
					$event = \Entity\CalendarEvent::sendMail($reminder['id']);
					$event->save();

					\DB::commitTransaction();
					$sentCount++;
				}
				catch (\App\Entity\Exception $ex) {

					\DB::rollbackTransaction();
					$notSentCount++;

					$this->logger->error(sprintf("Problem sending email for event '%s': %s", $reminder['id'], $ex->getMessagesListFormattedSimple()));
				}
			}

			$this->logger->success(sprintf("Emails sent: %s", $sentCount));
			if ($notSentCount) {
				$this->logger->error(sprintf("Emails not sent: %s", $notSentCount));
			}
		}
		else {
			$this->logger->idle("No calendar events alerts found.");
		}

	}


}
