<?php
  
/**
* Use an HTML form to create a new entry in the
* users table.
*
*/

require './config.php';
require './common.php';

/**
* Esto es para comprobar si existe la BD
* Además, nos permite seleccionar los últimos repostajes y otras cosas que queramos
*/
try {
    $conexion = new PDO( $dsn, $username, $password, $options );

    include './cabecera.php';
    
    /*
    	Seleccionamos los 10 últimos repostajes de todos los vehículos
    */
    $sql = "SELECT * 
    FROM carburante
    ORDER BY fecha DESC LIMIT 10";

    $statement = $conexion->prepare($sql);
    $statement->execute();

    $result = $statement->fetchAll();
    
    
    /*
      Seleccionar los vehículos que hay
    */
    
    $sql = "SELECT * 
            FROM vehiculos";


    $statement = $conexion->prepare($sql);

    $statement->execute();

    $resultvehiculos = $statement->fetchAll();
    
    /*
    	con los vehículos, buscamos los registros de repostajes para cada uno de ellos
    	y lo guaradamos en un array
    */
    
    $resultCoches = array();
    
    foreach ($resultvehiculos as $coche) {
    	
    	$sql = sprintf(
             "SELECT * 
              FROM carburante 
              WHERE vehiculo = '%s' ORDER BY fecha", $coche["matricula"]);

      $statement = $conexion->prepare($sql);
      $statement->execute();

      array_push($resultCoches, $statement->fetchAll(), $_ = null);
    }
?>
   

    
    <div class="app-wrapper">
	    
	    <div class="app-content pt-3 p-md-3 p-lg-4">
		    <div class="container-xl">
			    
			    <div class="row g-3 mb-4 align-items-center justify-content-between">
				    <div class="col-auto">
			            <h1 class="app-page-title mb-0">Gestión de repostajes</h1>
				    </div>
				    
			    </div><!--//row-->
			   
			    
			    <nav id="orders-table-tab" class="orders-table-tab app-nav-tabs nav shadow-sm flex-column flex-sm-row mb-4">
				    <a class="flex-sm-fill text-sm-center nav-link active" id="orders-all-tab" data-bs-toggle="tab" href="#orders-all" role="tab" aria-controls="orders-all" aria-selected="true">Todos</a>
				    
				    <?php foreach ($resultvehiculos as $cadacoche) : ?>

			       <a class="flex-sm-fill text-sm-center nav-link"  id="orders-paid-tab" data-bs-toggle="tab" href="#<?php echo $cadacoche["matricula"]?>" role="tab" aria-controls="orders-paid" aria-selected="false"><?php echo $cadacoche["marca"]?></a>
				    
				    <?php endforeach; ?>


				    <a class="flex-sm-fill text-sm-center nav-link" id="orders-pending-tab" data-bs-toggle="tab" href="#vehiculos" role="tab" aria-controls="orders-pending" aria-selected="false">Vehículos</a>
				</nav>
				
				
				<div class="tab-content" id="orders-table-tab-content">
			        <div class="tab-pane fade show active" id="orders-all" role="tabpanel" aria-labelledby="orders-all-tab">
					    <div class="app-card app-card-orders-table shadow-sm mb-5">
						    <div class="app-card-body">
							    <div class="table-responsive">
							        <table class="table app-table-hover mb-0 text-left">
										<thead>
											<tr>
												<th class="cell">#</th>
                        				<th class="cell">Fecha</th>
                        				<th class="cell">Vehículo</th>
                        				<th class="cell">Kilómetros</th>
                        				<th class="cell">Litros</th>
                        				<th class="cell">Descuento</th>
                        				<th class="cell">Precio/litro</th>
                        				<th class="cell">Importe</th>
											</tr>
										</thead>
										<tbody>
												<?php foreach ($result as $row) : ?>
                    						<tr>
                        					<td class="cell"><?php echo escape($row["identificador"]); ?></td>
                        					<td class="cell"><?php echo escape($row["fecha"]); ?></td>
                        					<td class="cell"><?php echo escape($row["vehiculo"]); ?></td>
                        					<td class="cell"><?php echo escape($row["kms"]); ?></td>
                        					<td class="cell"><?php echo escape(str_replace('.', ',',$row["litros"])); ?></td>
                        					<td class="cell"><?php echo escape(str_replace('.', ',',$row["descuento"])); ?></td>
                        					<td class="cell"><?php echo escape(str_replace('.', ',',$row["precioxlitro"])); ?></td>
                        					<td class="cell"><?php echo escape(str_replace('.', ',',$row["importe"])); ?></td>
                    						</tr>
                    						<?php endforeach; ?>
										</tbody>
									</table>
						        </div><!--//table-responsive-->
						       
						    </div><!--//app-card-body-->		
						</div><!--//app-card-->						
			        </div><!--//tab-pane-->
			              
			        <?php 
                   foreach ($resultCoches as $micoche) {  /* 1 */
                       if(is_iterable($micoche)) {  /* 2 */                          
                         foreach ($micoche as $rowtab) { /* 3 */
		           ?>
			        <div class="tab-pane fade" id="<?php echo $rowtab["vehiculo"]?>" role="tabpanel" aria-labelledby="orders-paid-tab">
					    <div class="app-card app-card-orders-table mb-5">
						    <div class="app-card-body">
							    <div class="table-responsive">
								    <?php echo $rowtab["vehiculo"]?>
							        <table class="table mb-0 text-left">
										<thead>
											<tr>
												<th class="cell">#</th>
                        				<th class="cell">Fecha</th>
                        				<th class="cell">Vehículo</th>
                        				<th class="cell">Kilómetros</th>
                        				<th class="cell">Litros</th>
                        				<th class="cell">Descuento</th>
                        				<th class="cell">Precio/litro</th>
                        				<th class="cell">Importe</th>
                        				<th class="cell">Recorridos</th>
                                    <th class="cell">Consumo/100kms</th>
											</tr>
										</thead>
										<tbody>
										
												<?php $kmsanterior=0;
		                                if(is_iterable($micoche)) {  /* 4 */                           
		                                  foreach ($micoche as $row) { /* 5 */
				                              $kmsrecorridos=$row["kms"]-$kmsanterior;
				                              if($kmsrecorridos==$row["kms"]) {$kmsrecorridos=0;}
		                                    $kmsanterior = $row["kms"];
		                                    $consumo=0;
		                                    if($kmsrecorridos>0) {$consumo=($row["litros"]*100)/$kmsrecorridos;}
		                              ?>
										  
                       
                    						<tr>
                        					<td class="cell"><?php echo escape($row["identificador"]); ?></td>
                        					<td class="cell"><?php echo escape($row["fecha"]); ?></td>
                        					<td class="cell"><?php echo escape($row["vehiculo"]); ?></td>
                        					<td class="cell"><?php echo escape($row["kms"]); ?></td>
                        					<td class="cell"><?php echo escape(str_replace('.', ',',$row["litros"])); ?></td>
                        					<td class="cell"><?php echo escape(str_replace('.', ',',$row["descuento"])); ?></td>
                        					<td class="cell"><?php echo escape(str_replace('.', ',',$row["precioxlitro"])); ?></td>
                        					<td class="cell"><?php echo escape(str_replace('.', ',',$row["importe"])); ?></td>
                        					<td class="cell"><?php echo escape($kmsrecorridos); ?></td>
                                       <td class="cell"><?php echo escape(number_format($consumo,2,",",".")); ?></td>
                    						</tr>
                    					   
                    					   <?php
                    						      } /* 5 */
                    						   } /*  4 */
                                    ?>
                              </tbody>
									</table>
						        </div><!--//table-responsive-->
						    </div><!--//app-card-body-->		
						</div><!--//app-card-->
			        </div><!--//tab-pane-->
			        <?php } /* 3 */
                    } /* 2 */
                 } /*  1 */
                 ?>
			      
			        
			        <div class="tab-pane fade" id="vehiculos" role="tabpanel" aria-labelledby="orders-pending-tab">
					    <div class="app-card app-card-orders-table mb-5">
						    <div class="app-card-body">
							    <div class="table-responsive">
							        <table class="table mb-0 text-left">
										<thead>
											<tr>
												<th class="cell">#</th>
                        				<th class="cell">Marca</th>
                        				<th class="cell">Modelo</th>
                        				<th class="cell">Matricula</th>
											</tr>
										</thead>
										<tbody>
                                    <?php foreach ($resultvehiculos as $row) : ?>
                    						<tr>
                        					<td class="cell"><?php echo escape($row["identificador"]); ?></td>
                        					<td class="cell"><?php echo escape($row["marca"]); ?></td>
                        					<td class="cell"><?php echo escape($row["modelo"]); ?></td>
                        					<td class="cell"><?php echo escape($row["matricula"]); ?></td>
                    						</tr>
                    						<?php endforeach; ?>
		
										</tbody>
									</table>
						        </div><!--//table-responsive-->
						    </div><!--//app-card-body-->		
						</div><!--//app-card-->
			        </div><!--//tab-pane-->
				</div><!--//tab-content-->
				
				
			    
		    </div><!--//container-fluid-->
	    </div><!--//app-content-->
	    	    
<?php 
    require './templates/footer.php';
} catch( PDOException $error ) {
    require './cabecera.php';
?>

<section id='four' class='main style2 special'>
    <div class='container'>
        <header class='major'>
            <h2>Base de datos inexistente</h2>
        </header>
        <section>
            <p>La base de datos no existe. ¿quieres inicializarla?</p>
            <ul class='actions special'>
                <li><a href='/install.php'><strong>Crear base de datos</strong></a></li>
            </ul>
        </section>
    </div>
</section>
<?php 
    require './templates/footer.php';
}
?>
   <!-- Javascript -->          
    <script src="assets/plugins/popper.min.js"></script>
    <script src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>  
    
    
    <!-- Page Specific JS -->
    <script src="assets/js/app.js"></script> 
</body>
</html>

