<?php
	/* LeaderOS
	 * Discord Webhook Class
	 * @author : benfiratkaya
	 * @copyright : https://firatkaya.net
	 */
	
	namespace Api\Libs;
	use Exception;
	
	class DiscordWebhook
	{
		private $event;
		private $url;
		private $botName;
		private $botAvatar;
		private $data;
		private array $variables;
		private $processedData;
		
		/**
		 * DiscordWebhook constructor.
		 * @param $event
		 * @param $url
		 * @param $botName
		 * @param $botAvatar
		 * @param $data
		 * @param array $variables
		 */
		public function __construct($event, $url, $botName, $botAvatar, $data, array $variables = [])
		{
			$this->event = $event;
			$this->url = $url;
			$this->variables = $variables;
			$this->botName = $botName;
			$this->botAvatar = $botAvatar;
			$this->data = $data;
			
			$this->processData();
		}
		
		private function processData(): void
		{
			$this->processedData = json_decode($this->fixJSON($this->data), true);
			$this->processedData['username'] = $this->botName;
			$this->processedData['avatar_url'] = $this->botAvatar;
			$this->processedData = $this->replaceVariables(json_encode($this->processedData));
		}
		
		private function replaceVariables($data)
		{
			foreach ($this->variables as $key => $value) {
				$placeholder = '{' . $key . '}';
				$data = str_replace($placeholder, $value, $data);
			}
			
			return $data;
		}
		
		private function fixJSON($json)
		{
			return str_replace('&quot;', '"', $json);
		}
		
		/**
		 * Send Webhook
		 * @return mixed
		 * @throws Exception
		 */
		public function send()
		{
			return $this->request();
		}
		
		/**
		 * @throws Exception
		 */
		private function request()
		{
			$request = curl_init($this->url);
			
			// Curl options
			curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($request, CURLOPT_CUSTOMREQUEST, 'POST');
			curl_setopt($request, CURLOPT_POSTFIELDS, $this->processedData);
			curl_setopt($request, CURLOPT_HTTPHEADER, [
				'Content-Type: application/json',
			]);
			
			$response = curl_exec($request);
			$error = curl_error($request);
			$errorNo = curl_errno($request);
			$httpCode = curl_getinfo($request, CURLINFO_HTTP_CODE);
			curl_close($request);
			
			if ($errorNo !== 0)
				throw new Exception($error, $errorNo);
			
			return $httpCode;
		}
	}
	
	?>