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

/**
 * Send Reseller Admins a list of overdue 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_Listoverdue extends Minion_Task {
	protected function _execute(array $params) {
		$overdue = ORM::factory('Invoice')->list_overdue(NULL,FALSE);

		$rtms = $invoices = array();
		foreach ($overdue as $io)
			$invoices[$io->account->rtm_id][] = $io;

		// Work out which suppliers should be notified.
		foreach (array_keys($invoices) as $rtm_id)
			foreach (ORM::factory('RTM')->suppliers(ORM::factory('RTM',$rtm_id)) as $rtmo)
				if (empty($rtms[$rtmo->id]))
					$rtms[$rtmo->id] = $rtmo;

		// Send an email to each supplier, with their list of overdue invoices.
		foreach ($rtms as $rtmo) {
			$output = '';

			$output .= sprintf('Hi, %s, here are the outstanding invoices of your customers.',$rtmo->name)."\n\n";

			$rtmp = array();
			foreach ($rtmo->agents($rtmo) as $artmo) {
				// If we have included this reseller ID or there are no invoices
				if (in_array($artmo->id,$rtmp) OR empty($invoices[$artmo->id]))
					continue;

				array_push($rtmp,$artmo->id);

				$rtm_invoices = array();
				$total = 0;

				foreach ($invoices[$artmo->id] as $o) {
					array_push($rtm_invoices,$o);
					$total += $o->due();
				}

				$output .= View::factory('invoice/task/listoverdue')->set('rtmo',$artmo)->set('o',$rtm_invoices);
			}

			// Send our email
			$et = Email_Template::instance('task_invoice_list_overdue');
			$et->to = array('account'=>$rtmo->peers());
			$et->variables = array(
				'TABLE'=>$output,
				'NUM_INV'=>count($rtm_invoices),
				'TOTAL'=>$total,
			);

			$et->send();
		}
	}
}
?>