<?php

require_once(__DIR__.'/tpv.php');

/**
 * Gets transaction confirmations from the IMAP mailbox.
 **/
class ConfirmMail extends Vn\Lib\Method {
	function run($db) {
		$imap = NULL;
		$imapConf = $db->getObject(
			'SELECT host, user, pass, cleanPeriod, successFolder, errorFolder
				FROM tpvImapConfig'
		);

		$mailbox = sprintf('{%s/imap/ssl/novalidate-cert}',
			$imapConf->host);

		$imap = imap_open($mailbox
			,$imapConf->user
			,base64_decode($imapConf->pass)
		);

		if (!$imap)
			throw new Exception(imap_last_error());

		// Fetchs and confirms new transaction mails

		$count = 0;
		$inbox = imap_search($imap, 'ALL');

		if ($inbox)
		foreach ($inbox as $msg) {
			// Decodes the mail body

			$params = [];
			$body = imap_fetchbody($imap, $msg, '1');
			$strings = explode(';', $body);

			foreach ($strings as $string) {
				$x = explode(':', $string);
				$params[trim($x[0])] = trim($x[1]);
			}
	
			// Confirms the transaction
			
			$success = FALSE;
			
			try {
				$success = Tpv::confirm($db, $params);
			} catch (\Exception $e) {
				trigger_error($e->getMessage(), E_USER_WARNING); 
			}
	
			// Moves the processed mail to another folder

			if ($success)
				$folder = $imapConf->successFolder;
			else
				$folder = $imapConf->errorFolder;				

			if (!imap_mail_move($imap, $msg, "$folder"))
				trigger_error(imap_last_error(), E_USER_WARNING);

			$count++;
		}

		imap_expunge($imap);

		// Cleans the old mails
		
		$deleted = 0;

		if (rand(1, 20) == 1) {
			$folders = array(
				 $imapConf->successFolder
				,$imapConf->errorFolder
			);

			$date = new \DateTime(NULL);
			$date->sub(new \DateInterval($imapConf->cleanPeriod));
			$filter = sprintf('BEFORE "%s"', $date->format('D, j M Y'));

			foreach ($folders as $folder)
			if (imap_reopen($imap, $mailbox.$folder))
			if ($messages = imap_search($imap, $filter)) {
				foreach ($messages as $message)
					imap_delete($imap, $message);

				imap_expunge($imap);
				$deleted += count($messages);
			}
		}

		echo "$count mails processed, $deleted mails deleted.\n";
	}
}