<?php 

	if (Session::get("tipo_usuario") != "4"){ show_403();}
	if ($_SERVER["REQUEST_METHOD"] == "POST") {
		import_file(DIR_MODELS."Model.class.php");
		import_file(DIR_LIBRARIES."functions.php");

		$id = encrypt_decode(filter_input(INPUT_POST, "id_solicitacao_saldo", FILTER_SANITIZE_STRING));
		$status = filter_input(INPUT_POST, "status_solicitacao_saldo", FILTER_SANITIZE_STRING);

		$model = new Model();

		if (!empty($id) and !empty($status)) {
			$data = $model->query("
				SELECT * FROM solicitacao_saldo 
				WHERE 
					id_solicitacao_saldo = :id
			", [
				":id" => $id
			])->fetch();

			if ($status == "S") {
				$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) {
					$last_query = $model->lastQuery();
					$model->insert("historico", [
						"comando_sql" => $last_query,
						"datahora_acao" => date("Y-m-d H:i:s"),
						"id_usuario" => Session::get("id_usuario")
					]);
				}
				else{
					$model->rollback();
					echo "<script>window.location.href='".show_link("/solicitacoes-saldo/?status=false")."';</script>";
					exit();
				}
			}

			// Muda o status da solicitação de saldo
			$result = $model->update("solicitacao_saldo", [
				"status_solicitacao_saldo" => $status
			],[
				"id_solicitacao_saldo" => $id
			]);

			if ($result > 0) {	
				// Gera o histórico da avaliação da solicitação de saldo
				$last_query = $model->lastQuery();
				$model->insert("historico", [
					"comando_sql" => $last_query,
					"datahora_acao" => date("Y-m-d H:i:s"),
					"id_usuario" => Session::get("id_usuario")
				]);

				$model->commit();
				echo "<script>window.location.href='".show_link("/solicitacoes-saldo/?status=true")."';</script>";
			}
			else{
				$model->rollback();
				echo "<script>window.location.href='".show_link("/solicitacoes-saldo/?status=false")."';</script>";
			}
		}
		else{
			echo "<script>window.location.href='".show_link("/solicitacoes-saldo/?status=false")."';</script>";
			exit();
		}
	}
	else{
		show_403();
	}

?>