<?php 

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

		$nome_subcategoria = filter_input(INPUT_POST, "nome_subcategoria", FILTER_SANITIZE_STRING);
		$id_categoria = (int) filter_input(INPUT_POST, "id_categoria", FILTER_SANITIZE_NUMBER_INT);
		$id_subcategoria = (int) encrypt_decode(filter_input(INPUT_POST, "id_subcategoria", FILTER_SANITIZE_STRING));

		$model = new Model();

		$result = $model->update("subcategoria", [
			"nome_subcategoria" => $nome_subcategoria,
			"id_categoria" => $id_categoria
		], [
			"id_subcategoria" => $id_subcategoria
		]);

		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")
			]);

			$model->commit();
			echo "<script>window.location.href='".show_link("/visualizar-categoria/?categoria=".urlencode(encrypt_encode($id_categoria))."&editar_sub=true")."';</script>";
		}
		else{
			$model->rollback();
			echo "<script>window.location.href='".show_link("/visualizar-categoria/?categoria=".urlencode(encrypt_encode($id_categoria))."&editar_sub=false")."';</script>";
		}
	}
	else{
		show_403();
	}

?>