<?php if (Session::get("tipo_usuario") != "1"){ show_403();} ?>
<?php import_file(DIR_TEMPLATES."header.php", ["title" => "Planos de Produtos", "active_page" => "planos"]); ?>
<?php import_file(DIR_MODELS."Model.class.php"); ?>
<?php import_file(DIR_LIBRARIES."functions.php"); ?>

<?php $config = obter_configuracao(); ?>

<div class="row align-items-center mb-3">
	<div class="col-6">
		<h4 class="mb-0">
			<i class="fa-regular fa-medal"></i> Planos de Produtos
		</h4>
	</div>
	<div class="col-6 text-right">
		<a href="<?php echo show_link("/cadastro-plano/"); ?>" class="btn btn-primary">
			<i class="fa-regular fa-plus"></i> Adicionar
		</a>
	</div>
</div>

<div class="content-box">
	<div class="form-row mb-3">
		<div class="col-xl-8 col-lg-8 col-md-6 col-sm-12"></div>
		<div class="col-xl-4 col-lg-4 col-md-6 col-sm-12">
			<form action="" method="get">
				<div class="input-group">
					<input type="text" name="pesquisa" class="form-control" autocomplete="off" value="<?php echo filter_input(INPUT_GET, "pesquisa", FILTER_SANITIZE_STRING); ?>">
					<div class="input-group-append">
						<button class="btn btn-primary">
							<i class="fa-regular fa-search"></i>
						</button>
					</div>
				</div>
			</form>
		</div>
	</div>

	<div class="table-responsive">
		<table class="table table-sm table-hover table-striped">
			<thead class="thead-inverse">
				<tr>
					<th class="align-middle text-left" style="width: 35%;">Nome</th>
					<th class="align-middle text-center" style="width: 20%;">Porcentagem do Valor</th>
					<?php if ($config->comissao_indicacao == "S"): ?>
						<th class="align-middle text-center" style="width: 20%;">Porcentagem da Comissão</th>
					<?php endif; ?>
					<th class="align-middle text-center" style="width: 10%;">Cor</th>
					<th class="align-middle text-center" style="width: 10%;">Situação</th>
					<th class="align-middle text-center" style="width: 5%;">Opções</th>
				</tr>
			</thead>
			<tbody>
				<?php 

					$model = new Model();

					$maximo = 15;

					if (isset($_GET["pag"])) {
						$pagina = filter_input(INPUT_GET, "pag", FILTER_SANITIZE_NUMBER_INT);
					}
					else{
						$pagina = 1;
					}

					$pesquisa = filter_input(INPUT_GET, "pesquisa", FILTER_SANITIZE_STRING);

					$inicio = (($maximo*$pagina)-$maximo);

					$busca = $model->query("
						SELECT * FROM plano 
						WHERE 
							(
								nome_plano LIKE :pesquisa
							) 
						ORDER BY 
							id_plano DESC 
						LIMIT 
							:maximo OFFSET :inicio
					", [
						":pesquisa" => "%".$pesquisa."%", 
						":maximo" => $maximo, 
						":inicio" => $inicio
					]);

					$n = ($pagina*$maximo)-$maximo + 1;

					foreach ($busca->fetchAll() as $dados):

				?>

					<tr>
						<td class="align-middle text-left"><?php echo $dados->nome_plano; ?></td>
						<td class="align-middle text-center"><?php echo floatval($dados->porcentagem_valor_plano)."%"; ?></td>
						<?php if ($config->comissao_indicacao == "S"): ?>
							<td class="align-middle text-center"><?php echo floatval($dados->porcentagem_comissao_plano)."%"; ?></td>
						<?php endif; ?>
						<td class="align-middle text-center">
							<div class="mx-auto" style="background-color: <?php echo $dados->cor_plano; ?>; width: 30px; height: 30px; border-radius: 30px;"></div>
						</td>
						<td class="align-middle text-center">
							<?php if ($dados->status_plano == "S"): ?>
								<span class="badge badge-success">
									Ativo
								</span>
							<?php else: ?>
								<span class="badge badge-danger">
									Inativo
								</span>
							<?php endif; ?>
						</td>
						<td class="align-middle text-center">
							<div class="d-inline-flex">
								<div class="mx-auto">
									<?php if ($dados->status_plano == "S"): ?>
										<button type="button" class="btn btn-info btn-square btn-ver-mais" data-value="<?php echo encrypt_encode($dados->id_plano); ?>" data-toggle="tooltip" data-placement="bottom" title="Ver Detalhes">
											<i class="fa-regular fa-search-plus"></i>
										</button>
									<?php else: ?>
										<button type="button" class="btn btn-info btn-square" disabled>
											<i class="fa-regular fa-search-plus"></i>
										</button>
									<?php endif; ?>
								</div>
							
								<div class="mx-2">
									<?php if ($dados->status_plano == "S"): ?>
										<form action="<?php echo show_link("/edita-plano/"); ?>" method="post">
											<input type="hidden" name="id_plano" class="d-none" value="<?php echo encrypt_encode($dados->id_plano); ?>">
											<button type="submit" class="btn btn-warning btn-square" data-toggle="tooltip" data-placement="bottom" title="Editar">
												<i class="fa-regular fa-pencil-alt"></i>
											</button>
										</form>
									<?php else: ?>
										<button type="button" class="btn btn-warning btn-square" disabled>
											<i class="fa-regular fa-pencil-alt"></i>
										</button>
									<?php endif; ?>
								</div>
							
								<div class="mx-auto">
									<?php if ($dados->status_plano == "S"): ?>
										<button type="button" class="btn btn-danger btn-square btn-mudar-status" data-value="<?php echo encrypt_encode($dados->id_plano); ?>" data-status="N" data-toggle="tooltip" data-placement="bottom" title="Desativar">
											<i class="fa-regular fa-times"></i>
										</button>
									<?php else: ?>
										<button type="button" class="btn btn-success btn-square btn-mudar-status" data-value="<?php echo encrypt_encode($dados->id_plano); ?>" data-status="S" data-toggle="tooltip" data-placement="bottom" title="Ativar">
											<i class="fa-regular fa-check"></i>
										</button>
									<?php endif; ?>
								</div>
							</div>
						</td>
					</tr>	
				<?php endforeach; ?>
			</tbody>
		</table>
	</div>

	<ul class="pagination justify-content-center" style="margin-bottom: -15px;">
		<?php 

			$busca = $model->query("SELECT * FROM plano WHERE (nome_plano LIKE :pesquisa) ORDER BY id_plano DESC", [":pesquisa" => "%".$pesquisa."%"]);

			$total  = $busca->rowCount();

			$total_paginas = ceil($total/$maximo);
						   
			if ($pagina <= $total_paginas and $pagina > 1) {
 				echo '<li class="page-item"><a href="?'.(!empty($pesquisa) ? "pesquisa=".$pesquisa."&" : "").'pag='.($pagina-1).'" class="page-link"><span aria-hidden="true">&laquo;</span></a> </li>';
			}

			echo ' <li class="page-item active"><p class="page-link">'.$pagina.'</p></li> ';

			if ($pagina < $total_paginas) {	
				echo '<li class="page-item"><a href="?'.(!empty($pesquisa) ? "pesquisa=".$pesquisa."&" : "").'pag='.($pagina+1).'" class="page-link"><span aria-hidden="true">&raquo;</span></a></li> ';
			}
			
		?>
	</ul>
</div>

<!-- Modal Ver Mais Plano -->
<div class="modal fade" id="modal-ver-mais-plano" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-lg" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title">
					<i class="fa-regular fa-search-plus"></i> Detalhes do Plano
				</h5>
			</div>
			<div class="modal-body" id="modal-content">
				
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-white" data-dismiss="modal">
					<i class="fa-regular fa-times"></i> Fechar
				</button>
			</div>
		</div>
	</div>
</div>

<!-- Modal Mudar Status Plano -->
<div class="modal fade" id="modal-mudar-status-plano" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title"><i class="fa-regular fa-exclamation-triangle"></i> Aviso</h5>
			</div>
			<div class="modal-body">
				<p id="modal-text"></p>
			</div>
			<div class="modal-footer">
				<form action="<?php echo show_link("/mudar-status-plano/"); ?>" method="post">
					<input type="hidden" name="id_plano" id="input-plano-id" class="d-none" required>
					<input type="hidden" name="status_plano" id="input-plano-status" class="d-none" required>
					<button type="submit" class="btn btn-white">
						<i class="fa-regular fa-check"></i> Sim
					</button>
					<button type="button" class="btn btn-white" data-dismiss="modal">
						<i class="fa-regular fa-times"></i> Não
					</button>
				</form>
			</div>
		</div>
	</div>
</div>

<script>
	$(".btn-ver-mais").click(function(){
		let id = $(this).data("value");

		$.ajax({
			type: "POST",
			data: "id_plano="+id,
			url: "<?php echo show_link("/obter-niveis/"); ?>",
			async: true
		}).then(function(response){
			let result = $.parseJSON(response);

			if (result.status == true) {
				let html = "";
				let data = result.dados;

				for (let i = 0; i < data.length; i++) {
					if (i+1 == data.length && data.length % 2 == 1) {
						html += `
							<tr>
								<th class="align-middle" colspan="2">${data[i].nome_nivel}</th>
							</tr>
							<tr>
								<td class="align-middle" colspan="2">${data[i].porcentagem_nivel.replace(".", ",")}%</th>
							</tr>
						`;
					}
					else {
						html += `
							<tr>
								<th class="align-middle">${data[i].nome_nivel}</th>
								<th class="align-middle">${data[i+1].nome_nivel}</th>
							</tr>
							<tr>
								<td class="align-middle">${data[i].porcentagem_nivel.replace(".", ",")}%</th>
								<td class="align-middle">${data[i+1].porcentagem_nivel.replace(".", ",")}%</th>
							</tr>
						`;

						i++;
					}
				}

				$("#modal-content").html(`
					<table class="table table-sm table-striped table-bordered">
						${html}
					</table>
				`);

				$("#modal-ver-mais-plano").modal("show");
			}
			else{
				$.toast({
					heading: "Aviso",
					text: "Erro ao obter os niveis!",
					icon: "error",
					loader: true
				});
			}
		}, function(error){
			console.log("Erro: "+error);
		});
	});

	$(".btn-mudar-status").click(function(){
		var id = $(this).data("value");
		var status = $(this).data("status");

		if (status == "S") {
			var info = "<strong class='text-success'>ATIVAR</strong>";
		}
		else{
			var info = "<strong class='text-danger'>DESATIVAR</strong>";
		}

		$("#modal-text").html("Tem certeza que deseja "+info+" esse plano?");

		$("#input-plano-id").val(id);
		$("#input-plano-status").val(status);
		$("#modal-mudar-status-plano").modal("show");
	});
</script>

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