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

/**
 * Send out first reminder for over 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_Remindoverdue1 extends Minion_Task {
	protected function remind_overdue($notice=1) {
		$action = array();

		$key = 'remind_overdue_'.$notice;

		switch ($notice) {
			case 1:
			case 2:
			case 3:
				$days = ORM::factory('Invoice')->config(strtoupper($key));
				break;

			default:
				$this->response->body(_('Unknown Remind Period: ').$notice);
				return;
		}

		foreach (ORM::factory('Invoice')->list_overdue_billing(time()-86400*$days,FALSE,FALSE) as $io) {
			// 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;

			// 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'),
				'EMAIL'=>Company::instance()->email(),
				'FIRST_NAME'=>$io->account->first_name,
				'INV_NUM'=>$io->refnum(),
				'INV_URL'=>URL::site(URL::link('user','invoice/view/'.$io->id),'http'),
				'LATE_FEE'=>'5.50',	// @todo This should come from a config file.
				'PAYMENTS_TABLE'=>$io->account->payment->list_recent_table(),
				'SITE_NAME'=>Company::instance()->name(),
			);

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

		return $action;
	}

	protected function _execute(array $params) {
		$action = $this->remind_overdue(1);

		return _('OverDue Notice #1 Reminders Sent: ').join('|',$action);
	}
}
?>