<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST'):

$FILENAME = '../private/bookings.csv';

$responses = [
  'no_file' => ['danger' => 'Imposibru'],
  'no_mail' => ['danger' => 'Email no encontrado'],
  'success' => [
    'success' => 'Haz anulado tu reserva exitosamente. Si deseas volver a '.
      'confirmar tu asistencia <a href="./contacto">contáctanos</a>'
  ]
];

/**
 * Rewrite if mail found */

if (file_exists($FILENAME)) {
  $fp = fopen($FILENAME, 'r');

  $i = 0;
  $newfile = array();
  while (($line = fgetcsv($fp)) !== false) {
    if ($line[2] === strtolower($_POST['abortEmail'])) {
      $found = true;
      $line[5] = 'y';
    }
    array_push($newfile, $line);
  }

  if (isset($found)) {
    fclose($fp);

    $fp = fopen($FILENAME, 'w');

    foreach ($newfile as $line)
      fputcsv($fp, $line);

    $response = $responses['success'];
  } else {
    $response = $responses['no_mail'];
  }

  fclose($fp);
} else {
  $response = $responses['no_file'];
}

/**
 * Response */

if (isset($_POST['fetch'])) {
  print json_encode($response);
} else {
  session_start();
  $_SESSION['response'] = json_encode($response);
  header('Location: ./');
}
return;

endif;
?>

<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Cancelar reserva</title>
  <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
  <form id="cancelForm" class="p-4 text-center" action="cancel.php" method="POST">
    <h3 class="lead">Anular reserva</h3>
    <div class="form-group">
      <label for="abortEmail">Email con que reservaste</label>
      <input type="text" name="abortEmail" class="form-control" id="abortEmail">
    </div>
    <button type="submit" class="btn btn-primary">Anular mi reserva</button>
  </form>
</body>
</html>
