<?php

class Mail extends Vn\Lib\Method {
	function run($db) {
		$db->query('START TRANSACTION');

		$mailer = new Vn\Web\Mailer($db);
		$res = $db->query(
			'SELECT * FROM vn.mail WHERE `sent` = 0
				ORDER BY creationDate
				LIMIT 50
				FOR UPDATE'
		);

		$pdfsDir = $db->getValue('SELECT pdfsDir FROM config');

		$count = 0;

		while ($row = $res->fetch_object()) {
			$sent = 1;
			$status = 'OK';

			try {
				$mail = $mailer->createObject($row->receiver, $row->body, $row->subject);

				if ($row->replyTo) {
					$mail->AddReplyTo($row->replyTo, $row->replyTo);
					//$mail->ReturnPath = $row->replyTo;
				}

				if (!empty($row->attachment)) {
					$attachment = "$pdfsDir/{$row->attachment}";

					if (file_exists($attachment))
						$mail->AddAttachment($attachment, '');
					else
						throw new Exception("Attachment file could not be found: $attachment");
				}

				if (!$mail->Send())
					throw new Exception($mail->ErrorInfo);
					
				$count++;
			} catch (Exception $e) {
				$sent = 2;
				$status = $e->getMessage();

				if ($row->replyTo) {
					Vn\Lib\Locale::set('es');
					$errorMsg = 
						 '<p>'. s('Notification from IT department about problem.') .'</p>'
						.'<p>'. s('If you have questions, resend this email to cau@verdnatura.es.') .'</p>'
						.'<p style="color: gray">'. $status .'</p>';

					$errorMail = $mailer->createObject($row->replyTo,
						$errorMsg,
						s('An automated message could not be delivered')
					);
					$errorMail->AddStringAttachment(
						$mail->getSentMIMEMessage(),
						'Undelivered Message',
						'8bit',
						'message/rfc822'
					);
					$errorMail->Send();
                }
			}

			$db->query('UPDATE vn.mail SET `sent` = #, status = # WHERE id = #',
				[$sent, $status, $row->id]);
		}

		$db->query('COMMIT');
		echo "Total $count mails sent\n";
	}
}
