<?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();

  try  {
    $connection = new PDO($dsn, $username, $password, $options);
    
    $nuevo_coche = array(
      "marca" => $_POST['marca'],
      "modelo"  => $_POST['modelo'],
      "matricula"     => $_POST['matricula']
    );

    $sql = sprintf(
      "INSERT INTO %s (%s) values (%s)",
      "vehiculos",
      implode(", ", array_keys($nuevo_coche)),
      ":" . implode(", :", array_keys($nuevo_coche))
    );
    
    $statement = $connection->prepare($sql);
    $statement->execute($nuevo_coche);
  } catch(PDOException $error) {
      echo $sql . "<br>" . $error->getMessage();
  }
}

?>

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

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

    <div class="app-wrapper">
	    <div class="container-xl">
			 <h1 class="app-page-title">Añadir vehículo</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="marca" class="form-label">Marca</label>
                   <input type="text"  class="form-control" name="marca" id="marca" required>
					 </div>
					 
					 <div class="mb-3">
                <label for="modelo" class="form-label">Modelo</label>
                <input type="text"  class="form-control" name="modelo" id="modelo" required>
                </div>
                
					 <div class="mb-3">                
                <label for="matricula" class="form-label">Matrícula</label>
                <input type="text" class="form-control" name="matricula" id="matricula" required >
                </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>