<?php

	class PagSeguro{
		private $email;
		private $token;

		private $url;
		private $url_redirect;
		private $url_notificacao;
		private $url_transactions;

		private $params = [];
		private $count = 1;

		private static $status_code = [
			0 => "Pendente",
			1 => "Aguardando pagamento",
			2 => "Em análise",
			3 => "Pago",
			4 => "Disponível",
			5 => "Em disputa",
			6 => "Devolvida",
			7 => "Cancelada"
		];
			
		public function __construct($active = true){
			if ($active == true) {
				$this->url               = "https://ws.pagseguro.uol.com.br/v2/checkout/";
				$this->url_redirect      = "https://pagseguro.uol.com.br/v2/checkout/payment.html?code=";
				$this->url_notifications = "https://ws.pagseguro.uol.com.br/v2/transactions/notifications/";
				$this->url_transactions  = "https://ws.pagseguro.uol.com.br/v2/transactions/";
			}
			else{
				$this->url               = "https://ws.sandbox.pagseguro.uol.com.br/v2/checkout/";
				$this->url_redirect      = "https://sandbox.pagseguro.uol.com.br/v2/checkout/payment.html?code=";
				$this->url_notifications = "https://ws.sandbox.pagseguro.uol.com.br/v2/transactions/notifications/";
				$this->url_transactions  = "https://ws.sandbox.pagseguro.uol.com.br/v2/transactions/";
			}
		}

		public function setEmail($email){
			$this->email = filter_var($email, FILTER_SANITIZE_EMAIL);
		}

		public function setToken($token){
			$this->token = filter_var($token, FILTER_SANITIZE_STRING);
		}

		public function addItem($data){
			$this->params["itemId".$this->count] = (!empty($data["id"])) ? $data["id"] : rand(1, 9999);
			$this->params["itemDescription".$this->count] = $data["description"];
			$this->params["itemAmount".$this->count] = number_format($data["amount"], 2, ".", "");
			$this->params["itemQuantity".$this->count] = (!empty($data["quantity"])) ? intval($data["quantity"]) : 1;
			$this->params["itemWeight".$this->count] = (!empty($data["weight"])) ? $data["weight"] : 0;

			$this->count++;
		}

		public function setMethod($method){
			$this->params["mode"] = "default";
			$this->params["method"] = filter_var($method, FILTER_SANITIZE_STRING);
		}

		public function setRedirect($url){
			$this->params["redirectURL"] = filter_var($url, FILTER_SANITIZE_URL);
		}

		public function setNotification($url){
			$this->params["notificationURL"] = filter_var($url, FILTER_SANITIZE_URL);
		}

		public function setReference($reference){
			$this->params["reference"] = filter_var($reference, FILTER_SANITIZE_STRING);
		}

		public function checkout(){
			$this->params["email"] = $this->email;
			$this->params["token"] = $this->token;
			$this->params["currency"] = "BRL";

			$data = http_build_query($this->params);

			$curl = curl_init($this->url);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
			curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8"));
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
			$response = curl_exec($curl);
			curl_close($curl);

			$this->params = [];
			$this->count = 1;

			if ($response == "Unauthorized") {
				echo "Erro: Os dados fornecido são inválidos!";
				exit();
			}

			$result = simplexml_load_string($response);

			if (count($result->error) > 0) {
				echo "Erro: ".var_export($result->errors, true);
				exit();
			}

			return $this->url_redirect.$result->code;
		}

		public function getNotification($code){
			$url = $this->url_notifications.$code."/?email=".$this->email."&token=".$this->token;

			$curl = curl_init($url);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);			
			$response = curl_exec($curl);
			curl_close($curl);

			if ($response == "Unauthorized") {
				exit();
			}

			return simplexml_load_string($response);
		}

		public function getTransaction($code=null, $info=null){
			try {
				if (!empty($code) and $code != null) {
					$url = $this->url_transactions.$code."/?email=".$this->email."&token=".$this->token;
				}
				else if (!empty($info) and $info != null and is_array($info)) {
					$data = http_build_query($info);
					$url = $this->url_transactions."?email=".$this->email."&token=".$this->token."&".$data;
				}
				else{
					return false;
				}
	
				$curl = curl_init($url);
				curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);			
				$response = curl_exec($curl);
				curl_close($curl);
	
				if ($response == "Unauthorized") {
					return false;
				}
	
				return simplexml_load_string($response);
			} 
			catch (\Throwable $th) {
				return false;
			}
		}

		public function getStatusDescription($code){
			if (is_numeric($code)) {
				if ($code >= 1 and $code <= 7) {
					return self::$status_code[$code];
				}
			}
			return false;
		}
	}

?>