<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * Send out an invoice remind for upcoming due invoices.
 *
 * @package    Invoice
 * @category   Tasks
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Task_Invoice_Reminddue extends Minion_Task {
	protected function _execute(array $params) {
		$action = array();
		$key = 'remind_due';
		$days = ORM::factory('Invoice')->config(strtoupper($key));

		foreach (ORM::factory('Invoice')->list_overdue(time()+86400*$days,FALSE) as $io) {
			// @todo Use another option to supress reminders
			// If we have already sent a reminder, we'll skip to the next one.
			if ($io->remind($key) OR ($io->account->invoice_delivery != 1))
				continue;

			// Generate a token to view the invoice online
			$token = ORM::factory('Module_Method_Token')
				->method(array('invoice','user_view'))
				->account($io->account)
				->expire(time()+86400*21)
				->uses(3)
				->generate();

			// Send our email
			$et = Email_Template::instance('task_invoice_'.$key);

			$et->to = array('account'=>array($io->account_id));
			$et->variables = array(
				'DUE'=>$io->due(TRUE),
				'DUE_DATE'=>$io->display('due_date'),
				'FIRST_NAME'=>$io->account->first_name,
				'INV_NUM'=>$io->refnum(),
				'INV_URL'=>URL::site(URL::link('user',sprintf('invoice/view/%s?token=%s',$io->id,$token)),'http'),
				'SITE_NAME'=>Company::instance()->name(),
			);

			$et->module = $io->mid();
			$et->module_data = $io->id;

			// @todo Record email log id if possible.
			if ($et->send()) {
				$io->set_remind($key,time());
				array_push($action,(string)$io);
			}
		}

		return _('Due Reminders Sent: ').join('|',$action);
	}
}
?>
