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

// Asegura que exista el paciente predeterminado aunque la base se haya creado antes.
$mysqli->query("INSERT IGNORE INTO patients (id, name, active) VALUES (1, 'Yiyita', 1)");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = (int)($_POST['user_id'] ?? 0);
    $patient_id = (int)($_POST['patient_id'] ?? 0);

    $stmt = $mysqli->prepare('SELECT id, name FROM users WHERE id = ? AND active = 1');
    $stmt->bind_param('i', $user_id);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    $stmt = $mysqli->prepare('SELECT id, name FROM patients WHERE id = ? AND active = 1');
    $stmt->bind_param('i', $patient_id);
    $stmt->execute();
    $patient = $stmt->get_result()->fetch_assoc();

    if ($user && $patient) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['patient_id'] = $patient['id'];
        $_SESSION['patient_name'] = $patient['name'];
        redirect('/ficha_medica/index.php');
    }
    $error = 'Seleccione un usuario y un paciente válido.';
}

$users = $mysqli->query('SELECT id, name FROM users WHERE active = 1 ORDER BY name');
$patients = $mysqli->query("SELECT id, name FROM patients WHERE active = 1 ORDER BY CASE WHEN name = 'Yiyita' THEN 0 ELSE 1 END, name");
include __DIR__ . '/../header.php';
?>
<div class="row justify-content-center">
  <div class="col-md-7 col-lg-6">
    <div class="card card-pink p-4">
      <h3 class="text-center mb-3" style="color:#d63384;">Ingresar</h3>
      <p class="text-center text-muted">Seleccione el usuario que carga y el paciente a seguir. No se utiliza contraseña.</p>
      <?php if (!empty($error)): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endif; ?>
      <form method="post">
        <label class="form-label">Usuario</label>
        <select name="user_id" class="form-select select2" required>
          <option value=""></option>
          <?php while($u = $users->fetch_assoc()): ?>
            <option value="<?= (int)$u['id'] ?>"><?= e($u['name']) ?></option>
          <?php endwhile; ?>
        </select>

        <label class="form-label mt-3">Paciente</label>
        <!-- Se deja sin Select2 en el login para evitar problemas de bloqueo en algunos navegadores/cPanel. -->
        <select name="patient_id" class="form-select" required>
          <?php while($p = $patients->fetch_assoc()): ?>
            <option value="<?= (int)$p['id'] ?>" <?= $p['name'] === 'Yiyita' ? 'selected' : '' ?>><?= e($p['name']) ?></option>
          <?php endwhile; ?>
        </select>
        <div class="form-text">El paciente predeterminado es Yiyita. Luego puede agregar más pacientes desde el menú Pacientes.</div>

        <button class="btn btn-pink w-100 mt-4">Entrar</button>
      </form>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../footer.php'; ?>
