<?php session_start();
//Invocamos el archivo de conexión
require ("conexion.php");
$sql = mysqli_query($enlace,"SELECT usuario_nombre FROM usuarios");//Este es el script SQL que necesitas para jalar el ultimo registro
$today = date("Y-m-d");
$Perfil=$_SESSION['Perfil'];


if (isset($_SESSION['usuario_nombre'])) {
	 if ($Perfil==1 or $Perfil==2 or $Perfil==3 or $Perfil==4){
	 
    $OK = true;

    
?>

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8" />
<title>Indicadores de Cumplimiento</title>
</head> 
<h1>Indicadores de Produccion a la fecha <?php echo $today; ?></h1>
<p><a href="index.php">&lt;&lt; Regresar</a></p>
<form name="Formulariodefechas" method="post">
	<p> Reporte de Indicadores </p>
		<br/>
			<li>
			<label for="Responsable">Responsable:</label>
            <input type="text" name="Responsable" / placeholder="Responsable" list="Responsable" required />
            <datalist id="Responsable">
            <option value="Pintura">
            <option value="Remanufactura">
			</li>
			<li>
			<label for="FechaInicial">Fecha Inicial:</label>
			<input type="date" name="FechaInicial" required />
			</li>
			<li>
			<label for="FechaFinal">Fecha Final:</label>
			<input type="date" name="FechaFinal" required />
			</li>
			<li>
			<input type="submit" name="Consultar" value="Consultar"/>
			</li>
</form>

<?php

if (array_key_exists('Consultar', $_POST)) {
		$Responsable=$_POST["Responsable"];	
		$FechaInicial=$_POST["FechaInicial"];
		$FechaFinal=$_POST["FechaFinal"];
		$OK = (array($_POST["FechaInicial"], $_POST['FechaFinal']));
	    
        if (!$OK) {
            echo $error[2];
        } else {
           
           $meter = mysqli_query($enlace,"Select DISTINCT Responsable,
															(Select Count(pedido) from UnicuadroFechas2 where Fecha_EA_Pintura between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable' and Fecha_EA_Pintura IS NOT NULL) as TraArea,
															(Select Count(pedido) from UnicuadroFechas2 where Fecha_EA_Pintura between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable' and Fecha_EA_Almacen<=Fecha_EA_Pintura and Fecha_EA_Almacen IS NOT NULL) as TraEntTiempo,
															(Select Count(pedido) from UnicuadroFechas2 where Fecha_EA_Pintura between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable' and Fecha_EA_Almacen>Fecha_EA_Pintura and Fecha_EA_Almacen IS NOT NULL) as TraEntDestiempo,
															(Select Count(pedido) from UnicuadroFechas2 where Fecha_EA_Pintura between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable' and Fecha_EA_Almacen IS NULL) as TraSinCerrar,
															((Select Count(pedido) from UnicuadroFechas2 where Fecha_EA_Pintura between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable' and Fecha_EA_Almacen<=Fecha_EA_Pintura and Fecha_EA_Almacen IS NOT NULL)*100/(Select Count(pedido) from UnicuadroFechas2 where Fecha_EA_Pintura between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable' )) as Cumplimiento,
															((Select Count(pedido) from UnicuadroFechas2 where Fecha_EA_Pintura between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable' and Fecha_EA_Almacen>Fecha_EA_Pintura and Fecha_EA_Almacen IS NOT NULL)*100/(Select Count(pedido) from UnicuadroFechas2 where Fecha_EA_Pintura between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable' )) as Incumplimiento
															From UnicuadroFechas2 where (FechaCreacionPedido between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable') ");
			 $meter1 = mysqli_query($enlace," SELECT  DISTINCT Responsable,
															count(distinct pedidop) as TotalT,
        													(select count(pedidop) from reprogramadas where Fecha_EA_p between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable' and TimeStap<>FechaModificacion and Fecha_EA_p > Fecha_EA_cp) as Retrasadas,
        													(select count(pedidop) from reprogramadas where Fecha_EA_p between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable' and TimeStap<>FechaModificacion and Fecha_EA_p <= Fecha_EA_cp) as Anticipadas,
        													((select count(pedidop) from reprogramadas where Fecha_EA_p between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable' and	 TimeStap<>FechaModificacion)*100/(count(distinct pedidop))) as PorReporgramadas
															FROM reprogramadas where Fecha_EA_p between ('$FechaInicial') and ('$FechaFinal') and Responsable='$Responsable'");
			 $meter2 = mysqli_query($enlace," SELECT SUM(TIMESTAMPDIFF(DAY, p.TimeStap, pr.TimeStap)) as Diferencia, count(p.Pedido) as Pedidos,(SUM(TIMESTAMPDIFF(DAY, p.TimeStap, pr.TimeStap)) div count(p.Pedido)) as Promedio
															FROM planeacion as p inner join produccion as pr 
																on p.Pedido=pr.Pedido
															where pr.Fecha_EA between ('2014-10-01') and ('2014-11-01') and Responsable='Remanufactura' and (TIMESTAMPDIFF(MINUTE, p.TimeStap, pr.TimeStap))>0");
														
	
			
			        		 if($meter){
																			  
						 			  //echo 'He modificado la Recepcion del Pedido Numero '.$pedido.'. ';
										echo "<table border='1' align='center'>";
										echo "<CAPTION>Cumplimiento de Actividades Programadas</CAPTION>";
										echo "<tr bgcolor='#CCCCCC'>";
										echo "<td><b>Responsable</b></td>";
										echo "<td><b>Total Trabajos Area</b></td>";
										echo "<td><b>Trabajos a Tiempo</b></td>";
										echo "<td><b>Trabajos a Destiempo</b></td>";
										echo "<td><b>Trabajos sin Entregar</b></td>";
										echo "<td><b>Cumplimiento</b></td>";
										echo "<td><b>Incumplimiento</b></td>";
										echo "</tr>";
										//una tabla con los datos ordenados según lo consultemos.
											while ($row = mysqli_fetch_array($meter)){		
  												 echo "<tr>";
  												 echo "<td>".$row['Responsable']."</td>";
  												 echo "<td>".$row['TraArea']."</td>";
  												 echo "<td>".$row['TraEntTiempo']."</td>";
  												 echo "<td>".$row['TraEntDestiempo']."</td>";
  												 echo "<td>".$row['TraSinCerrar']."</td>";
  												 echo "<td>".$row['Cumplimiento']." %</td>";
												 echo "<td>".$row['Incumplimiento']." %</td>";
							   			    echo "</tr>";
											// Cerramos el While
												}
												
											echo "\r\n";	
											
											echo "\r\n";	
											
											echo "\r\n";	
											
											echo "\r\n";	
											
			                
                        
                             }    else  {
                                echo 'Ha existido un problema por favor vuelta a intentarlo.';
                                header("refresh: 2;IndicadoresCumplimiento.php]");
                            }
                            
                           
			
                            
                             if($meter1){
																			  
						 			  //echo 'He modificado la Recepcion del Pedido Numero '.$pedido.'. ';
										echo "<table border='1' align='center'>";
										echo "<CAPTION>Actividades Reprogramadas</CAPTION>";
										echo "<tr bgcolor='#CCCCCC'>";
										echo "<td><b>Responsable</b></td>";
										echo "<td><b>Total Trabajos Area</b></td>";
										echo "<td><b>Trabajos Anticipados</b></td>";
										echo "<td><b>Trabajos Retrasados</b></td>";
										echo "<td><b>% de Reprogramacion</b></td>";
										echo "</tr>";
										//una tabla con los datos ordenados según lo consultemos.
											while ($row = mysqli_fetch_array($meter1)){		
  												 echo "<tr>";
  												 echo "<td>".$row['Responsable']."</td>";
  												 echo "<td>".$row['TotalT']."</td>";
  												 echo "<td>".$row['Anticipadas']."</td>";
  												 echo "<td>".$row['Retrasadas']."</td>";
  												 echo "<td>".$row['PorReporgramadas']." %</td>";
							   			    echo "</tr>";
											// Cerramos el While
												}
												
											echo "\r\n";	
											
											echo "\r\n";	
											
											echo "\r\n";	
											
											echo "\r\n";	
											
			                
                        
                             }    else  {
                                echo 'Ha existido un problema por favor vuelta a intentarlo.';
                                header("refresh: 2;IndicadoresCumplimiento.php]");
                            }
                            
                            if($meter2){
																			  
						 			  //echo 'He modificado la Recepcion del Pedido Numero '.$pedido.'. ';
										echo "<table border='1' align='center'>";
										echo "<CAPTION>Tiempo Promedio de Programacion</CAPTION>";
										echo "<CAPTION ALIGN=BOTTOM>Titulo de la tabla</CAPTION >";
										echo "<tr bgcolor='#CCCCCC'>";
										echo "<td><b>Suma Diferencia Entre Programaciones</b></td>";
										echo "<td><b>Total de trabajos</b></td>";
										echo "<td><b>Promedio de dias</b></td>";
										echo "</tr>";
										//una tabla con los datos ordenados según lo consultemos.
											while ($row = mysqli_fetch_array($meter2)){		
  												 echo "<tr>";
  												 echo "<td>".$row['Diferencia']." dias.</td>";
  												 echo "<td>".$row['Pedidos']."</td>";
  												 echo "<td>".$row['Promedio']." dias.</td>";
  												 echo "</tr>";
											// Cerramos el While
												}
												
											echo "\r\n";	
											
											echo "\r\n";	
											
											echo "\r\n";	
											
											echo "\r\n";	
											
			                
                        
                             }    else  {
                                echo 'Ha existido un problema por favor vuelta a intentarlo.';
                                header("refresh: 2;IndicadoresCumplimiento.php]");
                            }
            exit;
        }
    }

	

//Notemos que colocamos ". y ." para concatenar las variables php y HTML
//Cerramos la tabla, es necesario hacerlo fuera del while, de los contrario solo mostraría la segunda fila dentro de la tabla el resto estaría desordenado.
echo "</table>";
// mysqli_close() es el evivalente a mysql_close() sirve para finalizar la conexión.
mysqli_close($enlace);

$FECHAOLD=$_SESSION['UltimoIngreso'];
$HORA=date('Y-n-j H:i:s');

$tiempo=(strtotime($HORA) - strtotime($FECHAOLD));

if($tiempo>=600){
	session_destroy();
	echo '<script language=javascript> alert ("su session a sido caducada por su seguridad, por favor ingrese nuevamente.") self.location="index.php"</script>';
	}else{
	$_SESSION['UltimoIngreso']=$HORA;
	}
?>



<?php
}else{
        echo 'El usuario no tiene los permisos suficientes para acceder a la web';
         mysqli_close($enlace); //Cerramos la conexion a la db
    }
} #Cierre del
else{
echo 'El usuario no tiene acceso a esta pagina web comuniquese con el administrador del sistema';
 mysqli_close($enlace); //Cerramos la conexion a la db
}
?>