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

require_once APPPATH . 'interfaces/Validator_interface.php';

class TransDuplicateValidator implements Validator_interface
{
	private $params;

	public function __construct(&$params=null)
	{
        $this->params =& $params;
	}

	public function is_valid(&$data)
	{
		// throw new Exception("Can't Save.");
		//  && in_array($data['tType'], array(SALPMT,PURPMT,JOURNAL_CONTRA,JOURNAL_VOUCHER))

		return $this->is_exist($data);
	}

	public function is_exist($data)
	{
		if (!empty($data['allow_duplicate']))
		{
			return true;
		}

		$ci =& get_instance();

		// check transaction with same date and amount				
		$ci->db->select('t.id')->from('trans AS t');

		if (in_array($data['tType'],array(JOURNAL_CONTRA, JOURNAL_VOUCHER)))
		{
			$ci->db->select('group_concat(ta.accId,"d",ta.debit,"c",ta.credit order by ta.accId) AS acc_details', false);
			$ci->db->join('trans_acc AS ta', 'ta.transId=t.id');
		}

		$ci->db->where(array(
			't.cId'		=> $this->params->cId,
			't.tDate'	=> $data['tDate'],
			't.tType'	=> $data['tType'],
			't.totAmount'	=> $data['totAmount'],
			't.conId'	=> !empty($data['conId']) ? $data['conId'] : 0
		));					

		if (!empty($data['isPmt']))
		{
			$ci->db->where('t.status !=','X');
		}
		$ci->db->group_by('t.id');
		$tmp = $ci->db->get()->result_array();

		if ($tmp)
		{
			if (!empty($data['acc_details']))
			{
				$acc_details = '';
				foreach ($data['acc_details'] as $acc)
				{
					$acc_ids[$acc['accId']] = $acc;
				}

				ksort($acc_ids);
				
				foreach ($acc_ids as $acc)
				{
					$acc['debit'] = number_format((float)$acc['debit'], 2, '.', '');
					$acc['credit'] = number_format((float)$acc['credit'], 2, '.', '');
					$acc_details.=$acc['accId'].'d'.$acc['debit'].'c'.$acc['credit'].',';
				}
				$acc_details = trim($acc_details,',');

				foreach ($tmp as $row)
				{
					if ($row['acc_details'] == $acc_details)
					{
						throw new Exception("Similar transaction already exist.");
						// $this->error = 409;
						return false;
					}
				}
			}
			else
			{
				throw new Exception("Similar transaction already exist.");
				// $this->error = 409;
				return false;
			}
		}

		return true;
	}
}
