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

/**
 * Generate customer invoices for services
 *
 * @package    Invoice
 * @category   Tasks
 * @author     Deon George
 * @copyright  (c) 2009-2013 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Task_Invoice_Service extends Minion_Task {
	protected $_options = array(
		'days'=>0, // Days in advance to generate for
		'id'=>NULL, // Service invoice to generate for
	);

	protected function _execute(array $params) {
		// Used to only process X invoices in a row.
		$max = ($x=Kohana::$config->load('debug')->invoice) ? $x : ORM::factory('Invoice')->config('GEN_INV_MAX');
		// Sort our service by account_id, then we can generate 1 invoice.
		$svs = ORM::factory('Service')->list_invoicesoon($params['days'])->as_array();
		Sort::MAsort($svs,array('account_id'));

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

		$aid = $io = NULL;
		$max_count = 0;
		$action = array();

		foreach ($svs as $so) {
			// If we are generating an invoice for a service, skip to that service.
			if ($sids AND ! in_array($so->id,$sids))
				continue;

			// Close off invoice, and start a new one, if this is for a different account.
			if (is_null($io) OR (! is_null($aid) AND $aid != $so->account_id)) {
				// Close and save this invoice.
				if (is_object($io) AND ! $io->save())
					throw new Kohana_Exception('Failed to save invoice :invoice for service :service',array(':invoice'=>$io->id,':service'=>$so->id));

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

				// Start a new invoice.
				$io = Invoice::instance();
				$aid = $so->account_id;
			}

			$io->add_service($so);

			// Record what we have updated.
			array_push($action,$so->id);
		}

		// Save our invoice.
		if ($io AND ! $io->saved() AND ! $io->save())
			throw new Kohana_Exception('Failed to save invoice :invoice for service :service',array(':invoice'=>$io->id,':service'=>$so->id));

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