<?php
	namespace Main\Libs\Payment\PaymentGateways;
	
	use Exception;
	use Main\Libs\Payment\PaymentGateway;
	use Main\Libs\Payment\SuccessfulPayment;
	use Mollie\Api\Exceptions\ApiException;
	use Mollie\Api\MollieApiClient;
	
	class Mollie extends PaymentGateway
	{
		public function payment()
		{
			$mollie = new MollieApiClient();
			$mollie->setApiKey($this->config["api_key"]);
			$payment = $mollie->payments->create([
				"amount" => [
					"currency" => $this->currency,
					"value" => $this->order->paymentAmount
				],
				"metadata" => [
					"orderID" => $this->order->id,
				],
				"description" => $this->order->singleProductName,
				"redirectUrl" => $this->getSuccessUrl(),
				'cancelUrl' => $this->getCancelUrl(),
				"webhookUrl"  => $this->getCallbackUrl(),
			]);
			redirect($payment->getCheckoutUrl());
		}
		
		/**
		 * @throws ApiException
		 * @throws Exception
		 */
		public function callback(): SuccessfulPayment
		{
			$mollie = new MollieApiClient();
			$mollie->setApiKey($this->config["api_key"]);
			$payment = $mollie->payments->get(post("id"));
			
			if ($payment->isPaid() && !$payment->hasRefunds() && !$payment->hasChargebacks()) {
				$orderID = $payment->metadata->orderID;
				$paymentID = $payment->id;
				
				return new SuccessfulPayment($orderID, $paymentID);
			} else {
				throw new Exception("Payment failed");
			}
		}
	}