<?php
declare(strict_types=1);

require_once __DIR__ . '/db_connect.php';

function clean(string $s): string {
  return trim($s);
}

$nombre = clean($_POST['nombre'] ?? '');
$ap_pat = clean($_POST['apellido_paterno'] ?? '');
$ap_mat = clean($_POST['apellido_materno'] ?? '');
$tel    = clean($_POST['telefono'] ?? '');
$dir    = clean($_POST['direccion_destino'] ?? '');
$hora   = clean($_POST['hora_espera'] ?? ''); // datetime-local: YYYY-MM-DDTHH:MM

if ($nombre === '' || $ap_pat === '' || $ap_mat === '' || $tel === '' || $dir === '' || $hora === '') {
  header('Location: index.php?res=err');
  exit;
}

// Convertir a formato DATETIME (MySQL) si viene con 'T'
$hora_mysql = str_replace('T', ' ', $hora) . ':00';
if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $hora_mysql)) {
  header('Location: index.php?res=err');
  exit;
}

try {
  $sql = "INSERT INTO reservaciones
    (nombre, apellido_paterno, apellido_materno, telefono, direccion_destino, fecha_hora_espera)
    VALUES (?,?,?,?,?,?)";
  $stmt = $conn->prepare($sql);
  if (!$stmt) throw new Exception('Prepare failed: ' . $conn->error);

  $stmt->bind_param("ssssss", $nombre, $ap_pat, $ap_mat, $tel, $dir, $hora_mysql);
  if (!$stmt->execute()) throw new Exception('Execute failed: ' . $stmt->error);

  $stmt->close();
  $conn->close();

  header('Location: index.php?res=ok');
  exit;
} catch (Throwable $e) {
  // Opcional: registra el error en servidor
  // error_log($e->getMessage());
  header('Location: index.php?res=err');
  exit;
}
