<?php
require_once "../config/conexion.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['usuarios_ids'])) {
    $ids = $_POST['usuarios_ids'];

    // Separar IDs en alumnos y usuarios
    $alumno_ids = [];
    $usuario_ids = [];

    foreach ($ids as $id) {
        // Verifica si el ID existe en la tabla alumnos
        $stmt = $conn->prepare("SELECT id FROM alumnos WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $alumno_ids[] = $id;
        } else {
            $usuario_ids[] = $id;
        }

        $stmt->close();
    }

    // Eliminar usuarios
    if (!empty($usuario_ids)) {
        $placeholders = implode(',', array_fill(0, count($usuario_ids), '?'));
        $stmt = $conn->prepare("DELETE FROM usuarios WHERE id IN ($placeholders)");
        $types = str_repeat('i', count($usuario_ids));
        $stmt->bind_param($types, ...$usuario_ids);
        $stmt->execute();
        $stmt->close();
    }

    // Eliminar alumnos
    if (!empty($alumno_ids)) {
        $placeholders = implode(',', array_fill(0, count($alumno_ids), '?'));
        $stmt = $conn->prepare("DELETE FROM alumnos WHERE id IN ($placeholders)");
        $types = str_repeat('i', count($alumno_ids));
        $stmt->bind_param($types, ...$alumno_ids);
        $stmt->execute();
        $stmt->close();
    }

    header("Location: ../controllers/lista_usuarios.php?eliminados=ok");
    exit();
} else {
    header("Location: ../controllers/lista_usuarios.php");
    exit();
}