<?php
// public/pages/preparados/delete.php
require __DIR__.'/../../inc/bootstrap.php';

// Asegurar sesión para CSRF
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$id = (int)($_GET['id'] ?? ($_POST['id'] ?? 0));
if ($id <= 0) {
  http_response_code(400);
  echo "ID inválido";
  exit;
}

// Si POST: validar CSRF y eliminar
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $csrf = $_POST['csrf'] ?? '';
  if (!$csrf || !isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $csrf)) {
    http_response_code(403);
    echo "CSRF inválido";
    exit;
  }

  try {
    $pdo->beginTransaction();

    // Verificar existencia
    $chk = $pdo->prepare("SELECT id FROM preparados WHERE id=? FOR UPDATE");
    $chk->execute([$id]);
    $row = $chk->fetch();
    if (!$row) {
      $pdo->rollBack();
      http_response_code(404);
      echo "Preparado no encontrado";
      exit;
    }

    // Borrar detalles (si no tienes FK cascade)
    $pdo->prepare("DELETE FROM componentes_preparado WHERE id_preparado=?")->execute([$id]);

    // Borrar principal
    $pdo->prepare("DELETE FROM preparados WHERE id=?")->execute([$id]);

    $pdo->commit();

    // Limpia token usado
    unset($_SESSION['csrf_token']);

    header("Location: list.php?deleted=1");
    exit;

  } catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code(500);
    echo "Error al eliminar: ".$e->getMessage();
    exit;
  }
}

// Si GET: mostrar confirmación
// Cargar info mínima para mostrar (opcional)
$info = $pdo->prepare("SELECT p.numero_externo, p.fecha_elaboracion, pa.nombre AS pac, d.nombre AS doc
                       FROM preparados p
                       JOIN pacientes pa ON pa.id=p.id_paciente
                       JOIN doctores  d ON d.id=p.id_doctor
                       WHERE p.id=?");
$info->execute([$id]);
$inf = $info->fetch();

// CSRF token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
$csrf = $_SESSION['csrf_token'];
?>
<!doctype html><html lang="es"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../../assets/styles.css">
<link rel="stylesheet" href="../../assets/theme.css">
<title>Eliminar preparado</title>
<style>
