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

/**
 * This class is for processing Ezypay payments.
 *
 * @package    Payment/Ezypay
 * @subpackage System
 * @category   Helpers
 * @author     Deon George
 * @copyright  (c) 2010 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Payment_Bulk_Ezypay {
	public function form() {
		$return = '';

		$return .= Form::open(NULL,array('enctype'=>'multipart/form-data'));
		$return .= Form::hidden('payer',$_POST['payer']);
		$return .= View::factory('payment/admin/addbulk/ezypay');
		$return .= Form::submit('submit','submit',array('class'=>'form_button'));
		$return .= Form::close();

		return $return;
	}

	public function process() {
		$payments = array();

		// Process payment
		$file = file_get_contents($_FILES['payment']['tmp_name']);
		$file = preg_split("/[\r]?[\n]+/",$file);

		$i = 0;
		foreach ($file as $line) {
			// Line 0 is our header
			if ($i++ == 0 OR ! trim($line))
				continue;

			// Trim our whitespace on the end of the line.
			$line = preg_replace("/\s+$/",'',$line);
			$array = explode("\t",$line);

			// Field 4 has our account reference
			if (preg_match('/^'.Config::siteid(TRUE).'-/',$array[4]) AND $array[10] == 'Cleared') {
				$aid = preg_replace('/^'.Config::siteid(TRUE).'-/','',$array[4]);

				$po = ORM::factory('payment');
				$po->account_id = $aid;
				$po->total_amt = $array[7];
				$po->notes = $array[2].':'.$array[3];
				$po->date_payment = strtotime(str_replace('/','-',$array[8]));

				$payments[$array[3]] = $po;
			}
		}

		$file = file_get_contents($_FILES['transaction']['tmp_name']);
		$file = preg_split("/[\r]?[\n]+/",$file);

		$i = 0;
		foreach ($file as $line) {
			// Line 0 is our header
			if ($i++ == 0 OR ! trim($line))
				continue;

			// Trim our whitespace on the end of the line.
			$line = preg_replace("/\s+$/",'',$line);
			$array = explode("\t",$line);

			// If we dont have a payment item for this fee, we'll continue.
			if (! isset($payments[$array[3]]))
				continue;

			// Our commission fees
			// @todo This should be in a config file
			if (in_array($array[9],array(1,15)))
				$payments[$array[3]]->fees_amt = (float)$array[7];

			// @todo Hack - since the reports dont show how the payment was made.
			// @todo Put this in a config file, in the mean time.
			if ($array[7] == 1.05)
				$payments[$array[3]]->checkout_plugin_id = 2;
			else
				$payments[$array[3]]->checkout_plugin_id = 4;
		}

		$return = '';
		$return .= View::Factory('payment/admin/addbulk/ezypay/head');

		$total = $fees = 0;
		foreach ($payments as $po) {
			$po->save();

			$total += $po->total_amt;
			$fees += $po->fees_amt;

			$return .= View::Factory('payment/admin/addbulk/ezypay/body')
				->set('o',$po);
		}

		$return .= View::Factory('payment/admin/addbulk/ezypay/foot')
			->set('total',$total)
			->set('fees',$fees);;

		return $return;
	}
}
?>
