<?php 

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

		$config = obter_configuracao();

		$nome = filter_input(INPUT_POST, "nome_plano", FILTER_SANITIZE_STRING);
		// $valor = str_replace(",", ".", str_replace(".", "", filter_input(INPUT_POST, "valor_plano", FILTER_SANITIZE_STRING)));
		$porcentagem_valor_plano = filter_input(INPUT_POST, "porcentagem_valor_plano", FILTER_SANITIZE_STRING);
		if ($config->comissao_indicacao == "S") {
			// $comissao = str_replace(",", ".", str_replace(".", "", filter_input(INPUT_POST, "comissao_plano", FILTER_SANITIZE_STRING)));
			$porcentagem_comissao_plano = filter_input(INPUT_POST, "porcentagem_comissao_plano", FILTER_SANITIZE_STRING);
		}
		else{
			$comissao = "0.00";
		}
		$cor = filter_input(INPUT_POST, "cor_plano", FILTER_SANITIZE_STRING);
		$porcentagens = filter_var_array($_POST["niveis"], FILTER_SANITIZE_STRING);

		$model = new Model();

		if ($model->issetElementInTable("plano", ["nome_plano" => $nome])) {
			echo json_encode(["status" => false, "motivo" => "nome"]);
			exit();
		}

		if ($model->issetElementInTable("plano", ["cor_plano" => $cor])) {
			echo json_encode(["status" => false, "motivo" => "cor"]);
			exit();
		}

		$id_plano = $model->insert("plano", [
			"nome_plano" => $nome,
			"porcentagem_valor_plano" => $porcentagem_valor_plano,
			"porcentagem_comissao_plano" => $porcentagem_comissao_plano,
			"cor_plano" => $cor,
			"status_plano" => "S"
		]);

		if ($id_plano > 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")
			]);

			for ($i=1; $i <= count($porcentagens); $i++) {
				$result = $model->insert("nivel", [
					"nome_nivel" => "Nível $i",
					"porcentagem_nivel" => $porcentagens[($i-1)],
					"id_plano" => $id_plano
				]);

				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 json_encode(["status" => false]);
					exit();	
				}
			}

			$model->commit();
			echo json_encode(["status" => true]);
		}
		else{
			$model->rollback();
			echo json_encode(["status" => false]);
		}
	}
	else{
		show_403();
	}

?>