<?php

require_once('libphp-phpmailer/PHPMailerAutoload.php');

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

		$mailer = new Vn\Web\Mailer($db);
		$res = $db->query(
			'SELECT * FROM mail WHERE sent = 0 ORDER BY DATE_ODBC DESC
				LIMIT 20 FOR UPDATE');

		$count = 0;

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

			try {
				$mail = $mailer->createObject($row->to, $row->text, $row->subject);
				$mail->AddReplyTo($row->reply_to, $row->reply_to);

				if (!empty($row->path)) {
					$attachment = '/mnt/cluster/pdfs/'. $row->path;

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

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

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

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