<?php
    session_start();
	ob_start();

	$id_users = isset($_SESSION['id_users']) ? $_SESSION['id_users']: "";	
	$nome_user = isset($_SESSION['nome']) ? $_SESSION['nome']: "";	
	$email_users = isset($_SESSION['email']) ? $_SESSION['email']: "";	
	$pass_users = isset($_SESSION['pass']) ? $_SESSION['pass']: "";	
	$logado = isset($_SESSION['logado']) ? $_SESSION['logado']: "N";	

	if ($logado == "N" && $id_users == ""){	    
		echo  "<script type='text/javascript'>
					location.href='login.php'
				</script>";	
		exit();
	}

	require 'conexion.php';
	require_once('functions.php');
	
    if(isset($_GET['route'])) { $route = $_GET['route']; } else { $route = '2'; }
    if(isset($_GET['filter'])) { $filter = $_GET['filter']; } else { $filter = '1'; }
    if(isset($_GET['id'])) { $id = $_GET['id']; } else { $id = ''; }
	

	$sql = "SELECT
			pedidos.*,
			somagerala,
			somageralb,
			somagerald,			
			producao.*,	
			ordem_corte.*,
			producao.*,DATE_FORMAT(producao.producao_inicio, '%d/%m/%Y %H:%i:%s') AS producao_inicio, DATE_FORMAT(producao.producao_fim, '%d/%m/%Y %H:%i:%s') AS producao_fim,
			companies.popular_name
			FROM
				ordem_corte
			INNER JOIN pedidos ON pedidos.id = ordem_corte.id_pedido
			INNER JOIN companies ON pedidos.nr_company = companies.id
			INNER JOIN producao ON ordem_corte.id_oc = producao.id_oc
			INNER JOIN grade ON pedidos.id = grade.id_pedido
			GROUP BY ordem_corte.id_oc";	
		
    $resultado = $mysqli->query($sql);
	$row = $resultado->fetch_array(MYSQLI_ASSOC);
	
	$qtd = 0;
	$setor = "";							
	
	include(HEADER_TEMPLATE);

?>
			<div class="container-fluid">
			
			<div class="row">
				<div class="col-sm-9" style="background-color:WhiteSmoke;">
					<table id="mitabla" class="table table-hover table-bordered">
						<thead>
							<tr>
								<th>OC</th>
								<th>Cliente</th>                        
								<th>Pedido do Cliente</th>
								<th>M</th>
								<th>R</th>
								<th></th>		
								<th></th>										
								<th></th>								
							</tr>
						</thead>
						
						<tbody>
								<?php 
								$resultado = $mysqli->query($sql);
								while($row = $resultado->fetch_array(MYSQLI_ASSOC)) { ?>
									<tr>
										<td width="5%"><?php echo $row['id_oc']; ?></td>
										<td><?php echo substr($row['popular_name'],0,10); ?></td>
										<td width="50%"><?php echo $row['nr_pedido']; ?></td>
										<?php
											$prodInicio = (int)$row['producao_inicio'];
											$prodFim = (int)$row['producao_fim'];
											$idProd = (int)$row['id_producao'];
											$totalzao = (int)$row['somagerala'];

										?>
										<td width="5%"><?php echo $totalzao; ?></td>										
										<td><?php echo $row['somagerald']; ?></td>										

										<?php
											switch ($row['producao_fim'] and $row['producao_inicio']) {
													case ($row['producao_fim'] == '00/00/0000 00:00:00') :
												?>
												<td align="center"><button type="button" class="btn btn-xs btn-warning" data-toggle="modal" data-target="#exampleModal" data-whatever="<?php echo $idProd; ?>" data-whatevernome="<?php echo $setor; ?>"data-whateverdetalhes="<?php echo $qtd; ?>" data-whateverdetalhestotalzao="<?php echo $totalzao; ?>">APT</button></td>
												<?php                                    
													break;
													case ((int)$row['producao_fim'] > 0) :
												?>
												<td align="center"><a href="#" span class="glyphicon glyphicon-ok" disabled></span></a></td>											

												<?php                                    
													break;
													default:
												?>
														<td><a<button type="button" class="btn btn-xs btn-danger disabled">**ERRO**</button></a></td>
												<?php
											}
										?>

										<?php 
											$sqlAcabamento = "select setor FROM apontamentos WHERE id_producao = '$idProd' AND setor = '13 - ACABAMENTO'";
											$resultadoAcabamento = $mysqli->query($sqlAcabamento);
											$data = $resultadoAcabamento->fetch_assoc();
											$somagerald = $row['somagerald'];
										?>
											
										<?php
											IF ($data) :
										?>
											<?php                                    
												IF ( $somagerald >= $totalzao) {
											?>										
												<td align="center"><a href="#" span class="glyphicon glyphicon-saved"></span></a></td>											

											<?php
												} ELSE {
											?>												
												<td align="center"><a href="producao_fim.php?id=<?php echo $row['id']; ?>&route=2&producaoID=0" data-toggle="tooltip" data-placement="top" title="Entra dados grade finalização" span class="glyphicon glyphicon-retweet"></span></a></td>											
											<?php
												}
											?>										
										<?php                                    
											ELSE :
										?>
											<td align="center"><button type="button" class="btn btn-xs btn-defalut" data-toggle="tooltip" data-placement="top" title="Para liberar Grade Fim, deve-se apontar dados no setor 13-ACABAMENTO" >Falta Grade Fim</button></td>										
										<?php
											ENDIF ;
										?>
										<td align="center"><a href="apontamento_index.php?id=<?php echo $idProd; ?>&route=1&filter=1" data-toggle="tooltip" data-placement="top" title="visualizar no quadro ao lado os detalhes dos apontamentos realizados" <span class="glyphicon glyphicon-eye-open"></span></a></td>
									</tr>
								<?php } ?>

						</tbody>
					</table>
					
				</div>
				<div class="col-sm-3" style="">
					<?php 
						$id = $_GET['id']; 
						$sqlOC = "select producao.id_oc, ordem_corte.id_pedido FROM producao INNER JOIN ordem_corte ON ordem_corte.id_oc =  producao.id_oc WHERE id_producao = '$id'";
						$res = $mysqli->query($sqlOC);
						$rowoc = $res->fetch_array(MYSQLI_ASSOC);
						$ocNR = $rowoc['id_oc'];
						$idPed = $rowoc['id_pedido'];
					?>
					<div class="container-fluid" style="text-align:center">
						<div class="row"> 	
							<div class="panel panel-default" style="text-align:center">
							<div class="panel-heading">
								<td align="right"><a href="apontamento_index.php?id=<?php echo $id; ?>&filter=1&route=1" <button type="button" class="btn btn-xs btn-primary" >Apontamentos</button></a></td>
								<td align="center"><a href="apontamento_index.php?id=<?php echo $id; ?>&filter=2&route=1" <button type="button" class="btn btn-xs btn-primary" >Filtro por Setor</button></a></td>
								<td align="left"><a href="apontamento_index.php?id=<?php echo $id; ?>&filter=3&route=1" <button type="button" class="btn btn-xs btn-primary" >Totalização por Setor</button></a></td>
								<h4 style="text-align:center">O.C.: <?php echo $ocNR; ?> <a href="all2_view.php?id=<?php echo $idPed; ?>&view=apontamento2" <span class="glyphicon glyphicon-sunglasses"></span></a></h4>																																	
							</div>
								
							</div>					
						</div>
					</div>						
					<table id="mitabla" class="table table-condensed table-bordered">
						<thead>
							<tr>
								<th>ID</th>
								<th>Registro</th>                        
								<th>Setor</th>
								<th>QTD</th>
								<th>Obs</th>
								<th></th>

							</tr>
						</thead>
						
						<tbody>
								<?php 
								IF ($route == 1) {
									$id = $_GET['id'];
									$filter = $_GET['filter'];
									
									switch ( $filter ) {
										CASE ( $filter == '1' ) :
											$apontamento = "SELECT apontamentos.*, DATE_FORMAT(apontamentos.registro, '%d/%m/%Y %H:%i:%s') AS registro, producao.producao_fim FROM apontamentos INNER JOIN producao ON apontamentos.id_producao = producao.id_producao WHERE apontamentos.id_producao = '$id'  AND apontamentos.ativo = '1' ORDER by apontamentos.idApontamento DESC";
									    BREAK;
										CASE ( $filter == '2' ) :
											$apontamento = "SELECT apontamentos.*, DATE_FORMAT(apontamentos.registro, '%d/%m/%Y %H:%i:%s') AS registro, producao.producao_fim FROM apontamentos INNER JOIN producao ON apontamentos.id_producao = producao.id_producao WHERE apontamentos.id_producao = '$id' AND apontamentos.ativo = '1' ORDER by apontamentos.setor ASC ";
									    BREAK;
										CASE ( $filter == '3' ) :
											$apontamento = "SELECT apontamentos.*, DATE_FORMAT(apontamentos.registro, '%d/%m/%Y %H:%i:%s') AS registro, producao.producao_fim, SUM(apontamentos.qtd) as qtd FROM apontamentos INNER JOIN producao ON apontamentos.id_producao = producao.id_producao WHERE apontamentos.id_producao = '$id' AND apontamentos.ativo = '1' GROUP BY apontamentos.setor ORDER by apontamentos.setor ASC";
										DEFAULT:
									}
								} ELSE {
									$apontamento = "SELECT * FROM apontamentos WHERE ativo = '3'";													
								}
								
								$resultado = $mysqli->query($apontamento);
								while($row = $resultado->fetch_array(MYSQLI_ASSOC)) { ?>
									<tr>
										<td><?php echo $row['idApontamento']; ?></td>
										<td><?php echo $row['registro']; ?></td>
										<td align="center"><?php echo substr($row['setor'],0,2); ?></td>
										<td align="right"><?php echo $row['qtd']; ?></td>
										<td><?php echo $row['obs']; ?></td>	
										
										<?php IF ( $filter == '1' && ($row['producao_fim'] == '0000-00-00 00:00:00') ) { ?>
											<td><a href="apontamento_eliminar.php?idApontamento=<?php echo $row['idApontamento']; ?>&&idProd=<?php echo $id; ?>" data-toggle="tooltip" data-placement="right" title="Remover"><span class="glyphicon glyphicon-remove-sign"></span></a></td>
										<?php } ELSE { ?>
											<td><span class="glyphicon glyphicon-ban-circle" disabled></span></td>	
										<?php } ?>											
									</tr>
								<?php } ?>

						</tbody>
					</table>

				</div>			
								
					
			</div>

			
			
			
			
            <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
                <div class="modal-dialog modal-sm" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="exampleModalLabel">Apontamento de Produção</h4>
                            </div>
                        <div class="modal-body">
                            <form method="POST" action="apontamento_modal.php" enctype="multipart/form-data">

								<input name="idProd" type="hidden" class="form-control" id="idProd" value="">
								<input name="totalzao" type="hidden" class="form-control" id="totalzao" value="">
								
								<div class="form-group">
									<label for="message-text" class="control-label">setor:
									<input name="setor" type="hidden" class="form-control" id="setor" value="<?php echo $nome_user; ?>">
									<input type="text" class="form-control" id="setor" name="setor" value="<?php echo $nome_user; ?>">					
									
								</div>
                                <div class="form-group">
                                    <label for="message-text" class="control-label">Quantidade:</label>
									<input type="text" class="form-control" onkeyup="somenteNumeros(this);" maxlength="4" id="qtd" name="qtd" required>					
								</div>
                                <div class="form-group">
                                    <label for="message-text" class="control-label">Observações:</label>
									<textarea  rows="2" class="form-control" cols="50" id="obs" name="obs" style='text-transform:uppercase'0></textarea>					
								</div>
								
								<br>
                                <button type="submit" class="btn btn-success">REGISTRA</button>                            
                                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancela</button>

                            </form>

                        </div>
                      
                    </div>
                </div>
            </div>

            <?php include(FOOTER_TEMPLATE); ?>      

<script type="text/javascript">
    $('#exampleModal').on('show.bs.modal', function (event) {
      var button = $(event.relatedTarget) // Button that triggered the modal
      var recipient = button.data('whatever') // Extract info from data-* attributes
      var recipientnome = button.data('whatevernome')
      var recipientdetalhes = button.data('whateverdetalhes')
      var recipientdetalhestotalzao = button.data('whateverdetalhestotalzao')	  
	  
      // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
      // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
      var modal = $(this)
      modal.find('.modal-title').text('Produção Nr: ' + recipient)
      modal.find('#idProd').val(recipient)
      modal.find('#setor').val(recipientnome)
      modal.find('#qtd').val(recipientdetalhes)
      modal.find('#totalzao').val(recipientdetalhestotalzao)
      modal.find('#obs')
    })
</script>      
 <script>
    function somenteNumeros(num) {
        var er = /[^0-9.]/;
        er.lastIndex = 0;
        var campo = num;
        if (er.test(campo.value)) {
          campo.value = "";
        }
    }
 </script>
 	<script type="text/javascript">		
		$(document).ready(function() {
			$('#mitabla').DataTable( {
				"order": [[0, "desc"]],
						"language":{
							"lengthMenu": "Mostrar _MENU_ registros por página",
							"info": "Mostrando pagina _PAGE_ de _PAGES_",
							"infoEmpty": "Sem registros para serem mostrados",
							"infoFiltered": "(filtrada de _MAX_ registros)",
							"loadingRecords": "Lendo...",
							"processing":     "Procesando...",
							"search": "Buscar:",
							"zeroRecords":    "Não se encontra registros com esta caracterísica",
							"paginate": {
								"next":       ">>",
								"previous":   "<<"
						}},                  
			"columnDefs": [

				{
					"targets": [ 0 ],
					"visible": true,
					"searchable": true
				}
				]
			} );
		} );
		</script>	
