<?php
	namespace Main\Libs\Payment\PaymentGateways;
	
	use Exception;
	use Main\Libs\Payment\PaymentGateway;
	use Main\Libs\Payment\SuccessfulPayment;
	use Shopier\Enums\ProductType;
	use Shopier\Enums\WebsiteIndex;
	use Shopier\Exceptions\NotRendererClassException;
	use Shopier\Exceptions\RendererClassNotFoundException;
	use Shopier\Exceptions\RequiredParameterException;
	use Shopier\Models\Address;
	use Shopier\Models\Buyer;
	use Shopier\Models\ShopierResponse;
	use Shopier\Renderers\AutoSubmitFormRenderer;
	
	class Shopier extends PaymentGateway
	{
		protected bool $isContactRequired = true;
		protected bool $isBrowserSideCallback = true;
		
		/**
		 * @throws RendererClassNotFoundException
		 * @throws NotRendererClassException
		 * @throws RequiredParameterException
		 */
		public function payment()
		{
			$shopier = new \Shopier\Shopier($this->config['api_key'], $this->config['secret_key']);
			
			// Satın alan kişi bilgileri
			$buyer = new Buyer([
				'id'      => $this->customer->id,
				'name'    => $this->customer->contact->name,
				'surname' => $this->customer->contact->surname,
				'email'   => $this->customer->email,
				'phone'   => $this->customer->contact->phoneNumber,
			]);
			
			// Fatura ve kargo adresi birlikte tanımlama
			// Ayrı ayrı da tanımlanabilir
			$address = new Address([
				'address'   => 'Esentepe Mahallesi Eski Büyükdere Caddesi, Tekfen Tower No:209, 34343 4.Levent/Şişli',
				'city'      => 'İstanbul',
				'country'   => 'Türkiye',
				'postcode'  => '34343',
			]);
			
			// shopier parametrelerini al
			$params = $shopier->getParams();
			
			// Geri dönüş sitesini ayarla
			$params->setWebsiteIndex(WebsiteIndex::SITE_1);
			
			// Satın alan kişi bilgisini ekle
			$params->setBuyer($buyer);
			
			// Fatura ve kargo adresini aynı şekilde ekle
			$params->setAddress($address);
			
			// Sipariş numarası ve sipariş tutarını ekle
			$extraData = $this->order->id;
			$params->setOrderData($extraData, $this->order->paymentAmount);
			
			// Sipariş edilen ürünü ekle
			$params->setProductData($this->order->singleProductName, ProductType::DOWNLOADABLE_VIRTUAL);
			
			$renderer = $shopier->createRenderer(AutoSubmitFormRenderer::class);
			$shopier->goWith($renderer);
		}
		
		public function callback(): SuccessfulPayment
		{
			$shopierResponse = ShopierResponse::fromPostData();
			if ($shopierResponse->hasValidSignature($this->config["secret_key"])) {
				$orderID = post("platform_order_id");
				$paymentID = (string)post("payment_id");
				
				return new SuccessfulPayment($orderID, $paymentID);
			}
			else {
				redirect($this->getCancelUrl());
			}
		}
	}