<?php 

	import_file(DIR_MODELS."Model.class.php");

	if (isset($_GET["indicador"]) and !empty($_GET["indicador"])) {
		$indicador = (int) encrypt_decode(filter_input(INPUT_GET, "indicador", FILTER_SANITIZE_STRING));

		if (empty($indicador) or !is_numeric($indicador)) {
			$indicador = 1;
		}
	}
	else{
		$indicador = 1;
	}

	$produto = (int) encrypt_decode(filter_input(INPUT_GET, "produto", FILTER_SANITIZE_STRING));

	$model = new Model();

	$result = $model->query("
		SELECT * FROM usuario 
		WHERE 
			id_usuario = :id
	", [
		":id" => $indicador
	]);

	$dados_usuario = $result->fetch();

?>

<!DOCTYPE html>
<html lang="pt-br">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

		<link href="<?php echo show_file_link(SYS_ICONE); ?>" rel="icon" type="image/png">
		<title>Cadastro | <?php echo SYS_NAME; ?></title>

		<link href="<?php echo show_file_link("/assets/bootstrap/css/bootstrap.min.css"); ?>" rel="stylesheet">
		<link href="<?php echo show_file_link("/assets/fontawesome/releases/v6.2.0/css/all.css"); ?>" rel="stylesheet" type="text/css">
		<link href="<?php echo show_file_link("/assets/fontawesome/releases/v6.2.0/css/sharp-solid.css"); ?>" rel="stylesheet" type="text/css">
		<link href="<?php echo show_file_link("/assets/custom/css/custom.css"); ?>" rel="stylesheet">
		<link href="<?php echo show_file_link("/assets/jquery-toast/css/jquery.toast.css"); ?>" rel="stylesheet">
		<script src="<?php echo show_file_link("/assets/jquery/jquery.min.js"); ?>"></script>
		<script src="<?php echo show_file_link("/assets/bootstrap/js/bootstrap.bundle.min.js"); ?>"></script>
		<script src="<?php echo show_file_link("/assets/jquery-toast/js/jquery.toast.js"); ?>"></script>
		<script src="<?php echo show_file_link("/assets/jquery-mask/jquery.mask.js"); ?>"></script>
		<script src="<?php echo show_file_link("/assets/custom/js/scripts.js"); ?>"></script>

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

		<style>
			html, body{
				min-height: 100%;
			}
		</style>
	</head>
	<body style="background-image: linear-gradient(<?php echo GRADIENT_COLOR_1; ?>, <?php echo GRADIENT_COLOR_2; ?>);">
		<div class="container my-3">
			<div class="row justify-content-center">
				<div class="col-xl-8 col-lg-8 col-md-10 col-sm-12">
					<div class="card card-body o-hidden border-0 shadow-lg">
						<h4 class="text-center mb-2">
							<?php if (PRESENTATION_STANDARD == 1): ?>
								<a href="<?php echo show_link("/"); ?>">
									<img src="<?php echo show_file_link(SYS_SECONDARY_LOGO); ?>" alt="logo" style="max-width:250px; max-height:100px; width: auto; height: auto;">
								</a>
								<br>
								<?php echo SYS_NAME; ?>
							<?php elseif (PRESENTATION_STANDARD == 2): ?>
								<a href="<?php echo show_link("/"); ?>">
									<img src="<?php echo show_file_link(SYS_SECONDARY_LOGO); ?>" alt="logo" style="max-width:250px; max-height:100px; width: auto; height: auto;">
								</a>
							<?php else: ?>
								<a href="<?php echo show_link("/"); ?>">
									<?php echo SYS_NAME; ?>
								</a>
							<?php endif; ?>
							
							<br>

							<small>Crie a sua conta. É rápido e fácil!</small>
						</h4>

						<p class="text-center mb-3">Cadastro de pessoa física</p>

						<form id="form-cadastro-usuario" autocomplete="off">
							<div class="form-group">
								<label for="nome-usuario">Nome<span class="text-danger">*</span></label>
								<input type="text" name="nome_usuario" id="nome-usuario" class="form-control" maxlength="120" required>
							</div>

							<div class="form-row">
								<div class="col-md-6">
									<div class="form-group">
										<label for="data-nascimento-usuario">Data Nascimento<span class="text-danger">*</span></label>
										<input type="text" name="data_nascimento_usuario" id="data-nascimento-usuario" class="form-control" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="form-group">
										<label for="sexo-usuario">Sexo<span class="text-danger">*</span></label>
										<select name="sexo_usuario" id="sexo-usuario" class="form-control" required>
											<option value="">Selecione um...</option>
											<option value="M">Masculino</option>
											<option value="F">Feminino</option>
										</select>
									</div>
								</div>
							</div>

							<div class="form-row">
								<div class="col-md-6">
									<div class="form-group">
										<label for="cpf-usuario">CPF<span class="text-danger">*</span></label>
										<input type="text" name="cpf_usuario" id="cpf-usuario" class="form-control" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="form-group">
										<label for="telefone-usuario">Telefone<span class="text-danger">*</span></label>
										<input type="text" name="telefone_usuario" id="telefone-usuario" class="form-control" required>
									</div>
								</div>
							</div>

							<div class="form-row">
								<div class="col-md-6">
									<div class="form-group">
										<label for="id-estado">Estado<span class="text-danger">*</span></label>
										<select name="id_estado" id="id-estado" class="form-control" required>
											<option value="">Selecione um...</option>

											<?php

												$estados = $model->query("SELECT * FROM estado ORDER BY nome_estado ASC");

												foreach ($estados->fetchAll() as $i):

											?>
												<option value="<?php echo $i->id_estado; ?>"><?php echo $i->nome_estado; ?></option>
											<?php endforeach; ?>
										</select>
									</div>
								</div>

								<div class="col-md-6">
									<div class="form-group">
										<label for="id-cidade">Cidade<span class="text-danger">*</span></label>
										<select name="id_cidade" id="id-cidade" class="form-control" required>
											<option value="">Selecione um...</option>
										</select>
									</div>
								</div>
							</div>						

							<div class="form-row">
								<div class="col-md-6">
									<div class="form-group">
										<label for="email-usuario">E-mail<span class="text-danger">*</span></label>
										<input type="email" name="email_usuario" id="email-usuario" class="form-control" maxlength="255" required>
									</div>
								</div>

								<div class="col-md-6">
									<div class="form-group">
										<label for="senha-usuario">Senha<span class="text-danger">*</span></label>
										<div class="input-group">
											<input type="password" name="senha_usuario" id="senha-usuario" class="form-control" minlength="6" maxlength="32" required>
											<div class="input-group-append">
												<button type="button" id="btn-senha" class="btn btn-white">
													<i class="fa-solid fa-eye-slash"></i>
												</button>
											</div>
										</div>
									</div>
								</div>
							</div>

							<input type="hidden" name="indicador" class="d-none" value="<?php echo encrypt_encode($indicador); ?>">

							<div class="form-row align-items-center">
								<div class="col-md-6 mb-3">
									<button type="submit" class="btn btn-success">
										<i class="fa-regular fa-plus"></i> Cadastre-se
									</button>
								</div>
								<div class="col-md-6 text-md-right text-center mb-3">
									Já possui uma conta? <a href="<?php echo show_link("/login/"); ?>">Fazer login</a>
								</div>
							</div>
						</form>
					</div>

					<div class="text-center mt-3">
						<a href="<?php echo show_link("/"); ?>" class="text-white">
							Voltar para Início
						</a>
					</div>
				</div>
			</div>
		</div>

		<script src="<?php echo show_file_link("/assets/jquery-loading-overlay/loading-overlay.js"); ?>"></script>
		<script>
			$("#cpf-usuario").mask("000.000.000-00");
			$("#data-nascimento-usuario").mask("99/99/9999");
			$("#telefone-usuario").mask("(99) 99999-9999");

			$("#id-estado").change(function(){
				var id = $(this).val();

				$(".option-cidade").remove();

				if ($(this).val() != "") {
					$.ajax({
						type: "POST",
						data: {id_estado: id},
						url: "<?php echo show_link("/obter-cidades/"); ?>",
						async: true
					}).then(function(response){
						var result = $.parseJSON(response);

						if (result.status == true) {
							var html = "";

							$.each(result.dados, function(i, data){
								html += '<option value="'+data.id_cidade+'" class="option-cidade">'+data.nome_cidade+'</option>';
							});

							$("#id-cidade").append(html);
						}
					}, function(error){
						console.log("Erro: "+error);
					});
				}
			});

			$("#btn-senha").click(function(){
				if ($("#senha-usuario").attr("type") == "password") {
					$("#senha-usuario").attr("type", "text");
					$(this).html('<i class="fa-solid fa-eye"></i>');
				}
				else{
					$("#senha-usuario").attr("type", "password");
					$(this).html('<i class="fa-solid fa-eye-slash"></i>');
				}
			});

			$("#form-cadastro-usuario").submit(function(event){
				event.preventDefault();
				var form = $(this);
				$.ajax({
					type: "POST",
					data: form.serialize(),
					url: "<?php echo show_link("/cadastrar-usuario/"); ?>",
					async: true
				}).then(function(response){
					var result = $.parseJSON(response);
					if (result.status == true) {
						$.toast({
							heading: "Aviso",
							text: "Usuário Cadastrados com Sucesso!",
							icon: "success",
							loader: true
						});

						form.each(function(){
							this.reset();
						});

						setTimeout(function(){
							window.location.href = "<?php echo !empty($produto) ? show_link("/visualizar-produto/?produto=".urlencode(encrypt_encode($produto))) : show_link("/dashboard/"); ?>";
						},1200);
					}
					else if (result.status == false && result.motivo == "cpf") {
						$("#cpf-usuario").addClass("is-warning");
						$.toast({
							heading: "Aviso",
							text: "Esse CPF já foi cadastrado no sistema!",
							icon: "warning",
							loader: true
						});
						$("#cpf-usuario").keyup(function(){
							$(this).removeClass("is-warning");
							$(this).off("keyup");
						});
					}
					else if (result.status == false && result.motivo == "cpf_false") {
						$("#cpf-usuario").addClass("is-warning");
						$.toast({
							heading: "Aviso",
							text: "CPF Inválido!",
							icon: "warning",
							loader: true
						});
						$("#cpf-usuario").keyup(function(){
							$(this).removeClass("is-warning");
							$(this).off("keyup");
						});
					}
					else if (result.status == false && result.motivo == "data_false") {
						$("#data-nascimento-usuario").addClass("is-warning");
						$.toast({
							heading: "Aviso",
							text: "Data de Nascimento Inválida!",
							icon: "warning",
							loader: true
						});
						$("#data-nascimento-usuario").keyup(function(){
							$(this).removeClass("is-warning");
							$(this).off("keyup");
						});
					}
					else if (result.status == false && result.motivo == "email") {
						$("#email-usuario").addClass("is-warning");
						$.toast({
							heading: "Aviso",
							text: "Esse e-mail já foi cadastrado no sistema!",
							icon: "warning",
							loader: true
						});
						$("#email-usuario").keyup(function(){
							$(this).removeClass("is-warning");
							$(this).off("keyup");
						});
					}
					else{
						$.toast({
							heading: "Aviso",
							text: "Erro ao Cadastrar o Usuário!",
							icon: "error",
							loader: true
						});
					}
				}, function(error){
					console.log("Erro: "+error);
				});
			});

			$(document).ajaxStart(function(){
				$.LoadingOverlay("show", {
					fontawesome : "",
					image: "<?php echo show_file_link("/assets/img/loading.svg"); ?>",
				});
			});

			$(document).ajaxStop(function(){
				$.LoadingOverlay("hide");
			});

			$(".loadAjax").on("click", function(){
				$.LoadingOverlay("show", {
					fontawesome : "",
					image: "<?php echo show_file_link("/assets/img/loading.svg"); ?>"
				});
			});

			$("body").on("click", ".loadAjax", function(){
				$.LoadingOverlay("show", {
					fontawesome : "",
					image: "<?php echo show_file_link("/assets/img/loading.svg"); ?>"
				});
			});
		</script>
	</body>
</html>