<?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 Payleo extends IPaymentProcessor {
	private $consumerKey = "";
	private $consumerSecret = "";
	private $customerMsisdn = "";
	private $merchantCode = "";

	private $narration;

	public $paymentUrlTest = 'https://vendors.pay-leo.com/api/v2/test/deposit/';
	public $paymentUrl = 'https://vendors.pay-leo.com/api/v2/live/deposit/';

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

	public $amount;
	public $currency;

	public $orderNumber;
	
	public $notifyUrl;
	public $returnUrl;
	public $cancelUrl;
	
	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->consumerKey = $data->test_consumer_key;
			$this->consumerSecret = $data->test_consumer_secret;
			$this->customerMsisdn = $data->test_customer_msisdn;
			$this->merchantCode = $data->test_merchant_code;
			$this->narration = "testing";
		} else {
			$this->consumerKey = $data->consumer_key;
			$this->consumerSecret = $data->consumer_secret;
			$this->customerMsisdn = $data->customer_msisdn;
			$this->merchantCode = $data->merchant_code;
			$this->narration = "live";
		}
	}

	public function getPaymentGatewayUrl() {
		if ($this->mode == "test") {
			return $this->paymentUrlTest;
		} else {
			return $this->paymentUrl;
		}
	}

	/**
	 * 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_PAYLEO_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;

		$digits = 15; // nr of digits for transaction ID
		$transactionId = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

		$sig = substr_replace($this->getPaymentGatewayUrl(), "", -1)."&".$this->customerMsisdn."&".$this->amount."&".$this->merchantCode."&".$transactionId."&".$this->narration;
		$signature = hash_hmac('sha256', $sig, $this->consumerSecret);

		$req = array();
		$req["msisdn"] = $this->customerMsisdn;
		$req["amount"] = $data->amount;
		$req["merchantCode"] = $this->merchantCode;
		$req["transactionId"] = $transactionId;
		$req["consumerKey"] = $this->consumerKey;
		$req["auth_signature"] = $signature;
		$req["narration"] = $this->narration;

		$req = json_encode($req);

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));

		curl_setopt($ch, CURLOPT_URL, $this->getPaymentGatewayUrl());
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $req);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$server_output = curl_exec($ch);
		$server_result = json_decode($server_output);

		$status = PAYMENT_WAITING;
		$paymentStatus = PAYMENT_STATUS_PENDING;
		if ($server_result->status == "FAILED" || $server_result->code == 204) {
			$status = PAYMENT_ERROR;
			$paymentStatus = PAYMENT_STATUS_FAILURE;
		}

		$result                 = new stdClass();
		$result->transaction_id = $transactionId;
		$result->amount         = $data->amount;
		$result->payment_date   = date("Y-m-d");
		$result->response_code  = $server_result->code;
		$result->response_message = $server_result->message;

		if ($status == PAYMENT_ERROR) {
			$result->error_message = $server_result->message;
		}

		$result->order_id       = $data->id;
		$result->currency       = $data->currency;
		$result->processor_type = $this->type;
		$result->status         = $status;
		$result->payment_status = $paymentStatus;

		return $result;
	}
	 
	public function processResponse($data) {
		$result = new stdClass();
		
		$result->transaction_id = $data['command_number'];
		$result->amount = $data['paid_amount'];
		$result->response_code = $data['payment_status'];
		$result->processor_type = $this->type;
		$result->transactionTime  = date("Y-m-d", strtotime($data["payment_validation_date"]));

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

		return $result;
	}

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

	/**
	 * There are no html field
	 */
	public function getHtmlFields() {
		$html = '';

		return $html;
	}
}
