<?php

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

require "./config.php";
require "./common.php";

if (isset($_POST['submit'])) {
  if (!hash_equals($_SESSION['csrf'], $_POST['csrf'])) die();

  if (empty($_POST['fecha']) or 
      empty($_POST['kms']) or 
      empty($_POST['litros']) or
      empty($_POST['importe'])) {

?>

<?php require "./cabecera.php"; ?>

<section id="four" class="main style2 special">
    <div class="container">
        <header class="major">
            <h2>Introducción de repostajes</h2>
        </header>
        <section>
            <p>Por favor, rellena todos los campos.</p>
            <ul class="actions special">
                <li><a href="create.php" class="button wide primary">Volver</a></li>
            </ul>
        </section>
    </div>
</section>
<?php require "../templates/footer.php"; ?>

<?php
    die();
  } else {
    try  {
      $connection = new PDO($dsn, $username, $password, $options);

      // Calcula el precio por litro
      //$total = floatval($_POST['importe']);

      //$total=floatval(str_replace(',', '.', str_replace('.', '', $_POST['importe'])));
      $total = floatval($_POST['importe']);

      //$cantidad = floatval(str_replace(',', '.', str_replace('.', '', $_POST['litros'])));
      $cantidad = floatval($_POST['litros']);

      if(empty($_POST['dtoing'])) {
        $dto = 0;
      } else {
        $dto = ($total*0.03);
      }

      //$dto = intval($_POST['descuento']);
      $totalcondto = $total-$dto;
      $ellitro = ($totalcondto / $cantidad);

      // Estas líneas son para conocer los kms del último repostaje
      $sql = sprintf('SELECT kms FROM carburante WHERE vehiculo = ? order by identificador DESC LIMIT 1');
      $smt = $connection->prepare($sql);
      $smt->execute([$_POST['vehiculo']]);
      $filas = $smt->fetchAll();

      foreach ($filas as $row) {
        $kmsanteriores=$row["kms"];
      } 
      
      $kmsrecorridos=$_POST['kms']-$kmsanteriores;      

      //
      // Hasta aquí lo de conocer los kms del último repostaje

      $nuevo_repostaje = array(
        "fecha" => $_POST['fecha'],
        "vehiculo"  => $_POST['vehiculo'],
        "kms"     => $_POST['kms'],
        "litros"  => str_replace(',', '.',$_POST['litros']),
        "descuento" => $dto,
        "precioxlitro" => str_replace(',', '.',strval($ellitro)),
        "importe"  => $totalcondto,
      );

      $sql = sprintf(
        "INSERT INTO %s (%s) values (%s)",
        "carburante",
        implode(", ", array_keys($nuevo_repostaje)),
        ":" . implode(", :", array_keys($nuevo_repostaje))
      );
    
    /* 
     * Logs
     */

     $log_msg='CREA REPOSTAJE-> Litros: '.$cantidad.' Descuento: '.$dto.'. Total con descuento: '.$totalcondto.'. Total introducido: '.$_POST['importe'].'. Kilometros anteriores: '.$kmsanteriores.'. Kilometros recorridos: '.$kmsrecorridos;

     escribe_log($log_msg);

      $statement = $connection->prepare($sql);
      $statement->execute($nuevo_repostaje);
    } catch(PDOException $error) {
        echo $sql . "<br>" . $error->getMessage();
    }
  }
}


?>
<?php require "./cabecera.php"; ?>

<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['fecha']); ?> successfully added.</blockquote>
<?php endif; ?>

    <div class="app-wrapper">
	    <div class="container-xl">
			 <h1 class="app-page-title">Añadir repostaje</h1>
          <hr class="mb-4">
        
          <div class="app-card-body">
            <form class="settings-form" method="post">

                <input name="csrf" type="hidden" value="<?php echo escape($_SESSION['csrf']); ?>">
                
                <div class="mb-3">
                   <label for="fecha" class="form-label">Fecha</label>
                   <input type="date"  class="form-control" name="fecha" id="fecha" required>
					 </div>
					 
					 <div class="mb-3"> 
                <label for="vehiculo" class="form-label">Vehículo</label>
                <select name="vehiculo" id="vehiculo" required>
                        <option value="" disabled selected>Selecciona un vehículo</option>

                        <?php
                    try {
                    $conexion = new PDO($dsn, $username, $password, $options);
                    $smt = $conexion->prepare('SELECT matricula FROM vehiculos');
                    $smt->execute();
                    $vehiculos = $smt->fetchAll();
                    
                    foreach ($vehiculos as $row) {
                     echo "<option value='".$row["matricula"]."'>" . $row["matricula"]."</option>";
                     } 
                    } catch (PDOException $e) {
                      echo "Error: " . $e->getMessage();
                    }
                    ?>
                </select>
                </div>
					
					 <div class="mb-3">
                <label for="kms" class="form-label">Kilómetros</label>
                <input type="number"  class="form-control" name="kms" id="kms" required>
                </div>
                
					 <div class="mb-3">                
                <label for="litros" class="form-label">Litros</label>
                <input type="number" class="form-control" name="litros" id="litros" required step="0.01">
                </div>
					 <div class="mb-3">
                <label for="importe" class="form-label">Importe</label>
                <input type="number" class="form-control" name="importe" id="importe" required step="0.01">
                </div>
					 <div class="mb-3">                
                <input type="checkbox"  id="dtoing" name="dtoing">
                    <label for="dtoing" class="form-label">Descuento ING</label>
                </div>
                
                <input type="submit" class="btn app-btn-primary" name="submit" value="Crear">
            </form>
            </div>

    </div>
    </div>


<?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>