<?php if (Session::get("tipo_usuario") != "1"){ show_403();} ?>
<?php if ($_SERVER["REQUEST_METHOD"] != "POST"){ show_403();} ?>
<?php import_file(DIR_TEMPLATES."header.php", ["title" => "Editar Banco", "active_page" => "bancos"]); ?>
<?php import_file(DIR_MODELS."Model.class.php"); ?>

<?php 

	$id_banco = encrypt_decode(filter_input(INPUT_POST, "id_banco", FILTER_SANITIZE_STRING));

	$model = new Model();

	$result = $model->query("SELECT * FROM banco WHERE id_banco = :id AND status_banco = 'S'", [":id" => $id_banco]);

	$dados = $result->fetch();

?>

<h4 class="mb-3">
	<i class="fa-regular fa-edit"></i> Editar Banco
</h4>

<div class="content-box">
	<form id="form-banco">
		<div class="form-row">
			<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
				<div class="form-group">
					<label for="codigo-banco">Código<span class="text-danger">*</span></label>
					<input type="text" name="codigo_banco" id="codigo-banco" class="form-control" value="<?php echo $dados->codigo_banco; ?>" maxlength="20" required>
				</div>
			</div>

			<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
				<div class="form-group">
					<label for="nome-banco">Nome<span class="text-danger">*</span></label>
					<input type="text" name="nome_banco" id="nome-banco" class="form-control" value="<?php echo $dados->nome_banco; ?>" maxlength="120" required>
				</div>
			</div>
		</div>
		
		<input type="hidden" name="id_banco" class="d-none" value="<?php echo encrypt_encode($id_banco); ?>">

		<button type="submit" class="btn btn-primary">
			<i class="fa-regular fa-save"></i> Salvar
		</button>
		<a href="<?php echo show_link("/bancos/"); ?>" class="btn btn-secondary">
			<i class="fa-regular fa-arrow-left"></i> Voltar
		</a>
	</form>
</div>

<script>
	$("#form-banco").submit(function(event){
		event.preventDefault();
		var form = $(this);
		$.ajax({
			type: "POST",
			data: form.serialize(),
			url: "<?php echo show_link("/editar-banco/"); ?>",
			async: true
		}).then(function(response){
			var result = $.parseJSON(response);
			if (result.status == true) {
				$.toast({
					heading: "Aviso",
					text: "Dados Atualizado com Sucesso!",
					icon: "success",
					loader: true
				});
			}
			else if (result.status == false && result.motivo == "codigo") {
				$("#codigo-banco").addClass("is-warning");
				$.toast({
					heading: "Aviso",
					text: "Um banco com esse código já foi cadastrado no sistema!",
					icon: "warning",
					loader: true
				});
				$("#codigo-banco").keyup(function(){
					$(this).removeClass("is-warning");
					$(this).off("keyup");
				});
			}
			else{
				$.toast({
					heading: "Aviso",
					text: "Erro ao Atualizar os Dados!",
					icon: "error",
					loader: true
				});
			}
		}, function(error){
			console.log("Erro: "+error);
		});
	});
</script>

<?php import_file(DIR_TEMPLATES."footer.php"); ?>