<?php require_once 'db.php'; if (isset($_SESSION['user_id'])) header("Location: index.php");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $u = $_POST['u']; $p = $_POST['p'];
    $stmt = $conn->prepare("SELECT id_empleado, nombre, password_hash, rol FROM empleados WHERE usuario = ? AND estado = 1");
    $stmt->bind_param("s", $u); $stmt->execute(); $user = $stmt->get_result()->fetch_assoc();
    
    if ($user && password_verify($p, $user['password_hash'])) {
        $_SESSION['user_id'] = $user['id_empleado']; 
        $_SESSION['rol'] = $user['rol']; 
        
        // CARGAR PERMISOS A LA SESIÓN
        $perms = [];
        $q = $conn->query("SELECT vista FROM permisos WHERE rol = '{$user['rol']}'");
        while($row = $q->fetch_assoc()) { $perms[] = $row['vista']; }
        $_SESSION['mis_permisos'] = $perms;

        header("Location: index.php"); exit();
    } else { $err = "Credenciales incorrectas"; }
}
?>
<!DOCTYPE html><html lang="es"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><title>Login</title></head>
<body class="bg-light d-flex align-items-center justify-content-center vh-100">
    <form method="POST" class="bg-white p-5 rounded shadow" style="width:350px">
        <h4 class="text-center mb-4 text-primary fw-bold">Botica Guzmán</h4>
        <?php if(isset($err)) echo "<div class='alert alert-danger p-2 small'>$err</div>"; ?>
        <div class="mb-3"><label class="fw-bold small">USUARIO</label><input name="u" class="form-control" required></div>
        <div class="mb-4"><label class="fw-bold small">CONTRASEÑA</label><input type="password" name="p" class="form-control" required></div>
        <button class="btn btn-primary w-100 fw-bold">INGRESAR</button>
    </form>
</body></html>