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

<div class="row align-items-center mb-3">
	<div class="col-6">
		<h4 class="mb-0">
			<i class="fa-regular fa-fire-alt"></i> Planos de Lojas
		</h4>
	</div>
	<div class="col-6 text-right">
		<a href="<?php echo show_link("/cadastro-plano-loja/"); ?>" 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%;">Loja</th>
					<th class="align-middle text-left" style="width: 30%;">Plano</th>
					<th class="align-middle text-center" style="width: 10%;">Porcentagem</th>
					<th class="align-middle text-center" style="width: 10%;">Cashback</th>
					<th class="align-middle text-center" style="width: 10%;">Comissão</th>
					<th class="align-middle text-center" style="width: 5%;">Opções</th>
				</tr>
			</thead>
			<tbody>
				<?php 

					$model = new Model();

					$length = 15;

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

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

					$start = (($length*$page)-$length);

					$result = $model->query("
						SELECT * FROM plano_loja a
						INNER JOIN loja b ON (a.id_loja = b.id_loja) 
						INNER JOIN usuario c ON (b.id_usuario = c.id_usuario) 
						WHERE
							a.status_plano_loja = 'S' AND 
							(
								a.nome_plano_loja LIKE :search OR
								a.porcentagem_plano_loja LIKE :search OR
								b.nome_loja LIKE :search OR 
								c.cpf_usuario LIKE :search 
							)
						ORDER BY 
							a.id_loja ASC,
							a.id_plano_loja DESC
						LIMIT 
							:length OFFSET :start
					", [
						":search" => "%".$search."%", 
						":length" => $length, 
						":start" => $start
					]);

					$n = ($page*$length)-$length + 1;

					foreach ($result->fetchAll() as $data):

				?>

					<tr>
						<td class="align-middle text-left">
							<?php 

								echo "
									{$data->nome_usuario}<br>
									<small>{$data->cpf_usuario}</small><br>
									<small>{$data->email_usuario} | {$data->telefone_usuario}</small>
								"; 

							?>	
						</td>
						<td class="align-middle text-left"><?php echo $data->nome_plano_loja; ?></td>
						<td class="align-middle text-center"><?php echo floatval($data->porcentagem_plano_loja)."%"; ?></td>
						<td class="align-middle text-center"><?php echo floatval($data->porcentagem_cashback)."%"; ?></td>
						<td class="align-middle text-center"><?php echo floatval($data->porcentagem_comissao)."%"; ?></td>
						<td class="align-middle text-center">
							<div class="d-inline-flex">
								<div class="mx-auto">
									<button type="button" class="btn btn-info btn-square btn-ver-mais" data-value="<?php echo encrypt_encode($data->id_plano_loja); ?>" data-toggle="tooltip" data-placement="bottom" title="Ver Detalhes">
										<i class="fa-regular fa-search-plus"></i>
									</button>
								</div>

								<div class="mx-2">
									<form action="<?php echo show_link("/edita-plano-loja/"); ?>" method="post">
										<input type="hidden" name="id_plano_loja" class="d-none" value="<?php echo encrypt_encode($data->id_plano_loja); ?>">
										<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>
								</div>
							
								<div class="mx-auto">
									<button type="button" class="btn btn-danger btn-square btn-excluir" data-value="<?php echo encrypt_encode($data->id_plano_loja); ?>" data-toggle="tooltip" data-placement="bottom" title="Excluir">
										<i class="fa-regular fa-trash-alt"></i>
									</button>
								</div>
							</div>
						</td>
					</tr>	
				<?php endforeach; ?>
			</tbody>
		</table>
	</div>

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

			$result = $model->query("
				SELECT * FROM plano_loja a
				INNER JOIN loja b ON (a.id_loja = b.id_loja) 
				INNER JOIN usuario c ON (b.id_usuario = c.id_usuario) 
				WHERE
					a.status_plano_loja = 'S' AND 
					(
						a.nome_plano_loja LIKE :search OR
						a.porcentagem_plano_loja LIKE :search OR
						b.nome_loja LIKE :search OR 
						c.cpf_usuario LIKE :search 
					)
			", [
				":search" => "%".$search."%"
			]);

			$total  = $result->rowCount();

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

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

			if ($page < $total_page) {	
				echo '<li class="page-item"><a href="?'.(!empty($search) ? "pesquisa=".$search."&" : "").'pag='.($page+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 topico -->
<div class="modal fade" id="modal-mudar-excluir-plano-loja" 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>
					Tem certeza que deseja <strong class='text-danger'>EXCLUIR</strong> esse Plano?
				</p>
			</div>
			<div class="modal-footer">
				<form action="<?php echo show_link("/excluir-plano-loja/"); ?>" method="post">
					<input type="hidden" name="id_plano_loja" id="input-plano-loja-id" 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_loja="+id,
			url: "<?php echo show_link("/obter-niveis-loja/"); ?>",
			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_loja}</th>
							</tr>
							<tr>
								<td class="align-middle" colspan="2">${data[i].porcentagem_nivel_loja.replace(".", ",")}%</th>
							</tr>
						`;
					}
					else {
						html += `
							<tr>
								<th class="align-middle">${data[i].nome_nivel_loja}</th>
								<th class="align-middle">${data[i+1].nome_nivel_loja}</th>
							</tr>
							<tr>
								<td class="align-middle">${data[i].porcentagem_nivel_loja.replace(".", ",")}%</th>
								<td class="align-middle">${data[i+1].porcentagem_nivel_loja.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 níveis!",
					icon: "error",
					loader: true
				});
			}
		}, function(error){
			console.log("Erro: "+error);
		});
	});


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

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

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