<?php
// =============================================================================
// CONFIGURACIÓN PARA DEBUGGING Y VARIABLES
// =============================================================================
error_reporting(E_ALL);
ini_set('display_errors', 1);
ob_start();

// VARIABLES DE CONEXIÓN
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '33comRxXMysql'; 
$db_name = 'MS_Usuario';
$db_table = 'Menu_Catalogo';

// =============================================================================
// BACKEND PHP (Solo se ejecuta si hay petición AJAX)
// =============================================================================
if (isset($_GET['action'])) {
    if (ob_get_length()) ob_clean();
    header('Content-Type: application/json');

    $action = $_GET['action'];
    $response = ['status' => 'error', 'message' => 'Acción desconocida'];
    $conn = null;

    try {
        $conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
        if ($conn->connect_error) {
            throw new Exception("Error conectando a MySQL: " . $conn->connect_error);
        }
        $conn->set_charset("utf8");

        if ($action === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $items = $input['menu'] ?? [];

            $check = $conn->query("SHOW TABLES LIKE '$db_table'"); 
            if($check === false || $check->num_rows == 0) {
                 $sqlCreate = "CREATE TABLE $db_table (
                      IDM INT PRIMARY KEY AUTO_INCREMENT,
                      Grupo INT NOT NULL DEFAULT 0, 
                      Orden INT NOT NULL DEFAULT 0,
                      NombreGrupo VARCHAR(100) NOT NULL, 
                      NombreMenu VARCHAR(100) NOT NULL,
                      Descripcion TEXT, 
                      Link VARCHAR(255), 
                      Icono VARCHAR(100),
                      Datos_Mysql TEXT, 
                      Datos_Codigo TEXT, 
                      Datos_Componentes TEXT, 
                      Token VARCHAR(255)
                 )";
                 if(!$conn->query($sqlCreate)) throw new Exception("No se pudo crear la tabla. Error: " . $conn->error);
            }

            $conn->begin_transaction();
            // Limpiamos pero ahora insertaremos con el campo Orden
            if (!$conn->query("TRUNCATE TABLE $db_table")) {
                throw new Exception("Error al limpiar la tabla (TRUNCATE). Error: " . $conn->error);
            }
            
            // Agregamos Orden a la consulta
            $sql = "INSERT INTO $db_table (Grupo, Orden, NombreGrupo, NombreMenu, Descripcion, Link, Icono, Datos_Mysql, Datos_Codigo, Datos_Componentes, Token) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            if(!$stmt) throw new Exception("Error al preparar la consulta: " . $conn->error);

            // bind_param ajustado para 11 variables (ii sssssssss)
            $stmt->bind_param("iisssssssss", $v1, $v_ord, $v2, $v3, $v4, $v5, $v6, $v7, $v8, $v9, $v10);
            
            foreach ($items as $index => $i) {
                $v1=intval($i['Grupo'] ?? 0); 
                $v_ord = $index; // El orden es la posición en el array enviado
                $v2=$i['NombreGrupo']??''; $v3=$i['NombreMenu']??''; 
                $v4=$i['Descripcion']??''; $v5=$i['Link']??''; $v6=$i['Icono']??'';
                $v7=$i['Datos_Mysql']??''; $v8=$i['Datos_Codigo']??'';
                $v9=$i['Datos_Componentes']??''; $v10=$i['Token']??'';
                $stmt->execute();
            }
            $conn->commit();
            $response = ['status' => 'success', 'message' => 'Guardado correctamente (' . count($items) . ' items).'];
        }

        if ($action === 'fetch') {
            $check = $conn->query("SHOW TABLES LIKE '$db_table'");
            if($check !== false && $check->num_rows > 0) {
                // IMPORTANTÍSIMO: Ordenar por la nueva columna Orden
                $result = $conn->query("SELECT * FROM $db_table ORDER BY Orden ASC");
                $data = [];
                while ($row = $result->fetch_assoc()) { $data[] = $row; }
                $response = ['status' => 'success', 'data' => $data, 'message' => 'Datos cargados.'];
            } else {
                $response = ['status' => 'success', 'data' => [], 'message' => 'Tabla vacía.'];
            }
        }
    } catch (Exception $e) {
        if ($conn && $conn->in_transaction) $conn->rollback();
        $response = ['status' => 'error', 'message' => $e->getMessage()];
    } finally {
        if ($conn) $conn->close();
    }
    echo json_encode($response);
    exit;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EditorMenu - Pro 3.1 Fixed</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.5.5/css/simple-line-icons.min.css" rel="stylesheet">
    <style>
        :root { --sidebar-bg: #3f4d67; }
        body { background-color: #f4f7f6; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; overflow: hidden; }
        
        .column-scroll { 
            height: calc(100vh - 80px); 
            overflow-y: auto; 
            padding: 10px;
        }

        .card { border: none; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 15px; }
        .card-header { background: white; font-weight: bold; font-size: 0.9rem; }
        
        .code-editor { font-family: 'Cascadia Code', monospace; font-size: 11px; background: #1e1e1e; color: #9cdcfe; border: 1px solid #333; }
        .console-box { background: #000; color: #00ff00; font-family: monospace; font-size: 10px; height: 120px; overflow-y: auto; padding: 8px; border-radius: 4px; }
        
        .preview-container { background: var(--sidebar-bg); min-height: 100%; color: #a9b7d0; border-radius: 8px; padding-bottom: 20px; }
        .pcoded-navigatio-lavel { padding: 12px 20px; font-size: 10px; font-weight: bold; text-transform: uppercase; color: #8aa4af; border-bottom: 1px solid rgba(255,255,255,0.05); }
        .pcoded-hasmenu { display: flex; align-items: center; justify-content: space-between; transition: 0.2s; border-bottom: 1px solid rgba(255,255,255,0.02); }
        .pcoded-hasmenu:hover { background: rgba(255,255,255,0.05); }
        .pcoded-hasmenu a { padding: 8px 20px; display: block; color: #fff; text-decoration: none; flex-grow: 1; font-size: 13px; }
        
        .active-edit { background-color: #fff9c4 !important; border-left: 4px solid #fbc02d !important; }
        .order-btn { color: #8aa4af; cursor: pointer; padding: 2px 5px; font-size: 12px; opacity: 0.5; transition: 0.2s; }
        .order-btn:hover { color: #fff; opacity: 1; transform: scale(1.2); }

        ::-webkit-scrollbar { width: 5px; }
        ::-webkit-scrollbar-track { background: #f1f1f1; }
        ::-webkit-scrollbar-thumb { background: #ccc; border-radius: 10px; }
    </style>
</head>
<body>

<nav class="navbar navbar-dark bg-dark shadow-sm py-1">
    <div class="container-fluid">
        <span class="navbar-brand fs-6"><i class="fa fa-layer-group"></i> EDITOR MENU <small class="text-muted">v3.1</small></span>
        <div>
            <button class="btn btn-outline-light btn-sm me-2" onclick="loadData()"><i class="fa fa-sync"></i></button>
            <button class="btn btn-warning btn-sm fw-bold" onclick="saveData()" id="btnSave"><i class="fa fa-save"></i> GUARDAR</button>
        </div>
    </div>
</nav>

<div class="container-fluid">
    <div class="row">
        
        <div class="col-lg-3 column-scroll">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span>ESTRUCTURA (<span id="cnt">0</span>)</span>
                    <i class="fa fa-list-ol text-muted"></i>
                </div>
                <div class="list-group list-group-flush" id="list"></div>
            </div>
        </div>

        <div class="col-lg-6 column-scroll">
            <div class="card">
                <div class="card-header p-0">
                    <ul class="nav nav-tabs nav-fill" id="myTab">
                        <li class="nav-item"><button class="nav-link active py-2 small" data-bs-toggle="tab" data-bs-target="#tab1">GENERAL</button></li>
                        <li class="nav-item"><button class="nav-link py-2 small" data-bs-toggle="tab" data-bs-target="#tab2">DATOS JSON</button></li>
                    </ul>
                </div>
                <div class="card-body">
                    <form id="frm">
                        <input type="hidden" id="idx" value="-1">
                        <div class="tab-content">
                            <div class="tab-pane fade show active" id="tab1">
                                <div class="row g-2">
                                    <div class="col-md-3">
                                        <label class="small fw-bold">ID Grupo</label>
                                        <input type="number" class="form-control form-control-sm border-primary" id="iGrup" value="10">
                                    </div>
                                    <div class="col-md-9">
                                        <label class="small fw-bold">Agrupador (Nombre App/Categoría)</label>
                                        <input class="form-control form-control-sm" id="iApp" placeholder="Ej: Ventas, WEB, Config">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="small fw-bold">Nombre Menú</label>
                                        <input class="form-control form-control-sm fw-bold" id="iMenu">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="small fw-bold">Link (Archivo)</label>
                                        <input class="form-control form-control-sm text-primary" id="iLink">
                                    </div>
                                    <div class="col-md-12">
                                        <label class="small fw-bold">Icono</label>
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text bg-white"><i id="iPrev" class="fa fa-star"></i></span>
                                            <input class="form-control" id="iIcon" oninput="updIcon()" placeholder="fa fa-home">
                                        </div>
                                    </div>
                                    <div class="col-md-12">
                                        <label class="small fw-bold">Token Acceso</label>
                                        <input class="form-control form-control-sm" id="iTok" value="TKN_ACC">
                                    </div>
                                    <div class="col-md-12">
                                        <label class="small fw-bold">Descripción Corta</label>
                                        <input class="form-control form-control-sm" id="iDesc">
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="tab2">
                                <div class="mb-2">
                                    <label class="small fw-bold text-success">Configuración SQL</label>
                                    <textarea class="form-control code-editor" id="tSql" rows="3">{}</textarea>
                                </div>
                                <div class="mb-2">
                                    <label class="small fw-bold text-info">Lógica de Código</label>
                                    <textarea class="form-control code-editor" id="tCod" rows="3">{}</textarea>
                                </div>
                                <div>
                                    <label class="small fw-bold text-warning">Componentes UI</label>
                                    <textarea class="form-control code-editor" id="tCom" rows="3">{}</textarea>
                                </div>
                            </div>
                        </div>
                        <div class="mt-3 d-flex justify-content-between">
                            <button type="button" class="btn btn-sm btn-light border" onclick="resetFrm()">Limpiar</button>
                            <button type="button" class="btn btn-sm btn-primary px-4 fw-bold" onclick="addLocal()" id="btnAdd">AGREGAR ITEM</button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card bg-dark">
                <div class="card-header bg-dark text-white py-1 small border-secondary">SERVIDOR LOG</div>
                <div class="console-box" id="console"></div>
            </div>
        </div>

        <div class="col-lg-3 column-scroll">
            <h6 class="small fw-bold text-muted text-uppercase mb-2">Previsualización Sidebar</h6>
            <div class="preview-container shadow-sm">
                <div id="preview"></div>
            </div>
        </div>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    let data = [];
    window.onload = loadData;

    function log(msg, type='info') {
        const c = document.getElementById('console');
        const color = type === 'success' ? '#00ff00' : (type==='error'?'#ff4444':'#ffffff');
        c.innerHTML = `<div><span style="color:#888">[${new Date().toLocaleTimeString()}]</span> <span style="color:${color}">${msg}</span></div>` + c.innerHTML;
    }

    async function loadData() {
        try {
            const res = await fetch('?action=fetch');
            const json = await res.json();
            if(json.status === 'success') {
                data = json.data;
                render();
                log('Datos sincronizados correctamente.', 'success');
            }
        } catch (e) { log('Error de conexión al cargar.', 'error'); }
    }

    async function saveData() {
        const btn = document.getElementById('btnSave');
        btn.disabled = true; btn.innerHTML = 'GUARDANDO...';
        try {
            const res = await fetch('?action=save', {
                method:'POST', headers:{'Content-Type':'application/json'},
                body: JSON.stringify({menu: data})
            });
            const json = await res.json();
            if(json.status === 'success') {
                log('Base de Datos actualizada con éxito.', 'success');
                loadData(); // Recargamos para refrescar IDs
            }
        } catch (e) { log('Error al guardar en el servidor.', 'error'); }
        btn.disabled = false; btn.innerHTML = '<i class="fa fa-save"></i> GUARDAR';
    }

    function render() {
        // NO HACER SORT POR GRUPO EN JS. El orden viene del SQL (columna Orden).
        const l = document.getElementById('list'); l.innerHTML = '';
        const p = document.getElementById('preview'); p.innerHTML = '';
        document.getElementById('cnt').innerText = data.length;

        data.forEach((d, i) => {
            const isEdit = parseInt(document.getElementById('idx').value) === i ? 'active-edit' : '';
            l.innerHTML += `
            <div class="list-group-item p-2 d-flex justify-content-between align-items-center ${isEdit}" style="cursor:pointer" onclick="edit(${i})">
                <div class="text-truncate" style="font-size:12px">
                    <span class="badge bg-light text-dark border me-1">${d.Grupo}</span>
                    <i class="${d.Icono || 'fa fa-circle'} text-muted me-1"></i>
                    <strong>${d.NombreMenu}</strong>
                </div>
                <button class="btn btn-sm py-0 text-danger" onclick="del(event,${i})">&times;</button>
            </div>`;
        });

        // Agrupación visual para la previsualización
        const grouped = [];
        let currentGroupName = "";
        let currentGroupObj = null;

        data.forEach((item, idx) => {
            if (item.NombreGrupo !== currentGroupName) {
                currentGroupName = item.NombreGrupo;
                currentGroupObj = { name: currentGroupName, gID: item.Grupo, items: [] };
                grouped.push(currentGroupObj);
            }
            item._idx = idx;
            currentGroupObj.items.push(item);
        });

        grouped.forEach(group => {
            let h = `<div class="pcoded-navigatio-lavel">${group.name} <span class="float-end opacity-50">#${group.gID}</span></div><ul class="list-unstyled mb-0">`;
            group.items.forEach(item => {
                h += `
                <li class="pcoded-hasmenu">
                    <a href="javascript:void(0)"><i class="${item.Icono} me-2" style="font-size:11px"></i>${item.NombreMenu}</a>
                    <div class="d-flex flex-column pe-2">
                         <i class="fa fa-chevron-up order-btn" onclick="moveItem(${item._idx}, -1)"></i>
                         <i class="fa fa-chevron-down order-btn" onclick="moveItem(${item._idx}, 1)"></i>
                    </div>
                </li>`;
            });
            h += `</ul>`;
            p.innerHTML += h;
        });
    }

    // FUNCIÓN CORREGIDA: Intercambia posiciones en el array de datos
    function moveItem(index, dir) {
        const target = index + dir;
        if (target >= 0 && target < data.length) {
            const temp = data[index];
            data[index] = data[target];
            data[target] = temp;
            render();
            log('Posición cambiada localmente. Pendiente guardar.');
        }
    }

    function addLocal() {
        const i = document.getElementById('idx').value;
        const obj = {
            Grupo: parseInt(document.getElementById('iGrup').value || 0),
            NombreGrupo: document.getElementById('iApp').value,
            NombreMenu: document.getElementById('iMenu').value,
            Descripcion: document.getElementById('iDesc').value,
            Link: document.getElementById('iLink').value,
            Icono: document.getElementById('iIcon').value,
            Token: document.getElementById('iTok').value,
            Datos_Mysql: document.getElementById('tSql').value,
            Datos_Codigo: document.getElementById('tCod').value,
            Datos_Componentes: document.getElementById('tCom').value
        };

        if(i == -1) data.push(obj); else data[i] = obj;
        resetFrm();
        log('Cambios aplicados a la lista.');
    }

    function edit(i) {
        const d = data[i];
        document.getElementById('idx').value = i;
        document.getElementById('iGrup').value = d.Grupo;
        document.getElementById('iApp').value = d.NombreGrupo;
        document.getElementById('iMenu').value = d.NombreMenu;
        document.getElementById('iDesc').value = d.Descripcion;
        document.getElementById('iLink').value = d.Link;
        document.getElementById('iIcon').value = d.Icono;
        document.getElementById('iTok').value = d.Token;
        document.getElementById('tSql').value = d.Datos_Mysql;
        document.getElementById('tCod').value = d.Datos_Codigo;
        document.getElementById('tCom').value = d.Datos_Componentes;
        updIcon();
        render();
        document.getElementById('btnAdd').innerHTML = "ACTUALIZAR ITEM";
        document.getElementById('btnAdd').className = "btn btn-sm btn-success px-4 fw-bold";
    }

    function del(e, i) {
        e.stopPropagation();
        if(confirm('¿Eliminar este menú permanentemente de la lista?')) { 
            data.splice(i,1); 
            render(); 
        }
    }

    function resetFrm() {
        document.getElementById('frm').reset();
        document.getElementById('idx').value = -1;
        document.getElementById('btnAdd').innerHTML = "AGREGAR ITEM";
        document.getElementById('btnAdd').className = "btn btn-sm btn-primary px-4 fw-bold";
        updIcon();
        render();
    }

    function updIcon() {
        document.getElementById('iPrev').className = document.getElementById('iIcon').value || 'fa fa-star';
    }
</script>
</body>
</html>