<?php
	namespace Main\Libs\Payment\PaymentGateways;
	
	use Exception;
	use Main\Libs\Payment\PaymentGateway;
	use Main\Libs\Payment\SuccessfulPayment;
	use Square\Models\CheckoutOptions;
	use Square\Models\CreatePaymentLinkRequest;
	use Square\Models\Money;
	use Square\Models\Order;
	use Square\Models\OrderLineItem;
	use Square\SquareClient;
	
	class Square extends PaymentGateway
	{
		/**
		 * @throws Exception
		 */
		public function payment()
		{
			$access_token = $this->config["access_token"];
			$location_id = $this->config["location_id"];
			
			$client = new SquareClient([
				'accessToken' => $access_token
			]);
			
			$price_money = new Money();
			$price_money->setAmount($this->order->paymentAmount * 100);
			$price_money->setCurrency($this->currency);
			
			$order_item = new OrderLineItem('1');
			$order_item->setName($this->order->singleProductName);
			$order_item->setBasePriceMoney($price_money);
			
			$line_items = [
				$order_item
			];
			
			$order = new Order($location_id);
			$order->setLineItems($line_items);
			$order->setReferenceId($this->order->id);
			
			$checkout_options = new CheckoutOptions();
			$checkout_options->setRedirectUrl($this->getCallbackUrl());
			
			
			$body = new CreatePaymentLinkRequest();
			$body->setIdempotencyKey(uniqid());
			$body->setCheckoutOptions($checkout_options);
			$body->setOrder($order);
			
			$api_response = $client->getCheckoutApi()->createPaymentLink($body);
			
			if ($api_response->isSuccess()) {
				$result = $api_response->getResult();
				
				redirect($result->getPaymentLink()->getUrl());
			}
			else {
				throw new Exception($api_response->getErrors()[0]->getDetail());
			}
		}
		
		/**
		 * @throws Exception
		 */
		public function callback(): SuccessfulPayment
		{
			$access_token = $this->config["access_token"];
			
			$client = new SquareClient([
				'accessToken' => $access_token
			]);
			
			$paymentID = get("orderId");
			$orderResponse = $client->getOrdersApi()->retrieveOrder($paymentID);
			if ($orderResponse->isSuccess()) {
				$order = $orderResponse->getResult()->getOrder();
				if ($order->getState() == "COMPLETED"){
					$orderID = $order->getReferenceId();
					
					return new SuccessfulPayment($orderID, $paymentID);
				}
			}
			else {
				throw new Exception($orderResponse->getErrors()[0]->getDetail());
			}
		}
	}