<?php 

	header("access-control-allow-origin: https://pagseguro.uol.com.br");

	if (isset($_POST["notificationType"]) and $_POST["notificationType"] == "transaction") {
		import_file(DIR_MODELS."Model.class.php");
		import_file(DIR_LIBRARIES."functions.php");
		import_file(DIR_LIBRARIES."PagSeguro/PagSeguro.class.php");

		$code = filter_input(INPUT_POST, "notificationCode", FILTER_SANITIZE_STRING);
		$id_solicitacao_saldo = (int) encrypt_decode(filter_input(INPUT_GET, "saldo", FILTER_SANITIZE_STRING));

		$model = new Model();

		$config = obter_configuracao();

		if ($config->ambiente_teste_pagseguro == "S") {
			$pagseguro = new PagSeguro(false);
		}
		else{
			$pagseguro = new PagSeguro(true);
		}

		$pagseguro->setEmail($config->email_pagseguro);
		$pagseguro->setToken($config->token_pagseguro);

		$notification = $pagseguro->getNotification($code);

		if (intval($notification->status) == 3 or intval($notification->status) == 4) {
			$result = $model->query("
				SELECT * FROM solicitacao_saldo 
				WHERE 
					id_solicitacao_saldo = :id
			", [
				":id" => $id_solicitacao_saldo
			]);

			$data = $result->fetch();

			$result = $model->insert("entrada", [
				"id_usuario" => $data->id_usuario,
				"valor_entrada" => $data->valor_saldo,
				"descricao_entrada" => "Valor proveniente de compra de saldo",
				"datahora_entrada" => date("Y-m-d H:i:s"),
				"status_entrada" => "S"
			]);

			if ($result > 0) {
				$result = $model->update("solicitacao_saldo", [
					"codigo_transacao" => $notification->code,
					"status_solicitacao_saldo" => "S"
				], [
					"id_solicitacao_saldo" => $id_solicitacao_saldo
				]);

				if ($result > 0) {
					$model->commit();
				}
				else{
					$model->rollback();
				}
			}
			else{
				$model->rollback();
			}
		}
		elseif (intval($notification->status) == 7) {
			$model->update("solicitacao_saldo", [
				"codigo_transacao" => $notification->code,
				"status_solicitacao_saldo" => "N"
			], [
				"id_solicitacao_saldo" => $id_solicitacao_saldo
			]);

			$model->commit();
		}
		else{
			$model->update("solicitacao_saldo", [
				"codigo_transacao" => $notification->code
			], [
				"id_solicitacao_saldo" => $id_solicitacao_saldo
			]);

			$model->commit();
		}
	}

	$file = fopen("log_pagseguro.txt", "a+");

	$text = "CODE: ".$_POST["notificationCode"]." | DATETIME: ".date("Y-m-d H:i:s")." | ID_SALDO: ".encrypt_decode($_GET["saldo"])."\n";

	fwrite($file, $text);

	fclose($file);

?>