<?php defined('BASEPATH') OR exit('No direct script access allowed');

require_once APPPATH . 'processors/Transaction_processor.php';

class Payment_processor extends Transaction_processor
{
	public function init_save(&$data)
	{
		$cur_date = gmdate('Y-m-d');
		$data['tDate'] = !empty($data['tDate'])?$data['tDate']:$cur_date;
		
		parent::init_save($data);
		// throw new Exception();

		if (!empty($data['chequeDetail']))
		{
			// post dated cheque validation before trans save
			if (count($data['payModes']) <> 1)
			{
				throw new Exception(lang('CHEQUE_PAYMENT_REQUIRED'));
				return false;
			}

			$payModes = $data['payModes'][0];

			$cqdl = $data['chequeDetail'];

			TransFlag::$cqdl =& $cqdl;

			if (empty($payModes['pRef']))
			{
				throw new Exception(lang('CHEQUE_REF_REQUIRED'));
				return false;
			}

			//Cheque Number & Date not exists in other receipts				
			$data['ref'] =  $cqdl['cqDate'];

			$this->db->select('t.id')->from('trans_pay as tp')->join('trans as t','t.id=tp.transId');
			$this->db->where (array('tp.cId' => $this->params->cId, 't.conId' => $data['conId'], 'tp.pRef' => $payModes['pRef'], 't.ref' => $cqdl['cqDate']));

			if (!empty($data['id']))
			{
				// check cheque Number exists
				$this->db->where('t.id !=',$data['id']);
			}

			$tmp = $this->db->get()->row_array();

			if ($tmp)
			{
				throw new Exception(lang('CHEQUE_ALREADY_APPLIED'));
				return false;
			}

			$tmp_trans = $this->params->tmp_trans;

			if (!empty($cqdl['isCollected'])) 
			{			
				if (strtotime($cqdl['ctDate']) > strtotime($cur_date)) 
				{
					throw new Exception(lang('CHEQUE_COLL_DATE_ERROR'));
					return false;
				}

				if (strtotime($cqdl['cqDate']) > strtotime($cqdl['ctDate']))
				{
					throw new Exception(lang('CHEQUE_DATE_COLL_ERROR'));
					return false;
				}

				$data['dueDate'] 	= empty($tmp_trans) ? $data['tDate']:($tmp_trans['dueDate'] == '0000-00-00' || strtotime($tmp_trans['dueDate']) > strtotime($data['tDate']) ? $data['tDate'] : $tmp_trans['dueDate']);
				$data['tDate'] 	= $data['tDate'] = $cqdl['ctDate']; // tdate= Amount Collected Dat
				$data['status'] 	= 'S';
			}
			else
			{
				$data['status'] = empty($cqdl['isCancelled']) ? 'D' : 'X';
				if ($data['status'] == 'X')
				{
					$data['payments'] = array();// unset payments if it cancel status
				}
				else
				{
					$data['dueDate'] = $data['ref'];
				}

				if (!empty($tmp_trans) && !empty($tmp_trans['dueDate']) && $tmp_trans['dueDate'] != '0000-00-00' && strtotime($data['tDate']) > strtotime($tmp_trans['dueDate']))
				{
					$data['tDate'] = $tmp_trans['dueDate'];
				}
			}
		}
		else
		{
			//Save as normal
			$data['status'] = 'S';
		}
	}

	public function pre_save(&$data)
	{
		parent::pre_save($data);

		if (empty(TransFlag::$cqdl['ctDate']) && !empty($data['dueDate']) && $data['dueDate'] != '0000-00-00')
		{
			$data['dueDate'] = strtotime($data['dueDate']) >= strtotime($data['tDate']) ? $data['dueDate'] : $data['tDate'];
		}

	}
}
