<?php
session_start();
require_once 'db/config.php';

// Check if user is logged in and is an Administrador
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'Administrador') {
    header('Location: login.php');
    exit;
}

if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['message'] = '<div class="alert alert-danger">ID de usuario no válido.</div>';
    header('Location: manage_users.php');
    exit;
}

$user_id = $_GET['id'];

// Prevent admin from deleting themselves
if ($user_id == $_SESSION['user_id']) {
    $_SESSION['message'] = '<div class="alert alert-danger">No puedes eliminar tu propia cuenta.</div>';
    header('Location: manage_users.php');
    exit;
}

try {
    $db = db();
    $stmt = $db->prepare("DELETE FROM users WHERE id = :id");
    $stmt->bindParam(':id', $user_id);

    if ($stmt->execute()) {
        $_SESSION['message'] = '<div class="alert alert-success">Usuario eliminado con éxito.</div>';
    } else {
        $_SESSION['message'] = '<div class="alert alert-danger">Error al eliminar el usuario.</div>';
    }
} catch (PDOException $e) {
    $_SESSION['message'] = '<div class="alert alert-danger">Error de base de datos: ' . $e->getMessage() . '</div>';
}

header('Location: manage_users.php');
exit;
?>