<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';
require_user();

$procedures = $mysqli->query('SELECT id, name FROM procedures_catalog WHERE active = 1 ORDER BY name');
$medications = $mysqli->query('SELECT id, name FROM medications_catalog WHERE active = 1 ORDER BY name');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = (int)current_user_id();
    $patient_id = (int)current_patient_id();
    $date = $_POST['followup_date'] ?? date('Y-m-d');
    $time = $_POST['followup_time'] ?? date('H:i');
    $procedure_id = ($_POST['procedure_id'] ?? '') !== '' ? (int)$_POST['procedure_id'] : null;
    $medication_id = ($_POST['medication_id'] ?? '') !== '' ? (int)$_POST['medication_id'] : null;
    $blood_pressure = trim($_POST['blood_pressure'] ?? '');
    $oxygen_saturation = ($_POST['oxygen_saturation'] ?? '') !== '' ? (float)$_POST['oxygen_saturation'] : null;
    $observation = trim($_POST['observation'] ?? '');

    $stmt = $mysqli->prepare('INSERT INTO medical_followups (user_id, patient_id, followup_date, followup_time, procedure_id, medication_id, blood_pressure, oxygen_saturation, observation) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
    $stmt->bind_param('iissiisds', $user_id, $patient_id, $date, $time, $procedure_id, $medication_id, $blood_pressure, $oxygen_saturation, $observation);
    $stmt->execute();
    redirect('/ficha_medica/seguimiento/index.php?ok=1');
}
include __DIR__ . '/../header.php';
?>
<div class="row justify-content-center">
  <div class="col-lg-9">
    <div class="card card-pink p-4">
      <h4 class="mb-1" style="color:#d63384;">Nuevo Item</h4>
      <p class="text-muted mb-3">Paciente: <strong><?= e(current_patient_name()) ?></strong></p>
      <form method="post" class="row g-3">
        <div class="col-md-6">
          <label class="form-label">Fecha</label>
          <input type="date" name="followup_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
        </div>
        <div class="col-md-6">
          <label class="form-label">Hora</label>
          <input type="time" name="followup_time" id="followup_time" class="form-control" required>
        </div>
        <div class="col-md-6">
          <label class="form-label">Procedimiento</label>
          <select name="procedure_id" class="form-select select2">
            <option value=""></option>
            <?php while($p = $procedures->fetch_assoc()): ?>
              <option value="<?= (int)$p['id'] ?>"><?= e($p['name']) ?></option>
            <?php endwhile; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label">Medicamento</label>
          <select name="medication_id" class="form-select select2">
            <option value=""></option>
            <?php while($m = $medications->fetch_assoc()): ?>
              <option value="<?= (int)$m['id'] ?>"><?= e($m['name']) ?></option>
            <?php endwhile; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label">Presión arterial</label>
          <input type="text" name="blood_pressure" class="form-control" placeholder="Ej: 120/80">
        </div>
        <div class="col-md-6">
          <label class="form-label">Saturación de oxígeno (%)</label>
          <input type="number" step="0.01" min="0" max="100" name="oxygen_saturation" class="form-control" placeholder="Ej: 96">
        </div>
        <div class="col-12">
          <label class="form-label">Observación</label>
          <textarea name="observation" class="form-control" rows="5" placeholder="Detalle de evolución, síntomas, indicaciones, etc."></textarea>
        </div>
        <div class="col-12 d-flex gap-2">
          <button class="btn btn-pink px-4">Guardar item</button>
          <a class="btn btn-outline-secondary" href="index.php">Cancelar</a>
        </div>
      </form>
    </div>
  </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const horaInput = document.getElementById('followup_time');

    if (horaInput && !horaInput.value) {
        const ahora = new Date();
        const horas = String(ahora.getHours()).padStart(2, '0');
        const minutos = String(ahora.getMinutes()).padStart(2, '0');

        horaInput.value = `${horas}:${minutos}`;
    }
});
</script>
<?php include __DIR__ . '/../footer.php'; ?>
