<?php

/**
 * Description of IndexController
 *
 * @author Arkadiusz Rychlik <a.rychlik at eppe.com.pl>
 */
class Main_P24_Controller_IndexController extends Eppe_Frontend_Controller_Action {

	private $receivedData;
	private $transactionBean;

	public function receiveAction() {
		$validators = [
			'Int' => new Zend_Validate_Int(),
			'Alnum' => new Zend_Validate_Alnum(),
			'NotEmpty' => new Zend_Validate_NotEmpty(),
			'P24CRC' => new Zend_Validate_Callback([
				'callback' => [$this,'verifyCRC']
			]),
			'Merchant' => new Zend_Validate_Callback([
				'callback' => [$this,'verifyMerchant']
			])
		];
		$this->receivedData = [
			'p24_merchant_id' => 'Merchant',
			'p24_session_id' => 'Alnum',
			'p24_order_id' => 'Int',
			'p24_amount' => 'Int',
			'p24_currency' => 'Alnum',
			'p24_sign' => 'P24CRC',
		];
		
		// Validate
		foreach($this->receivedData as $key => $validator){
			$value = $this->_getPost($key);
			if(empty($value) || !$validators[$validator]->isValid($value)){
				throw new P24_Exception(__('Validate failed on key :key',[$key]));
			}
			else{
				$this->receivedData[$key] = $value;
			}
		}

		$bean = R::findOne('p24transaction','session_id = ? AND amount = ?',[$this->receivedData['p24_session_id'], $this->receivedData['p24_amount']]);
		if(!$bean){
			throw new P24_Exception(__('Previously created local transaction was not found'));
		}
		
		$bean->orderid = $this->receivedData['p24_order_id'];
		$bean->receiveddt = R::getCell('SELECT NOW()');
		$bean->status = 'received';
		R::store($bean);
		
		$this->paymentVerification($bean);
		
	}
	
	public function cancelAction() {
	}
	
	protected function paymentVerification($bean) {
		if(P24_Transaction::getCPAssert('test_mode')){
			$url = P24_Transaction::getCPAssert('s_url_verify');
		}
		else{
			$url = P24_Transaction::getCPAssert('url_verify');
		}
		
		$c = new Zend_Http_Client($url);
		$post = [
			'p24_merchant_id' => P24_Transaction::getCPAssert('merchant_id'),
			'p24_pos_id' => P24_Transaction::getCPAssert('merchant_id'),
			'p24_session_id' => $bean->session_id,
			'p24_amount' => (int) $bean->amount,
			'p24_currency' => $bean->currency,
			'p24_order_id' => $bean->orderid,
			'p24_sign' => $bean->crc,
		];
		
		$c->setParameterPost($post);
		$r = $c->request('POST');
		$b = $r->getBody();
		if($b == "RESULT\r\nTRUE"){
			$bean->status = 'verified';
			$bean->verifieddt = R::getCell('SELECT NOW()');
			R::store($bean);
			$this->onVerifyResultCorrect($bean);
		}
		else{
			$bean->status = 'error';
			$bean->errordt = R::getCell('SELECT NOW()');
			$bean->errordetails = $b;
			R::store($bean);
			
			$this->onVerifyResultIncorrect($bean,$b);
		}
	}

	public function verifyCRC($their_md5) {
		// Przelewy24 bug workaround
		$testMode = P24_Module_Module::getInstance()->config->test_mode;
		if($testMode){ 
			return true;
		}
		
		// Normal validation
		$crc_key = P24_Module_Module::getInstance()->config->crc_key;
		$our_md5 = md5($this->receivedData['p24_session_id'] . '|' . 
				$this->receivedData['p24_order_id'] . '|' . 
				$this->receivedData['p24_amount'] . '|' . 
				$this->receivedData['p24_currency'] . '|' . 
				$crc_key);
		return ($our_md5 == $their_md5);
	}

	public function verifyMerchant($their) {
		$our = P24_Module_Module::getInstance()->config->merchant_id;
		return ($their == $our);
	}

	/* Te akcje nadpisujemy w Application */
	
	public function onVerifyResultCorrect($bean) {
	}

	public function onVerifyResultIncorrect($bean,$response) {
	}
	
}
