<?php
	namespace Main\Libs\Payment\PaymentGateways;
	
	use Exception;
	use Main\Libs\Payment\PaymentGateway;
	use Main\Libs\Payment\SuccessfulPayment;
	use Paymentwall_Config;
	use Paymentwall_Pingback;
	use Paymentwall_Product;
	use Paymentwall_Widget;
	
	class Paymentwall extends PaymentGateway
	{
		public function payment()
		{
			Paymentwall_Config::getInstance()->set(array(
				'api_type' => Paymentwall_Config::API_GOODS,
				'public_key' => $this->config["project_key"],
				'private_key' => $this->config["secret_key"]
			));
			$widget = new Paymentwall_Widget(
				$this->customer["id"], // uid
				$this->config["widget_id"], // widget
				[
					new Paymentwall_Product(
						$this->order->id, // ag_external_id
						$this->order->paymentAmount, // amount
						$this->currency, // currencyCode
						$this->order->singleProductName, // ag_name
						Paymentwall_Product::TYPE_FIXED // ag_type
					)
				],
				array(
					'email' => $this->customer->email,
					'ps' => 'all', // Replace it with specific payment system short code for single payment methods
					'success_url' => $this->getSuccessUrl(),
					'failure_url' => $this->getCancelUrl(),
					'custom' => $this->order->id
				)
			);
			redirect($widget->getUrl());
		}
		
		/**
		 * @throws Exception
		 */
		public function callback(): SuccessfulPayment
		{
			Paymentwall_Config::getInstance()->set(array(
				'api_type' => Paymentwall_Config::API_GOODS,
				'public_key' => $this->config["project_key"],
				'private_key' => $this->config["secret_key"]
			));
			$get = $_GET;
			$pingback = new Paymentwall_Pingback($get, $_SERVER['REMOTE_ADDR']);
			if ($pingback->validate()) {
				if ($pingback->isDeliverable()) {
					$orderID = $pingback->getParameter("custom");
					$paymentID = $pingback->getReferenceId();
					
					return new SuccessfulPayment($orderID, $paymentID);
				} else {
					throw new Exception("Payment is not deliverable");
				}
			} else {
				throw new Exception($pingback->getErrorSummary());
			}
		}
	}