<?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->getRow (
			'SELECT host, user, pass, clean_period, success_folder, error_folder
				FROM tpv_imap_config'
		);

		$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['success_folder'];
			else
				$folder = $imapConf['error_folder'];				

			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['success_folder']
				,$imapConf['error_folder']
			);

			$date = new \DateTime (NULL);
			$date->sub (new \DateInterval ($imapConf['clean_period']));
			$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";
	}
}

