<?php 
    @$msg = $_GET['msg'];
	require_once("vendor/autoload.php");
	require_once('./constantes.php');
	$pedidos = new \App\Models\Pedidos();
	$getAllUsers = $pedidos->getAllUsersActive();

	$pagina = @$_GET['pagina'];
	$limite = 100;

	if(empty($pagina)){
		$pagina = 1;
	}

	$inicio = (intval($pagina) - 1) * $limite;

	$getAllPedidos   = $pedidos->getAllPedidos($inicio, $limite);
	
	$countPedidos    = count($pedidos->getAllPedidos('', ''));

	$ultima          = ceil($countPedidos / $limite);

	?>
<style>
	.bd-placeholder-img {
		font-size: 1.125rem;
		text-anchor: middle;
		-webkit-user-select: none;
		-moz-user-select: none;
		-ms-user-select: none;
		user-select: none;
	}
	@media (min-width: 768px) {
		.bd-placeholder-img-lg {
			font-size: 3.5rem;
		}
	}
	.list-group-horizontal{-ms-flex-direction: row;flex-direction: row;}
	.list-group-item{ padding: .4rem 0rem; }
	.list-group-item a{ padding: .75rem 1.25rem; } 
	.disabled {cursor: not-allowed;}
	.table-hover tbody tr:hover {
		background-color: rgba(0,0,0,.075) !important;
	}
		.table td, .table th {
		font-size: 11px !important;
	    height: auto !important;
	}
	.btn {
		padding: .1rem 1.8rem !important;
		font-size: 12px !important;
	}
	.form-control {
			font-size: 12px;
			border-color: #ebedf2;
			padding: 2px 5px;
			height: inherit!important;
		}
</style>

<!-- MOVE O CURSO DO MENU -->

<script> window.onload = function(e){ $('.nav-item').removeClass('active'); $('#pedido').addClass('active'); } </script>

<!-- MOVE O CURSO DO MENU -->

<div class="page-inner">
	<div class="page-header">
		<h4 class="page-title">Pedidos</h4>
		<ul class="breadcrumbs">
			<li class="nav-home">
				<a href="#">
					<i class="flaticon-home"></i>
				</a>
			</li>
			<li class="separator">
				<i class="flaticon-right-arrow"></i>
			</li>
			<li class="nav-item">
				<a href="#">Pedidos</a>
			</li>
		</ul> 
	</div>
	<div class="row">
		<div class="col-md-12">
			<?php include './inc/alerts.php';?>
		</div>
	</div>
	<div class="row" style="padding-top: 5px; padding-bottom: 5px;">
		<div class="col-md-6">
			<button type="button" onclick="" name="btt1PED" id="btt1PED" class="btn btn-secondary btt disabled" >Exportar</button>
			<button type="button" onclick="window.location.reload();" name="btt0PED" id="btt0PED" class="btn btn-secondary" >Atualizar</button>
			<button type="button" onclick="atualizarPED();" name="btt0PED" id="btt0PED" class="btn btn-secondary" >Pedidos Atualizar COD</button>
			<!--<button type="button" onclick="envioPEDmanual();" target="_blank" class="btn btn-info" >Manual</button>-->
		</div>
		<div class="col-md-6">
			<button type="button" onclick="" name="btt2PED" id="btt2PED" class="btn btn-secondary btt disabled" style="float: right; margin-left: 3px" >Excluir</button>
			<button type="button" onclick=""  name="btt3PED" id="btt3PED" class="btn btn-secondary btt disabled" style="float: right; margin-left: 3px"  >Alterar</button>
			<button type="button" onclick=""  name="btt4PED" id="btt4PED" class="btn btn-secondary btt disabled" style="float: right; margin-left: 3px"  >Envio Separação</button>
		</div>
	</div>		
	<div class="row">
	<div>
		<div class="col-md-12" style="display: flex;align-items: center;gap: 10px;">
			<?php
				if($pagina > 1){
					?>
						<button class="btn btn-info" onclick="pagination(1)">Primeira</button>
						<button class="btn btn-info" onclick="pagination('-')"><</button>
					<?php
				}
				if($pagina < $ultima){
					?>
						<button class="btn btn-info" onclick="pagination('+')">></button>
						<button class="btn btn-info" onclick="pagination(<?= $ultima ?>)">Última</button>
					<?php
				}
			?>
		</div>
	</div>
		<div class="col-md-12">
			
			<div class="card">
				<div class="card-body">
				
					<div class="table-responsive">
						<table id="example2" class="table table-bordered table-head-bg-default">
							<thead>
								<tr>
									<th></th>
									<th>Código</th>
									<th>Loja</th>
									<th>Data</th>
									<th style="text-align: center;width: 80px;">Status</th>
									<th>Usuário</th>
									<th>Operador</th>
									<th>Pedido</th>
									<th>NF</th>
								</tr>
							</thead>
							<tbody>
								<?php
								function mscolor($st1){
									switch($st1){
										case 'CONCLUIDO':
											echo "background-color: #cfd3f7;";
											break;
										case 'EXPORTADO':
											echo "background-color: #b9ffd4;";
											break;
										case 'PENDENTE':
											echo "background-color: #fbb1b1;";	
											break;
										case 'SEPARAÇÃO':
											echo "background-color: #ffd892;";
											break;
										default:
											echo "background-color: #fff;";
											break;
									}
									
								}
									$contador = 1;
									if(!empty($getAllPedidos)){
										foreach ($getAllPedidos as $key => $lista) {
								?>
								<tr style="font-weight: bold;color: #000;height: 40px; <?php echo mscolor($lista['status']); ; ?>">
									<td><input type='checkbox' class='checkclass' id='two<?= $lista['id'];?>' data-status="<?= $lista['status'] ?>" onchange="libDisabled3('<?= $lista['status'];?>', <?= $lista['id'];?>);"  name='checks2[]' value='two<?= $lista['id'];?>'/></td>
									<td><?= $lista['id'];?></td>
									<td><?php echo $pedidos->getLoja($lista['loja']); ?></td>
									<td><?= date("d-m-Y H:i:s", strtotime($lista['data']));?></td>
									<td><?= $lista['status'];?></td>
									<td><?php echo $pedidos->getUser($lista['usuario']); ?></td>
									<td><?php echo $pedidos->getUserOP($lista['gerador']); ?></td>
									<?php 
										$response = $pedidos->getSFOPED($lista['id']);
										$nome = "";
										$nf   = "";
										if(!empty($response)){
											foreach ($response as $key => $l) {
												$nome .= $l['sofcon_pedido'].",";
												$nf   .= $l['sofcon_nf'].",";
											}
										}else{
											$nome = "0";
											$nf = "0";
										}
									?>
									<td><?= $nome ;?></td>
									<td><?= $nf   ;?></td>
								</tr>
								<?php $contador++;}}?>
							</tbody>
						</table>
					</div>
					
				</div>
			</div>
			
		</div>
	</div>
	
	
	<div class="row" style="padding-top: 5px; padding-bottom: 5px;">
		<div class="col-md-6">
		</div>
		<div class="col-md-6">
			<button type="button" onclick="alert('O Pedido já foi exportado, não pode ser alterado!');" name="btt2ITEM" id="btt2ITEM" class="btn btn-secondary btt disabled" style="float: right; margin-left: 3px" >Excluir</button>
		</div>
	</div>	
	<div class="row">
		<div class="col-lg-12">
			<div class="table-responsive">
				<div style="overflow-x:auto;" id="ts" >
					<table id="example" class="table table-bordered table-hover" style="background:#FFF; margin:0 !important;width: 100%;">
						<thead  class="thead-dark">
							<tr>
								<th></th>
								<th style="text-align:center;">COD</th>
								<th style="text-align:center;">REF</th>
								<th style="text-align:center;">DESCRIÇÂO</th>
								<th style="text-align:center;">SUGESTÂO</th>
								<th style="text-align:center;">SEPARADO</th>
								<th style="text-align:center;">DEPOSITO</th>
							</tr>
						</thead>
						<tbody id="ResultX"></tbody>
						<tfoot class="text-center">
							<tr>
							  <td colspan="7" ><span id="meupedidoid" ></span></td>
							</tr>
						</tfoot>
					</table>
				</div>
			</div>
		</div>
	</div>
	<div class="row" style="display: flex;align-items: center;gap: 10px;">
		<div class="col-md-12">
			<?php
				if($pagina > 1){
					?>
						<button class="btn btn-info" onclick="pagination(1)">Primeira</button>
						<button class="btn btn-info" onclick="pagination('-')"><</button>
					<?php
				}
				if($pagina < $ultima){
					?>
						<button class="btn btn-info" onclick="pagination('+')">></button>
						<button class="btn btn-info" onclick="pagination(<?= $ultima ?>)">Última</button>
					<?php
				}
			?>
		</div>
	</div>
	<script type="text/javascript">
	    function pagination(parameter){
	        let page       = 0;
	        let search_arr = [];

	        if(location.search){
	            const search     = location.search.split("?")[1];
	            
	            search_arr = search.split("&");

	            search_arr.forEach(query=>{
	                const query_arr = query.split("=");
	                if(query_arr[0] == "pagina"){
	                    page = query_arr[1];
	                }
	            });
	        }

	        switch (parameter) {
	            case "+":
	                page++;
	                break;

	            case "-":
	                page--;
	                break;
	        
	            default:
	                page = parameter;
	                break;
	        }

	        if(page <= 0){
	            page = 1;
	        }

	        let new_query = `pagina=${page}`;

	        if(location.search){
	            search_arr.forEach(query=>{
	                const index = search_arr.indexOf(query);
	                const query_arr = query.split("=");

	                if(query_arr[0] == "pagina"){
	                    search_arr[index] = new_query;
	                }
	            });
	        } else {
	            search_arr = [`pagina=${page}`];
	        }

	        let new_search = `?${search_arr.join("&")}`;

	        if(new_search.indexOf("pagina") < 0){
	            page = 2;

	            new_query = `pagina=${page}`;

	            const new_search_arr = new_search.split("?")[1].split("&");

	            new_search = `?${new_query}&${new_search_arr.join("&")}`;
	        }

	        location.search = new_search;
	    }
	</script>
</div>

    <div class="modal fade" id="modalStatus" tabindex="-1" role="dialog" aria-labelledby="modalEdtdms" aria-hidden="true">
		 <div class="modal-dialog">
			  <div class="modal-content">
				  <div class="modal-header">
					<h5 class="modal-title" id="modalEdtdms">Observação da Página</h5>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					  <span aria-hidden="true">&times;</span>
					</button>
				  </div>
				  <div class="modal-body">
					<p style="font-size: 12px;padding-top: 2px;"><b>Para alterar basta dá duplo click na sugestão que deseja.</b><br> <i class="fa fa-square" aria-hidden="true" style='color: #ed8080; width: 8px; height: 8px; display: inline-block;' ></i> Vermelho: Sujestão maior que a quantidade da loja matriz. <br> <i class="fa fa-square" aria-hidden="true" style='color: #f7c44f; width: 8px; height: 8px; display: inline-block;'></i> Amarelo: Sujestão igual a quantidade da loja matriz.</p>
				  </div>
			  </div>
		 </div>
    </div>
	<style>
	    .bootstrap-select.form-control {
			border: 1px solid #90939a;
		}
	</style>
    <div class="modal fade" id="modalSeparacao" tabindex="-1" role="dialog" aria-labelledby="modalSeparacao" aria-hidden="true">
		 <div class="modal-dialog">
			  <div class="modal-content">
				  <div class="modal-header">
					<h5 class="modal-title" id="modalSeparacao">Envio para Separação</h5>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					  <span aria-hidden="true">&times;</span>
					</button>
				  </div>
				  <div class="modal-body">
						<div class="row">
							<div class="col-md-12">
								<label>Selecione usuário para separação</label>
								<hr>
								<select name="usuario" id="usuario" class="form-control" required >
										<option value="" disabled selected>::- Selecione Usuário -::</option>
									<?php 
										foreach ($getAllUsers as $key => $lista) {
									?>
										<option value="<?= $lista['id'];?>"><?= $lista['nome'];?></option>
									<?php }?>
								</select>														
							</div>
						</div>
						<div class="row" style="margin-top: 10px;">
							<div class="col-md-12">
							
								<button type="button" onclick="envioPED();" class="btn btn-secondary btn-block btt" style="margin-top: 5px"  >Envio Separação</button>
							
						    </div>
						</div>
				  </div>
			  </div>
		 </div>
    </div>



<!-- inclusao do footer -->
<?php
		$jspage  = "<script src='utils/js/acoes_analise_pedidos.js'></script>";
		$jspage .= "<script src='./assets/js/dataTables.buttons.min.js'></script>";
		$jspage .= "<script src='./assets/js/jszip.min.js'></script>";
		$jspage .= "<script src='./assets/js/pdfmake.min.js'></script>";
		$jspage .= "<script src='./assets/js/vfs_fonts.js'></script>";
		$jspage .= "<script src='./assets/js/buttons.html5.min.js'></script>";
		$jspage .= "<script>";
		$jspage .= "	$(document).ready(function() {";
		
		
		$jspage .= "				var dtini  = $('#dtini').val();";
		$jspage .= "				var dtfim  = $('#dtfim').val();";
		$jspage .= "				var temp = $('#dtini').val().split('/');";
		$jspage .= "				var d1     = new Date(temp[2], temp[1]-1,temp[0]);";
		$jspage .= "				var temp = $('#dtfim').val().split('/');";
		$jspage .= "				var d2     = new Date(temp[2], temp[1]-1,temp[0]);";
		
		$jspage .= " console.log(dtini)				";
		
		$jspage .= "				$(\"[data-toggle2='tooltip']\").tooltip();";
		$jspage .= "				$(\"#example2\").DataTable( {";
		$jspage .= "					'pageLength': 25,";
		$jspage .= "					'order': [[ 1, 'desc' ]],";
		$jspage .= "					'pagingType': 'full_numbers',";
		$jspage .= "					'language': {";
		$jspage .= "						'lengthMenu': 'Exibição _MENU_ registros por página',";
		$jspage .= "						'zeroRecords': 'Nada encontrado - desculpe',";
		$jspage .= "						'info': 'Mostrando página _PAGE_ de _PAGES_ | _TOTAL_ Pedidos',";
		$jspage .= "						'infoEmpty': 'Não há registros acessível',";
		$jspage .= "						'infoFiltered': '(filtrado de _MAX_ total registros)',";
		$jspage .= "							'sSearch':       	'Procurar',";
		$jspage .= "						'sEmptyTable': 'Nenhum dado disponível na tabela', ";
		$jspage .= "						'sLoadingRecords':'Carregando...',";
		$jspage .= "						'sProcessing':'Aguarde...', ";
		$jspage .= "						'sZeroRecords':'Nenhuma entrada.', ";
		$jspage .= "					'oPaginate': {";
		$jspage .= "							'sFirst':    	'Primeira',";
		$jspage .= "							'sPrevious': 	'Voltar',";
		$jspage .= "							'sNext':     	'Próximo',";
		$jspage .= "							'sLast':     	'Último'";
		$jspage .= "						}";
		$jspage .= "					}";
		$jspage .= "				} );";
		$jspage .= "				let msg = localStorage.getItem('msg');";
		$jspage .= "				if(msg == 'ativa'){";
		$jspage .= "					func(localStorage.getItem('status'),localStorage.getItem('texto'));";
		$jspage .= "				}";
		
		/*
		if($temSeparados != 0){
			$jspage .= "	var arrr = JSON.parse(".$result.");";		
			$jspage .= "	var pedidos = arrr[1];";		
			$jspage .= "	var analise = arrr[0];";		
			$jspage .= "	if(pedidos != 0){";	
			$jspage .= "	atualizarOFF(pedidos,analise);";		
			$jspage .= "	}";		
		}*/
		
		/*
		$jspage .= "	var p = ".$getAllPedidosSP.";";		
		$jspage .= "	if(p != false){";
		
		$jspage .= "$.ajax({";
		$jspage .= "			type: 'POST',";
		$jspage .= "            contentType: 'application/json',";
        $jspage .= "            cache: false,";
		$jspage .= "			dataType: 'json',";
		$jspage .= "			url: 'https://conect.agenciadp.com.br/response_api_integra20.php',";
		$jspage .= "			data: {cod: 'ENVIO', pedidos: JSON.stringify(".$getAllPedidosSP."), analise: JSON.stringify(".$getAllAnaliseSP.")},";
		$jspage .= "			success: function(data){";
		$jspage .= "				console.log('Enviado com Sucesso '+data);";
		$jspage .= "			},";
		$jspage .= "			error: function(){";
		$jspage .= "				console.log('Não Foi Possivel Enviar!');";
		$jspage .= "			}";
		$jspage .= "		});";	
		
		$jspage .= "		}";	*/
		
		$jspage .= "			});";
		$jspage .= "		</script>";
		
?>

