<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();

if (!isset($_SESSION['username']) || $_SESSION['rol'] !== 'administrador') {
    header("Location: ../login.php?error=access_denied");
    exit();
}

require_once __DIR__ . '/../includes/db.php';

$page_title = "Gestión de Menú";
include __DIR__ . '/../includes/header.php';

// --- LÓGICA DEL BACKEND ---

$feedback = [];

// Obtener todos los roles posibles de la tabla de usuarios (o definirlos manualmente)
$sql_roles = "SELECT DISTINCT rol FROM usuarios";
$result_roles = $conn->query($sql_roles);
$available_roles = [];
while ($row = $result_roles->fetch_assoc()) {
    $available_roles[] = $row['rol'];
}

// Manejar POST para crear/actualizar item
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_menu_item'])) {
    $item_id = $_POST['item_id'] ?: null;
    $label = trim($_POST['label']);
    $url = trim($_POST['url']);
    $icon = trim($_POST['icon']) ?: 'fa-solid fa-link';
    $parent_id = $_POST['parent_id'] ?: null;
    $roles = $_POST['roles'] ?? [];

    if (empty($label) || empty($url)) {
        $feedback = ['type' => 'danger', 'message' => 'El nombre y la URL son obligatorios.'];
    } else {
        if ($item_id) { // Actualizar
            $stmt = $conn->prepare("UPDATE menu_items SET label = ?, url = ?, icon = ?, parent_id = ? WHERE id = ?");
            $stmt->bind_param("sssii", $label, $url, $icon, $parent_id, $item_id);
            $stmt->execute();

            // Actualizar roles
            $conn->query("DELETE FROM menu_roles WHERE menu_item_id = $item_id");
            if (!empty($roles)) {
                $stmt_roles = $conn->prepare("INSERT INTO menu_roles (menu_item_id, rol) VALUES (?, ?)");
                foreach ($roles as $rol) {
                    $stmt_roles->bind_param("is", $item_id, $rol);
                    $stmt_roles->execute();
                }
            }
            $feedback = ['type' => 'success', 'message' => 'Elemento del menú actualizado correctamente.'];
        } else { // Crear
            $stmt = $conn->prepare("INSERT INTO menu_items (label, url, icon, parent_id) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("sssi", $label, $url, $icon, $parent_id);
            $stmt->execute();
            $new_item_id = $conn->insert_id;

            // Asignar roles
            if (!empty($roles)) {
                $stmt_roles = $conn->prepare("INSERT INTO menu_roles (menu_item_id, rol) VALUES (?, ?)");
                foreach ($roles as $rol) {
                    $stmt_roles->bind_param("is", $new_item_id, $rol);
                    $stmt_roles->execute();
                }
            }
            $feedback = ['type' => 'success', 'message' => 'Nuevo elemento de menú creado.'];
        }
    }
}

// Manejar eliminación
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_menu_item'])) {
    $item_id = $_POST['item_id'];
    // La BD está configurada con ON DELETE CASCADE, así que menu_roles se limpia solo.
    $stmt = $conn->prepare("DELETE FROM menu_items WHERE id = ?");
    $stmt->bind_param("i", $item_id);
    $stmt->execute();
    $feedback = ['type' => 'info', 'message' => 'Elemento del menú eliminado.'];
}

// --- OBTENER DATOS PARA LA VISTA ---
$sql = "SELECT mi.*, GROUP_CONCAT(mr.rol) as roles 
        FROM menu_items mi 
        LEFT JOIN menu_roles mr ON mi.id = mr.menu_item_id 
        GROUP BY mi.id
        ORDER BY mi.sort_order, mi.label";
$result = $conn->query($sql);
$menu_items = [];
while ($row = $result->fetch_assoc()) {
    $row['roles'] = $row['roles'] ? explode(',', $row['roles']) : [];
    $menu_items[] = $row;
}

// Función para construir el árbol de menú para la vista
function buildMenuTree(array &
$elements, $parentId = null) {
    $branch = [];
    foreach ($elements as &
$element) {
        if ($element['parent_id'] == $parentId) {
            $children = buildMenuTree($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[$element['id']] = $element;
            unset($element);
        }
    }
    return $branch;
}

$menu_tree = buildMenuTree($menu_items);

// Función para renderizar el árbol de menú en HTML
function renderMenuTree($nodes, $roles_disponibles, $is_child = false) {
    echo $is_child ? '<ul class="list-group mt-2">' : '<ul class="list-group">' ;
    foreach ($nodes as $node) {
        echo '<li class="list-group-item d-flex justify-content-between align-items-center">';
        echo '<div>';
        echo '<i class="' . htmlspecialchars($node['icon']) . ' me-2"></i>';
        echo '<strong>' . htmlspecialchars($node['label']) . '</strong>';
        echo '<br><small class="text-muted">' . htmlspecialchars($node['url']) . '</small>';
        echo '<div class="mt-1">';
        foreach ($node['roles'] as $role) {
            echo '<span class="badge bg-secondary me-1">' . htmlspecialchars($role) . '</span>';
        }
        echo '</div>';
        echo '</div>';
        echo '<div>';
        echo '<button class="btn btn-primary btn-sm me-2" data-bs-toggle="modal" data-bs-target="#menuModal" data-item=\'' . htmlspecialchars(json_encode($node), ENT_QUOTES, 'UTF-8') . '\'"><i class="fas fa-edit"></i> Editar</button>';
        echo '<form method="POST" style="display:inline-block;" onsubmit="return confirm(\'¿Estás seguro de que quieres eliminar este elemento?\');">
';
        echo '<input type="hidden" name="item_id" value="' . $node['id'] . '">';
        echo '<button type="submit" name="delete_menu_item" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i></button>';
        echo '</form>';
        echo '</div>';
        echo '</li>';

        if (!empty($node['children'])) {
            echo '<li class="list-group-item" style="padding-left: 40px;">';
            renderMenuTree($node['children'], $roles_disponibles, true);
            echo '</li>';
        }
    }
    echo '</ul>';
}

?>

<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-bars me-2"></i>Gestión del Menú de Navegación</h2>
        <div>
            <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#menuModal" data-item="null">
                <i class="fas fa-plus"></i> Añadir Nuevo Elemento
            </button>
            <a href="gestion_registro.php" class="btn btn-secondary">Volver a Configuración</a>
        </div>
    </div>

    <?php if ($feedback): ?>
        <div class="alert alert-<?= $feedback['type'] ?>"><?= htmlspecialchars($feedback['message']) ?></div>
    <?php endif; ?>

    <div class="card">
        <div class="card-header">Menú Principal</div>
        <div class="card-body">
            <?php if (empty($menu_tree)): ?>
                <p class="text-center text-muted">No hay elementos en el menú. ¡Añade uno para empezar!</p>
            <?php else: ?>
                <?php renderMenuTree($menu_tree, $available_roles); ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal para Añadir/Editar -->
<div class="modal fade" id="menuModal" tabindex="-1" aria-labelledby="menuModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title" id="menuModalLabel">Añadir/Editar Elemento del Menú</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="item_id" id="item_id">
                    
                    <div class="mb-3">
                        <label for="label" class="form-label">Nombre / Etiqueta</label>
                        <input type="text" class="form-control" id="label" name="label" required>
                    </div>

                    <div class="mb-3">
                        <label for="url" class="form-label">URL</label>
                        <input type="text" class="form-control" id="url" name="url" required>
                        <div class="form-text">Ej: /admin/gestion_usuarios.php</div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="icon" class="form-label">Icono (Font Awesome)</label>
                            <input type="text" class="form-control" id="icon" name="icon">
                            <div class="form-text">Ej: fa-solid fa-users</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="parent_id" class="form-label">Elemento Padre (para submenús)</label>
                            <select class="form-select" id="parent_id" name="parent_id">
                                <option value="">-- Ninguno (Elemento Principal) --</option>
                                <?php foreach ($menu_items as $item): ?>
                                    <option value="<?= $item['id'] ?>"><?= htmlspecialchars($item['label']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Visible para los roles:</label>
                        <div class="d-flex flex-wrap">
                            <?php foreach ($available_roles as $role): ?>
                                <div class="form-check form-check-inline me-3">
                                    <input class="form-check-input" type="checkbox" name="roles[]" id="role_<?= htmlspecialchars($role) ?>" value="<?= htmlspecialchars($role) ?>">
                                    <label class="form-check-label" for="role_<?= htmlspecialchars($role) ?>"><?= ucfirst(htmlspecialchars($role)) ?></label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" name="save_menu_item" class="btn btn-primary">Guardar Cambios</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var menuModal = document.getElementById('menuModal');
    menuModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        var itemData = button.getAttribute('data-item');
        var item = itemData && itemData !== 'null' ? JSON.parse(itemData) : null;

        var modalTitle = menuModal.querySelector('.modal-title');
        var form = menuModal.querySelector('form');
        form.reset(); // Limpiar formulario

        // Resetear checkboxes de roles
        form.querySelectorAll('input[type="checkbox"]').forEach(chk => chk.checked = false);

        if (item) { // Editar
            modalTitle.textContent = 'Editar Elemento: ' + item.label;
            form.querySelector('#item_id').value = item.id;
            form.querySelector('#label').value = item.label;
            form.querySelector('#url').value = item.url;
            form.querySelector('#icon').value = item.icon;
            form.querySelector('#parent_id').value = item.parent_id || '';

            // Marcar roles asignados
            if (item.roles) {
                item.roles.forEach(function(role) {
                    var checkbox = form.querySelector('#role_' + role);
                    if (checkbox) checkbox.checked = true;
                });
            }

            // Deshabilitar la opción de ser padre de sí mismo
            var parentOption = form.querySelector('#parent_id option[value="' + item.id + '"]');
            if(parentOption) parentOption.disabled = true;

        } else { // Crear
            modalTitle.textContent = 'Añadir Nuevo Elemento';
            form.querySelector('#item_id').value = '';
        }
    });
});
</script>

<?php
include __DIR__ . '/../includes/footer.php';
?>
