<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';
require_user();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    if ($name !== '') {
        $stmt = $mysqli->prepare('INSERT INTO medications_catalog (name) VALUES (?)');
        $stmt->bind_param('s', $name);
        @$stmt->execute();
    }
    redirect('/ficha_medica/medicamentos/index.php');
}
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $mysqli->prepare('UPDATE medications_catalog SET active = 0 WHERE id = ?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    redirect('/ficha_medica/medicamentos/index.php');
}
$items = $mysqli->query('SELECT id, name FROM medications_catalog WHERE active = 1 ORDER BY name');
include __DIR__ . '/../header.php';
?>
<div class="card card-pink p-4">
  <h4 style="color:#d63384;">Medicamentos</h4>
  <form method="post" class="row g-2 mb-4">
    <div class="col-md-10"><input class="form-control" name="name" placeholder="Nombre del medicamento" required></div>
    <div class="col-md-2"><button class="btn btn-pink w-100">Agregar</button></div>
  </form>
  <div class="table-responsive"><table class="table table-hover align-middle">
    <thead><tr><th>Medicamento</th><th class="text-end">Acción</th></tr></thead><tbody>
    <?php while($row = $items->fetch_assoc()): ?>
      <tr><td><?= e($row['name']) ?></td><td class="text-end"><a class="btn btn-sm btn-outline-danger" onclick="return confirm('¿Eliminar medicamento?')" href="?delete=<?= (int)$row['id'] ?>">Eliminar</a></td></tr>
    <?php endwhile; ?>
    </tbody></table></div>
</div>
<?php include __DIR__ . '/../footer.php'; ?>
