<?php
namespace App\Model;

//nette
use Nette;
use Nette\Database\Table\ActiveRow;
use Nette\Database\Table\Selection;
use Nette\Utils\ArrayHash;
use Nette\SmartObject;
//include
use App\Model\MailManager;
use App\Model\DatabaseManager;
//phpmailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;


require_once '../PHPMailer/PHPMailer/src/Exception.php';
require_once '../PHPMailer/PHPMailer/src/PHPMailer.php';
require_once '../PHPMailer/PHPMailer/src/SMTP.php';


class Cron extends DatabaseManager{

	use SmartObject;

	public $mailManager;

	public function __construct(MailManager $mailManager) {
		//parent::__construct();
		$this->mailManager = $mailManager;

	}

	const
		# DB
		TABLE_EVENTS = 'events',
		TABLE_OTEVRENO = 'otevreno',
		TABLE_NAME = 'invitations',
		COLUMN_ID = 'invitation_id',
		COLUMN_BODY = 'body',
		COLUMN_NAME = 'name',
		COLUMN_KEY_ID = 'event_id',
		TABLE_CON = 'contacts',
		COLUMN_CON_ID = 'contact_id',
		COLUMN_CON_MAIL = 'mail',
		COLUMN_CON_NAME = 'name',
		COLUMN_CON_ADRESS = 'adress_id',
		TABLE_ADRESS = 'adress',
		COLUMN_TOKEN = 'token',
		COLUMN_ACTIVE = 'active',
		COLUMN_CON_SALT = 'salt';

	#tahání mailů podle contact_id
	public function idToMail($contact_id) {
		return $this->database->table(self::TABLE_CON)->where(self::COLUMN_CON_ID, $contact_id)->fetchField(self::COLUMN_CON_MAIL);
	}

	#tahání jmén podle contact_id
	public function idToName($contact_id) {
		return $this->database->table(self::TABLE_CON)->where(self::COLUMN_CON_ID, $contact_id)->fetchField(self::COLUMN_CON_NAME);
	}
	

	#invitation $id podle event_id
	public function idToInvitation($id) {
		return $this->database->table(self::TABLE_NAME)->where(self::COLUMN_KEY_ID, $id)->fetchField(self::COLUMN_ID);
		
	}

	#event_id podle adress_id
	public function adressToEvent($adress_id) {
		return $this->database->table(self::TABLE_ADRESS)->where(self::COLUMN_CON_ADRESS, $adress_id)->fetchField(self::COLUMN_KEY_ID);
	}	


	#invitation_id podle adress_id
	public function contactToInvitation($id) {

		$event_id = $this->adressToEvent($id);
		return $this->database->table(self::TABLE_NAME)->where(self::COLUMN_KEY_ID, $event_id)->fetchField(self::COLUMN_ID);
	}


	#všechny aktivní eventy
	public function allActiveEvents() {
		return $this->database->table(self::TABLE_EVENTS)->where(self::TABLE_OTEVRENO, 1)->fetchAll();
	}



//posílání měsíčně

	#vrací tokeny a maily v poli (mail => token)
	public function tokens($id) {
		return $this->database->fetchPairs('SELECT mail, token FROM contacts WHERE adress_id = ? AND active = 1' , $id);

	}

	#tahání pozvanky podle invitation_id
	public function idToInv($invitation_id) {
		return $this->database->table(self::TABLE_NAME)->where(self::COLUMN_ID, $invitation_id)->fetchField(self::COLUMN_BODY);
	}

	#tahání jména pozvánky podle invitation_id
	public function idToinvN($invitation_id) {
		return $this->database->table(self::TABLE_NAME)->where(self::COLUMN_ID, $invitation_id)->fetchField(self::COLUMN_NAME);
	}

	#adresáře
	public function adresses() {
		return $this->database->fetchAll('SELECT adress_id FROM adress');
	}

	#pozvánky
	public function invitations() {
		return $this->database->fetchAll('SELECT invitation_id FROM invitations');
	}


	public function cron() {

	try {

		$adresses = $this->adresses();
		foreach ($adresses as $adress) {

			$adress_id = $adress;

			$invitations = $this->invitations();
			foreach ($invitations as $invitaion) {

			$invitation_id = $invitation;

				$inv_body = $this->idToInv($invitation_id);
				$inv_name = $this->idToInvN($invitation_id);
				$tokens = $this->tokens($adress_id);
				$dir = $this->mailManager->url_dir;

				try {

					$mail = new PHPMailer();

					$mail->SMTPAutoTLS = false;
					$mail->CharSet = "utf-8";
					$mail->Encoding = "base64";
					$mail->Host = $this->mailManager->host;
					$mail->SMTPSecure = $this->mailManager->secure; 
					$mail->Port = $this->mailManager->port; 
				    $mail->isSMTP(); 
				    $mail->isHTML(true);

				    //Recipients
				  	$mail->setFrom($this->mailManager->from, $this->mailManager->fromname);
				  	$mail->addAttachment('../GDPR.pdf');         // GDPR příloha
					$mail->addAddress($this->mailManager->from, $this->mailManager->fromname);

						foreach ($tokens as $email => $token) {
							$mail->AddCC($email);
							$mail->Body = $inv_body . "<br> Pro odhlášení od odběru pozvánek klikněte zde: <a href=\"http://". $dir ."/adresar/odhlasit/". $token . "\"> Odhlášení odběru</a>.";
							$mail->Subject = $inv_name;
							$mail->AltBody = strip_tags($inv_body);
							$mail->send();
							$mail->ClearAllRecipients();
						}
				    
				} catch (Exception $e) {
				    throw new Exception("Error Processing Request", 1);
				}

			} //invitations
		} //adresses

		} catch (Exception $e) {
			throw new Exception("Cron chyba", 1);
		}//catch

	}//try

}