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

/**
 * This task emails 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_Email extends Minion_Task {
	protected $_options = array(
		'force'=>NULL, // Force emailing if already sent
		'id'=>NULL, // Invoice to email
	);

	protected function _execute(array $params) {
		// Used to only process X invoices in a row.
		$max = ORM::factory('Invoice')->config('EMAIL_INV_MAX');

		$iids = $params['id'] ? explode(':',$params['id']) : array();

		$max_count = 0;
		$action = array();

		// Get our list of invoices to send
		$i = $iids ? ORM::factory('Invoice')->where('id','IN',$iids) : ORM::factory('Invoice')->list_tosend();

		$key = 'send';

		foreach ($i->find_all() as $io) {
			// If we have already sent a reminder or we dont email invoices we'll skip to the next one.
			if (($io->remind($key) AND (is_null($params['force']) OR $params['force'] != 'again')) OR ($io->account->invoice_delivery != 1))
				continue;

			// If we have issued the max number of invoices this round, finish.
			if (++$max_count > $max)
				break;

			if (Invoice::instance($io)->render('email','all')) {
				// Log the emailling
				$imo = $io->invoice_memo;
				$imo->invoice_id = $io->id;
				$imo->type = 'email';
				$imo->memo = 'Invoice Emailed.';
				$imo->save();

				$io->print_status = 1;
				$io->set_remind($key,time(),($params['force']=='again' ? TRUE : FALSE));
				$io->save();

				array_push($action,(string)$io);

			} else {
				throw new Kohana_Exception('Unable to send invoice :io',array(':io'=>$io->id));
			}
		}

		return _('Invoiced emailed: ').join('|',$action);
	}
}
?>
