<?php
	namespace Main\Services;
	
	use Main\Libs\Payment\Customer;
	use Main\Libs\Payment\CustomerContact;
	use Main\Libs\Payment\PaymentGateway;
	use Exception;
	
	class PaymentGatewayService
	{
		/**
		 * @throws Exception
		 */
		public static function init($name, $currency, $config): PaymentGateway
		{
			// Parse the name to make sure it is a valid class name
			$className = str_replace(['-', '_'], '', ucwords($name, '-_'));
			
			// Namespace with the class
			$className = "Main\\Libs\\Payment\\PaymentGateways\\$className";
			
			// Currency
			if ($currency == null || $currency == "") {
				$currency = settings('currency');
			}
			
			// Config
			$config = self::parseConfig($config);
			
			if (class_exists($className)) {
				return new $className($name, $currency, $config);
			} else {
				throw new Exception("Payment Gateway not found: $className");
			}
		}
		
		/**
		 * @throws Exception
		 */
		public static function parseConfig($config): array
		{
			if ($config == null || $config == "" || $config == "{}") {
				throw new Exception("Payment Gateway config is required");
			}
			$config = json_decode($config, true);
			if ($config == null) {
				throw new Exception("Payment Gateway config is invalid");
			}
			
			$parsedConfig = [];
			foreach ($config as $configItem) {
				$parsedConfig[$configItem["key"]] = $configItem["value"];
			}
			
			return $parsedConfig;
		}
		
		public static function getCustomer($id = null): ?Customer
		{
			if ($id == null) {
				$id = auth()->user()->id();
				$username = auth()->user()->displayName();
				$email = auth()->user()->email();
			} else {
				$user = db()->prepare("SELECT * FROM Accounts WHERE id = ?");
				$user->execute([$id]);
				$user = $user->fetch();
				if (!$user) {
					return null;
				}
				$username = $user["realname"];
				$email = $user["email"];
			}
			
			$contact = null;
			$userContact = db()->prepare("SELECT * FROM AccountContactInfo WHERE accountID = ?");
			$userContact->execute([$id]);
			$userContact = $userContact->fetch();
			if ($userContact) {
				$contact = new CustomerContact(
					$userContact["firstName"],
					$userContact["lastName"],
					$userContact["phoneNumber"]
				);
			}
			
			return new Customer(
				$id,
				$username,
				$email,
				getIP(),
				$contact
			);
		}
	}