<?php
/**
 * @package    JBusinessDirectory
 *
 * @author     CMSJunkie http://www.cmsjunkie.com
 * @copyright  Copyright (C) 2007 - 2020 CMS Junkie. All rights reserved.
 * @license    https://www.gnu.org/licenses/agpl-3.0.en.html
 */

defined('_JEXEC') or die('Restricted access');

class TouchPay extends IPaymentProcessor {
	private $agencyCode = "";
	private $securityCode = "";

	public $type;
	public $name;
	public $mode;

	public $amount;
	public $currency;

	public $orderNumber;
	
	public $notifyUrl;
	public $returnUrl;
	public $cancelUrl;

	public $scriptUrl;
	
	public $noRedirectMessage = true;
	public $recurring = false;

	public $billingDetails;

	/**
	 * Initialize the payment processor
	 *
	 * @param unknown_type $data
	 *
	 * @throws Exception
	 */
	public function initialize($data) {
		$this->type = $data->type;
		$this->name = $data->name;
		$this->mode = $data->mode;

		if ($this->mode == 'test') {
			$this->agencyCode = $data->test_agency_code;
			$this->securityCode = $data->test_security_code;
			$this->scriptUrl = "https://dev-touchpay.gutouch.com/touchpay/script/dev_touchpay-0.0.1.js";
		} else {
			$this->agencyCode = $data->agency_code;
			$this->securityCode = $data->security_code;
			$this->scriptUrl = "https://touchpay.gutouch.com/touchpay/script/prod_touchpay-0.0.1.js";
		}
	}

	public function getPaymentGatewayUrl() {
		return "";
	}

	/**
	 * Generates the payment processor html
	 */
	public function getPaymentProcessorHtml($data = null) {
		$html = "";

		$this->amount   = $data->amount;
		$this->currency = $data->currency;
				
		$html .= "<ul id=\"payment_form_$this->type\" style=\"display:none\" class=\"form-list\">
		<li>
		    " . JText::_('LNG_PROCESSOR_TOUCHPAY_INFO', true) . "
		    </li>
		</ul>";

		return $html;
	}

	/**
	 * Process the transaction by calling the payment gateway
	 *
	 * @param unknown_type $data
	 * @param string       $controller
	 *
	 * @return stdClass
	 */
	public function processTransaction($data, $controller = "payment") {
		$this->amount   = $data->amount;
		$this->currency = $data->currency;
		$this->billingDetails = isset($data->billingDetails) ? $data->billingDetails : null;

		$this->returnUrl = JBusinessUtil::getWebsiteURL().JRoute::_("index.php?option=com_jbusinessdirectory&task=$controller.processResponse&processor=touchpay&orderId=$data->id", false, 0);
		$this->notifyUrl = JBusinessUtil::getWebsiteURL().JRoute::_("index.php?option=com_jbusinessdirectory&task=$controller.processAutomaticResponse&processor=touchpay&orderId=$data->id", false, 0);
		$this->cancelUrl = JBusinessUtil::getWebsiteURL().JRoute::_("index.php?option=com_jbusinessdirectory&task=$controller.processCancelResponse&processor=touchpay&orderId=$data->id", false, 0);
		
		$this->amount       = $data->amount;
		$this->orderNumber  = $data->id;

		$result                 = new stdClass();
		$result->transaction_id = 0;
		$result->amount         = $data->amount;
		$result->payment_date   = date("Y-m-d");
		$result->response_code  = 0;
		$result->order_id       = $data->id;
		$result->currency       = $data->currency;
		$result->processor_type = $this->type;
		$result->status         = PAYMENT_REDIRECT;
		$result->payment_status = PAYMENT_STATUS_PENDING;

		return $result;
	}
	 
    public function processResponse($data) {
		$result = new stdClass();
		
		if (!isset($data['payment_token'])) {
			$result->transaction_id   = $data['num_transaction_from_gu'];
			$result->amount           = $data['amount'];
			$result->response_code    = $data['errorCode'];
			$result->processor_type   = $this->type;
			$result->transactionTime  = date("Y-m-d H:i:s");
			$result->status           = PAYMENT_WAITING;
			$result->payment_status   = PAYMENT_STATUS_WAITING;

			OrderService::setOrderTransactionID($data['orderId'], $result->transaction_id);

			if ($data['errorCode'] == 202) {
				$result->status         = PAYMENT_WAITING;
				$result->payment_status = PAYMENT_STATUS_WAITING;
			} else if ($data['errorCode'] == 200) {
				$result->status         = PAYMENT_SUCCESS;
				$result->payment_status = PAYMENT_STATUS_PAID;
			} else {
				$result->status         = PAYMENT_ERROR;
				$result->payment_status = PAYMENT_STATUS_FAILURE;
			}
		} else {
			$result->transaction_id   = $data['payment_token'];
			$result->amount           = $data['paid_sum'];
			$result->response_code    = $data['errorCode'];
			$result->transactionTime  = date('Y-m-d H:i:s', $data['payment_validation_date']);
			$result->processor_type   = $this->type;

			if ($data['payment_status'] == 200) {
				$result->status         = PAYMENT_SUCCESS;
				$result->payment_status = PAYMENT_STATUS_PAID;
			} else {
				$result->status         = PAYMENT_ERROR;
				$result->payment_status = PAYMENT_STATUS_FAILURE;
			}
		}

		if (!isset($data["orderId"])) {
			$result->order_id = OrderService::getOrderByTransactionID($result->transaction_id)->id;
		} else {
			$result->order_id         = $data["orderId"];
		}

		return $result;
    }

	/**
	 * Get the payment details
	 *
	 * @param $paymentDetails
	 *
	 * @return string
	 */
	public function getPaymentDetails($paymentDetails) {
		return JText::_('LNG_PROCESSOR_TOUCHPAY', true);
	}

	/**
	 * There are no html field
	 */
	public function getHtmlFields() {
		$data = new stdClass();
		$data->order_number = $this->orderNumber;
		$data->agency_code = $this->agencyCode;
		$data->security_code = $this->securityCode;
		$data->url_notif_success = $this->notifyUrl;
		$data->url_notif_failed = $this->cancelUrl;
		$data->domain_name = JBusinessUtil::getWebsiteUrl();
		$data->amount = $this->amount;

		if (!empty($this->billingDetails)) {
			$data->city = $this->billingDetails->city;
			$data->email = $this->billingDetails->email;
			$data->clientFirstname = $this->billingDetails->first_name;
			$data->clientLastname = $this->billingDetails->last_name;
			$data->clientPhone = $this->billingDetails->phone;
		}

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

	/**
	 * Prepares the necessary script needed for opening the iframe
	 *
	 * @param data object
	 *
	 * @return string js
	 */
	private function getScript($data) {
		$params = json_encode($data);

		$script = "";
		$script .= '<script src="'.$this->scriptUrl.'"></script> ';
		$script .= "
            <script>
                function jbdCallTouchPay()
                {
                    let params = ".$params.";

                    sendPaymentInfos(
                        new Date().getTime(), 
                        params.agency_code, 
                        params.security_code, 
                        params.domain_name, 
                        params.url_notif_success, 
                        params.url_notif_failed, 
                        params.amount
                    );
                }

                window.onload = jbdCallTouchPay;
    
            </script>
        ";

		return $script;
	}
}
