<?php
	namespace Main\Libs\Payment\PaymentGateways;
	
	use Curl\Curl;
	use Exception;
	use Main\Libs\Payment\PaymentGateway;
	use Main\Libs\Payment\SuccessfulPayment;
	
	class TebexCheckout extends PaymentGateway
	{
		protected bool $isContactRequired = true;
		
		/**
		 * @throws Exception
		 */
		public function payment()
		{
			$postFields = array(
				'basket' => [
					'first_name' => $this->customer->contact->name,
					'last_name' => $this->customer->contact->surname,
					'email' => $this->customer->email,
					'custom' => [
						'order_id' => $this->order->id,
					],
					'return_url' => $this->getCancelUrl(),
					'complete_url' => $this->getSuccessUrl(),
				],
				'items' => [
					[
						'package' => [
							'name' => $this->order->singleProductName,
							'price' => $this->order->paymentAmount,
						],
						'qty' => 1,
						'type' => 'single',
					]
				],
				'sale' => []
			);
			
			$curlURL = 'https://checkout.tebex.io/api/checkout';
			$curl = new Curl();
			$curl->setHeader('Content-Type', 'application/json');
			$curl->setOpt(CURLOPT_USERPWD, $this->config["username"].':'.$this->config["api_key"]);
			$curl->post($curlURL, $postFields);
			$response = $curl->response;
			
			if (isset($response->links->checkout)) {
				redirect($response->links->checkout);
			}
			else {
				throw new Exception(json_encode($response));
			}
		}
		
		/**
		 * @throws Exception
		 */
		public function callback(): SuccessfulPayment
		{
			$json = file_get_contents("php://input");
			$data = json_decode($json, true);
			$secret = $this->config["secret_key"];
			$signature = hash_hmac('sha256', hash('sha256', $json), $secret);
			
			if ($signature != $_SERVER["HTTP_X_SIGNATURE"])
				throw new Exception("Invalid signature");
			
			$dataId = $data["id"];
			if ($data["type"] == "validation.webhook")
				response()->json([
					'id' => $dataId
				]);
			
			if ($data["type"] != "payment.completed")
				exit();
			
			$data = $data["subject"];
			
			$orderID = $data["custom"]["order_id"];
			$paymentID = $data["transaction_id"];
			
			return new SuccessfulPayment($orderID, $paymentID);
		}
	}