<?php
// pages/gestionar_categorias.php

$error_message = null;
$success_message = null;
$current_role = $_SESSION['user_role'];

// Solo admin y editor pueden gestionar categorías
if (!in_array($current_role, ['admin', 'editor'])) {
    header('Location: index.php');
    exit;
}

// Recuperar mensaje de sesión
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}
if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}

// Obtener datos
$categorias1 = [];
$categorias2 = [];
$mapeos = [];
$grupos_axapta = [];
$tab = $_GET['tab'] ?? 'mapeo';

try {
    // Obtener grupos de Axapta desde la base de datos
    $stmt = $pdo->query("SELECT * FROM grupos_axapta WHERE activo = 1 ORDER BY codigo");
    $grupos_axapta = $stmt->fetchAll();
    
    // Obtener todos los grupos (incluyendo inactivos) para la pestaña de grupos
    $stmt = $pdo->query("SELECT ga.*, COUNT(cm.id) as mapeos_count 
                        FROM grupos_axapta ga 
                        LEFT JOIN categoria_mapping cm ON ga.codigo COLLATE utf8mb4_0900_ai_ci = cm.grupo_articulo COLLATE utf8mb4_0900_ai_ci
                        GROUP BY ga.id 
                        ORDER BY ga.codigo");
    $todos_grupos_axapta = $stmt->fetchAll();
    
    // Obtener categorías nivel 1
    $stmt = $pdo->query("SELECT * FROM categorias_nivel1 ORDER BY orden, nombre");
    $categorias1 = $stmt->fetchAll();
    
    // Obtener categorías nivel 2 con su categoría padre
    $stmt = $pdo->query("
        SELECT c2.*, c1.nombre as categoria1_nombre 
        FROM categorias_nivel2 c2 
        JOIN categorias_nivel1 c1 ON c2.categoria1_id = c1.id 
        ORDER BY c1.orden, c1.nombre, c2.orden, c2.nombre
    ");
    $categorias2 = $stmt->fetchAll();
    
    // Obtener mapeos con nombres de categorías
    $stmt = $pdo->query("
        SELECT cm.*, 
               c1.nombre as categoria1_nombre,
               c2.nombre as categoria2_nombre,
               COUNT(DISTINCT rd.referencia) as productos_count
        FROM categoria_mapping cm
        LEFT JOIN categorias_nivel1 c1 ON cm.categoria1_id = c1.id
        LEFT JOIN categorias_nivel2 c2 ON cm.categoria2_id = c2.id
        LEFT JOIN references_data rd ON rd.grupo_articulo = cm.grupo_articulo
        GROUP BY cm.id
        ORDER BY cm.grupo_articulo
    ");
    $mapeos = $stmt->fetchAll();
    
} catch (PDOException $e) {
    $error_message = "Error al cargar datos: " . $e->getMessage();
}

// Obtener grupos sin mapear
$grupos_mapeados = array_column($mapeos, 'grupo_articulo');
$grupos_disponibles = array_column($grupos_axapta, 'codigo');
$grupos_sin_mapear = array_diff($grupos_disponibles, $grupos_mapeados);
?>

<div class="space-y-6">
    <!-- Header -->
    <div class="bg-gradient-to-r from-indigo-600 to-purple-700 rounded-xl p-6 text-white shadow-xl">
        <div class="flex items-center justify-between">
            <div class="flex items-center gap-4">
                <div class="bg-white/20 backdrop-blur p-4 rounded-lg">
                    <i class="fas fa-tags fa-3x"></i>
                </div>
                <div>
                    <h1 class="text-3xl font-bold">Gestión de Categorías</h1>
                    <p class="text-indigo-100 mt-1">Administra categorías y mapeo de grupos de Axapta</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Mensajes -->
    <?php if ($error_message): ?>
        <div class="bg-red-50 border-l-4 border-red-500 p-4 rounded-lg shadow-md animate-fade-in">
            <div class="flex items-center">
                <div class="bg-red-500 text-white rounded-full p-2 mr-3">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <div><?php echo htmlspecialchars($error_message); ?></div>
            </div>
        </div>
    <?php endif; ?>
    
    <?php if ($success_message): ?>
        <div class="bg-green-50 border-l-4 border-green-500 p-4 rounded-lg shadow-md animate-fade-in">
            <div class="flex items-center">
                <div class="bg-green-500 text-white rounded-full p-2 mr-3">
                    <i class="fas fa-check"></i>
                </div>
                <div>
                    <p class="font-bold text-green-800">Operación Exitosa</p>
                    <p class="text-green-700"><?php echo htmlspecialchars($success_message); ?></p>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- Logs de sincronización -->
    <?php if (isset($_SESSION['sync_logs'])): ?>
        <?php $sync_logs = $_SESSION['sync_logs']; unset($_SESSION['sync_logs']); ?>
        <div class="bg-gray-900 rounded-xl shadow-lg overflow-hidden animate-slide-up">
            <div class="bg-gray-800 px-6 py-3 flex items-center justify-between">
                <h3 class="text-white font-semibold flex items-center">
                    <i class="fas fa-sync mr-2"></i>Log de Sincronización
                </h3>
                <button onclick="this.parentElement.parentElement.style.display='none'" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-4 max-h-48 overflow-y-auto font-mono text-sm">
                <?php foreach ($sync_logs as $msg): ?>
                    <p class="mb-1 <?php
                        if (strpos($msg, '[SUCCESS]') !== false) echo 'text-green-300 font-bold';
                        elseif (strpos($msg, '[STATS]') !== false) echo 'text-blue-400';
                        elseif (strpos($msg, '[PROGRESS]') !== false) echo 'text-yellow-400';
                        elseif (strpos($msg, '[ERROR]') !== false) echo 'text-red-400';
                        else echo 'text-gray-300';
                    ?>"><?php echo htmlspecialchars($msg); ?></p>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>

    <!-- Tabs -->
    <div class="bg-white rounded-lg shadow-md">
        <div class="border-b">
            <nav class="flex -mb-px">
                <a href="?page=gestionar_categorias&tab=mapeo" 
                   class="py-3 px-6 <?php echo $tab === 'mapeo' ? 'border-b-2 border-indigo-500 text-indigo-600' : 'text-gray-500 hover:text-gray-700'; ?>">
                    <i class="fas fa-map mr-2"></i>Mapeo de Grupos
                </a>
                <a href="?page=gestionar_categorias&tab=grupos" 
                   class="py-3 px-6 <?php echo $tab === 'grupos' ? 'border-b-2 border-indigo-500 text-indigo-600' : 'text-gray-500 hover:text-gray-700'; ?>">
                    <i class="fas fa-cubes mr-2"></i>Grupos de Axapta
                </a>
                <a href="?page=gestionar_categorias&tab=cat1" 
                   class="py-3 px-6 <?php echo $tab === 'cat1' ? 'border-b-2 border-indigo-500 text-indigo-600' : 'text-gray-500 hover:text-gray-700'; ?>">
                    <i class="fas fa-folder mr-2"></i>Categorías Principales
                </a>
                <a href="?page=gestionar_categorias&tab=cat2" 
                   class="py-3 px-6 <?php echo $tab === 'cat2' ? 'border-b-2 border-indigo-500 text-indigo-600' : 'text-gray-500 hover:text-gray-700'; ?>">
                    <i class="fas fa-folder-open mr-2"></i>Subcategorías
                </a>
            </nav>
        </div>

        <!-- Contenido según tab -->
        <?php if ($tab === 'grupos'): ?>
            <!-- Tab de Grupos de Axapta -->
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-lg font-semibold">Grupos de Axapta</h2>
                    <button onclick="openModal('create-grupo-modal')" 
                            class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700">
                        <i class="fas fa-plus mr-2"></i>Nuevo Grupo
                    </button>
                </div>

                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-100">
                            <tr>
                                <th class="p-3 text-left font-semibold text-gray-600">Código</th>
                                <th class="p-3 text-left font-semibold text-gray-600">Descripción</th>
                                <th class="p-3 text-center font-semibold text-gray-600">Mapeos</th>
                                <th class="p-3 text-center font-semibold text-gray-600">Estado</th>
                                <th class="p-3 text-right font-semibold text-gray-600">Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($todos_grupos_axapta)): ?>
                                <tr>
                                    <td colspan="5" class="text-center p-8 text-gray-500">
                                        No hay grupos configurados
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($todos_grupos_axapta as $grupo): ?>
                                    <tr class="border-b hover:bg-gray-50">
                                        <td class="p-3">
                                            <span class="font-mono font-semibold text-indigo-600">
                                                <?php echo htmlspecialchars($grupo['codigo']); ?>
                                            </span>
                                        </td>
                                        <td class="p-3">
                                            <?php echo htmlspecialchars($grupo['descripcion'] ?? '-'); ?>
                                        </td>
                                        <td class="p-3 text-center">
                                            <span class="text-gray-600">
                                                <?php echo $grupo['mapeos_count']; ?>
                                            </span>
                                        </td>
                                        <td class="p-3 text-center">
                                            <?php if ($grupo['activo']): ?>
                                                <span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs font-semibold">
                                                    Activo
                                                </span>
                                            <?php else: ?>
                                                <span class="px-2 py-1 bg-gray-100 text-gray-500 rounded-full text-xs font-semibold">
                                                    Inactivo
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="p-3">
                                            <div class="flex justify-end gap-2">
                                                <button onclick="openEditGrupoModal(<?php echo htmlspecialchars(json_encode($grupo)); ?>)" 
                                                        class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600 transition">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <?php if ($current_role === 'admin' && $grupo['mapeos_count'] == 0): ?>
                                                    <button onclick="openDeleteModal('grupo', <?php echo $grupo['id']; ?>, '<?php echo htmlspecialchars($grupo['codigo']); ?>')" 
                                                            class="bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600 transition">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        <?php elseif ($tab === 'mapeo'): ?>
            <!-- Tab de Mapeo -->
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-lg font-semibold">Mapeo de Grupos a Categorías</h2>
                    <div class="flex gap-2">
                        <button onclick="openModal('sync-modal')" 
                                class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 flex items-center">
                            <i class="fas fa-sync mr-2"></i>Sincronizar Productos
                        </button>
                        <button onclick="openModal('create-mapping-modal')" 
                                class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700">
                            <i class="fas fa-plus mr-2"></i>Nuevo Mapeo
                        </button>
                    </div>
                </div>

                <?php if (count($grupos_sin_mapear) > 0): ?>
                    <div class="bg-amber-50 border border-amber-200 rounded-lg p-4 mb-4">
                        <h4 class="font-semibold text-amber-800 mb-2">
                            <i class="fas fa-exclamation-triangle mr-2"></i>
                            Grupos sin mapear (<?php echo count($grupos_sin_mapear); ?>)
                        </h4>
                        <div class="text-xs text-amber-700 max-h-20 overflow-y-auto">
                            <?php echo implode(', ', array_slice($grupos_sin_mapear, 0, 50)); ?>
                            <?php if (count($grupos_sin_mapear) > 50): ?>
                                ... y <?php echo count($grupos_sin_mapear) - 50; ?> más
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-100">
                            <tr>
                                <th class="p-3 text-left font-semibold text-gray-600">Grupo Axapta</th>
                                <th class="p-3 text-left font-semibold text-gray-600">Categoría Principal</th>
                                <th class="p-3 text-left font-semibold text-gray-600">Subcategoría</th>
                                <th class="p-3 text-center font-semibold text-gray-600">Productos</th>
                                <th class="p-3 text-center font-semibold text-gray-600">Estado</th>
                                <th class="p-3 text-right font-semibold text-gray-600">Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($mapeos)): ?>
                                <tr>
                                    <td colspan="6" class="text-center p-8 text-gray-500">
                                        No hay mapeos configurados
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($mapeos as $mapeo): ?>
                                    <tr class="border-b hover:bg-gray-50">
                                        <td class="p-3">
                                            <span class="font-mono font-semibold text-indigo-600">
                                                <?php echo htmlspecialchars($mapeo['grupo_articulo']); ?>
                                            </span>
                                        </td>
                                        <td class="p-3">
                                            <span class="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm">
                                                <?php echo htmlspecialchars($mapeo['categoria1_nombre'] ?? 'Sin categoría'); ?>
                                            </span>
                                        </td>
                                        <td class="p-3">
                                            <span class="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-sm">
                                                <?php echo htmlspecialchars($mapeo['categoria2_nombre'] ?? 'Sin subcategoría'); ?>
                                            </span>
                                        </td>
                                        <td class="p-3 text-center">
                                            <div class="flex items-center justify-center gap-2">
                                                <span class="text-lg font-semibold text-gray-800"><?php echo $mapeo['productos_count']; ?></span>
                                                <?php if ($mapeo['productos_count'] > 0): ?>
                                                    <form method="POST" action="index.php?page=gestionar_categorias" class="inline-block">
                                                        <input type="hidden" name="action" value="sync_group_products">
                                                        <input type="hidden" name="grupo_articulo" value="<?php echo htmlspecialchars($mapeo['grupo_articulo']); ?>">
                                                        <input type="hidden" name="current_tab" value="mapeo">
                                                        <button type="submit" 
                                                                class="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded hover:bg-blue-200 transition"
                                                                title="Sincronizar solo este grupo"
                                                                onclick="this.innerHTML='<i class=\'fas fa-spinner fa-spin\'></i>'; this.disabled=true; this.form.submit();">
                                                            <i class="fas fa-sync"></i>
                                                        </button>
                                                    </form>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td class="p-3 text-center">
                                            <?php if ($mapeo['activo']): ?>
                                                <span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs font-semibold">
                                                    Activo
                                                </span>
                                            <?php else: ?>
                                                <span class="px-2 py-1 bg-gray-100 text-gray-500 rounded-full text-xs font-semibold">
                                                    Inactivo
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="p-3">
                                            <div class="flex justify-end gap-2">
                                                <button onclick="openEditMappingModal(<?php echo htmlspecialchars(json_encode($mapeo)); ?>)" 
                                                        class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600 transition">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <?php if ($current_role === 'admin'): ?>
                                                    <button onclick="openDeleteModal('mapping', <?php echo $mapeo['id']; ?>, '<?php echo htmlspecialchars($mapeo['grupo_articulo']); ?>')" 
                                                            class="bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600 transition">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        <?php elseif ($tab === 'cat1'): ?>
            <!-- Tab de Categorías Principales -->
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-lg font-semibold">Categorías Principales</h2>
                    <button onclick="openModal('create-cat1-modal')" 
                            class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700">
                        <i class="fas fa-plus mr-2"></i>Nueva Categoría
                    </button>
                </div>

                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-100">
                            <tr>
                                <th class="p-3 text-left font-semibold text-gray-600">Nombre</th>
                                <th class="p-3 text-center font-semibold text-gray-600">Orden</th>
                                <th class="p-3 text-center font-semibold text-gray-600">Subcategorías</th>
                                <th class="p-3 text-center font-semibold text-gray-600">Estado</th>
                                <th class="p-3 text-right font-semibold text-gray-600">Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($categorias1 as $cat): ?>
                                <?php 
                                $subcats_count = count(array_filter($categorias2, function($c) use ($cat) { 
                                    return $c['categoria1_id'] == $cat['id']; 
                                }));
                                ?>
                                <tr class="border-b hover:bg-gray-50">
                                    <td class="p-3">
                                        <span class="font-semibold">
                                            <?php echo htmlspecialchars($cat['nombre']); ?>
                                        </span>
                                    </td>
                                    <td class="p-3 text-center">
                                        <?php echo $cat['orden']; ?>
                                    </td>
                                    <td class="p-3 text-center">
                                        <span class="text-gray-600">
                                            <?php echo $subcats_count; ?>
                                        </span>
                                    </td>
                                    <td class="p-3 text-center">
                                        <?php if ($cat['activo']): ?>
                                            <span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs font-semibold">
                                                Activo
                                            </span>
                                        <?php else: ?>
                                            <span class="px-2 py-1 bg-gray-100 text-gray-500 rounded-full text-xs font-semibold">
                                                Inactivo
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-3">
                                        <div class="flex justify-end gap-2">
                                            <button onclick="openEditCat1Modal(<?php echo htmlspecialchars(json_encode($cat)); ?>)" 
                                                    class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600 transition">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <?php if ($current_role === 'admin' && $subcats_count == 0): ?>
                                                <button onclick="openDeleteModal('cat1', <?php echo $cat['id']; ?>, '<?php echo htmlspecialchars($cat['nombre']); ?>')" 
                                                        class="bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600 transition">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        <?php elseif ($tab === 'cat2'): ?>
            <!-- Tab de Subcategorías -->
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-lg font-semibold">Subcategorías</h2>
                    <button onclick="openModal('create-cat2-modal')" 
                            class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700">
                        <i class="fas fa-plus mr-2"></i>Nueva Subcategoría
                    </button>
                </div>

                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-100">
                            <tr>
                                <th class="p-3 text-left font-semibold text-gray-600">Categoría Principal</th>
                                <th class="p-3 text-left font-semibold text-gray-600">Subcategoría</th>
                                <th class="p-3 text-center font-semibold text-gray-600">Orden</th>
                                <th class="p-3 text-center font-semibold text-gray-600">Estado</th>
                                <th class="p-3 text-right font-semibold text-gray-600">Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($categorias2 as $cat): ?>
                                <tr class="border-b hover:bg-gray-50">
                                    <td class="p-3">
                                        <span class="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm">
                                            <?php echo htmlspecialchars($cat['categoria1_nombre']); ?>
                                        </span>
                                    </td>
                                    <td class="p-3">
                                        <span class="font-semibold">
                                            <?php echo htmlspecialchars($cat['nombre']); ?>
                                        </span>
                                    </td>
                                    <td class="p-3 text-center">
                                        <?php echo $cat['orden']; ?>
                                    </td>
                                    <td class="p-3 text-center">
                                        <?php if ($cat['activo']): ?>
                                            <span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs font-semibold">
                                                Activo
                                            </span>
                                        <?php else: ?>
                                            <span class="px-2 py-1 bg-gray-100 text-gray-500 rounded-full text-xs font-semibold">
                                                Inactivo
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-3">
                                        <div class="flex justify-end gap-2">
                                            <button onclick="openEditCat2Modal(<?php echo htmlspecialchars(json_encode($cat)); ?>)" 
                                                    class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600 transition">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <?php if ($current_role === 'admin'): ?>
                                                <button onclick="openDeleteModal('cat2', <?php echo $cat['id']; ?>, '<?php echo htmlspecialchars($cat['nombre']); ?>')" 
                                                        class="bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600 transition">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Modal de Sincronización -->
<div id="sync-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-2xl p-6">
        <div class="flex items-center justify-between mb-6">
            <div>
                <h2 class="text-2xl font-bold text-gray-800">Sincronizar Categorías de Productos</h2>
                <p class="text-gray-600 mt-1">Actualiza las categorías de todos los productos según los mapeos configurados</p>
            </div>
            <button onclick="closeModal('sync-modal')" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
            <h4 class="font-semibold text-blue-800 mb-2">
                <i class="fas fa-info-circle mr-2"></i>¿Qué hace la sincronización?
            </h4>
            <ul class="text-sm text-blue-700 space-y-1">
                <li>• Actualiza las categorías de todos los productos según su grupo de artículo</li>
                <li>• Aplica los mapeos configurados en esta página</li>
                <li>• Productos sin mapeo quedan con categorías "Otros" y "General"</li>
                <li>• Es útil después de importar productos o cambiar mapeos</li>
            </ul>
        </div>
        
        <div class="bg-amber-50 border border-amber-200 rounded-lg p-4 mb-6">
            <h4 class="font-semibold text-amber-800 mb-2">
                <i class="fas fa-exclamation-triangle mr-2"></i>Importante
            </h4>
            <ul class="text-sm text-amber-700 space-y-1">
                <li>• Este proceso puede tardar varios minutos si hay muchos productos</li>
                <li>• Se sobrescribirán las categorías actuales de los productos</li>
                <li>• Solo se actualizan productos que tienen grupo de artículo definido</li>
            </ul>
        </div>
        
        <form method="POST" action="index.php?page=gestionar_categorias">
            <input type="hidden" name="action" value="sync_all_categories">
            <input type="hidden" name="current_tab" value="mapeo">
            
            <div class="flex justify-end gap-4">
                <button type="button" onclick="closeModal('sync-modal')" 
                        class="px-6 py-3 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 font-semibold">
                    Cancelar
                </button>
                <button type="submit" 
                        class="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 font-semibold"
                        onclick="this.innerHTML='<i class=\'fas fa-spinner fa-spin mr-2\'></i>Sincronizando...'; this.disabled=true; this.form.submit();">
                    <i class="fas fa-sync mr-2"></i>Iniciar Sincronización
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Modales para Grupos de Axapta -->
<div id="create-grupo-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md p-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Nuevo Grupo de Axapta</h2>
        <form method="POST" action="index.php?page=gestionar_categorias">
            <input type="hidden" name="action" value="create_grupo">
            <input type="hidden" name="current_tab" value="grupos">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Código</label>
                    <input type="text" name="codigo" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" 
                           required pattern="[A-Za-z0-9]+" title="Solo letras y números">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Descripción (opcional)</label>
                    <input type="text" name="descripcion" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
            </div>
            <div class="flex justify-end gap-4 mt-6 pt-6 border-t">
                <button type="button" onclick="closeModal('create-grupo-modal')" 
                        class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
                    Cancelar
                </button>
                <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">
                    Crear Grupo
                </button>
            </div>
        </form>
    </div>
</div>

<div id="edit-grupo-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md p-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Editar Grupo de Axapta</h2>
        <form method="POST" action="index.php?page=gestionar_categorias">
            <input type="hidden" name="action" value="update_grupo">
            <input type="hidden" name="current_tab" value="grupos">
            <input type="hidden" name="id" id="edit-grupo-id">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Código</label>
                    <input type="text" name="codigo" id="edit-grupo-codigo" 
                           class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" 
                           required pattern="[A-Za-z0-9]+" title="Solo letras y números">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Descripción (opcional)</label>
                    <input type="text" name="descripcion" id="edit-grupo-descripcion" 
                           class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
                <div>
                    <label class="flex items-center">
                        <input type="checkbox" name="activo" id="edit-grupo-activo" class="mr-2">
                        <span class="text-sm font-medium text-gray-700">Activo</span>
                    </label>
                </div>
            </div>
            <div class="flex justify-end gap-4 mt-6 pt-6 border-t">
                <button type="button" onclick="closeModal('edit-grupo-modal')" 
                        class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
                    Cancelar
                </button>
                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                    Guardar Cambios
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Modales para Mapeo -->
<div id="create-mapping-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md p-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Nuevo Mapeo</h2>
        <form method="POST" action="index.php?page=gestionar_categorias">
            <input type="hidden" name="action" value="create_mapping">
            <input type="hidden" name="current_tab" value="mapeo">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Grupo de Artículo (Axapta)</label>
                    <select name="grupo_articulo" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" required>
                        <option value="">Seleccionar...</option>
                        <?php foreach ($grupos_sin_mapear as $grupo): ?>
                            <option value="<?php echo htmlspecialchars($grupo); ?>">
                                <?php echo htmlspecialchars($grupo); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Categoría Principal</label>
                    <select name="categoria1_id" id="new-cat1-select" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" required>
                        <option value="">Seleccionar...</option>
                        <?php foreach ($categorias1 as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>">
                                <?php echo htmlspecialchars($cat['nombre']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Subcategoría</label>
                    <select name="categoria2_id" id="new-cat2-select" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                        <option value="">Seleccionar primero una categoría principal</option>
                    </select>
                </div>
            </div>
            <div class="flex justify-end gap-4 mt-6 pt-6 border-t">
                <button type="button" onclick="closeModal('create-mapping-modal')" 
                        class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
                    Cancelar
                </button>
                <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">
                    Crear Mapeo
                </button>
            </div>
        </form>
    </div>
</div>

<div id="edit-mapping-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md p-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Editar Mapeo</h2>
        <form method="POST" action="index.php?page=gestionar_categorias">
            <input type="hidden" name="action" value="update_mapping">
            <input type="hidden" name="current_tab" value="mapeo">
            <input type="hidden" name="id" id="edit-mapping-id">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Grupo de Artículo (Axapta)</label>
                    <input type="text" name="grupo_articulo" id="edit-mapping-grupo" 
                           class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Categoría Principal</label>
                    <select name="categoria1_id" id="edit-cat1-select" 
                            class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" required>
                        <?php foreach ($categorias1 as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>">
                                <?php echo htmlspecialchars($cat['nombre']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Subcategoría</label>
                    <select name="categoria2_id" id="edit-cat2-select" 
                            class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                        <option value="">Sin subcategoría</option>
                    </select>
                </div>
                <div>
                    <label class="flex items-center">
                        <input type="checkbox" name="activo" id="edit-mapping-activo" class="mr-2">
                        <span class="text-sm font-medium text-gray-700">Activo</span>
                    </label>
                </div>
            </div>
            <div class="flex justify-end gap-4 mt-6 pt-6 border-t">
                <button type="button" onclick="closeModal('edit-mapping-modal')" 
                        class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
                    Cancelar
                </button>
                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                    Guardar Cambios
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Modales para Categorías Nivel 1 -->
<div id="create-cat1-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md p-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Nueva Categoría Principal</h2>
        <form method="POST" action="index.php?page=gestionar_categorias">
            <input type="hidden" name="action" value="create_cat1">
            <input type="hidden" name="current_tab" value="cat1">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Nombre</label>
                    <input type="text" name="nombre" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Orden</label>
                    <input type="number" name="orden" value="99" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
            </div>
            <div class="flex justify-end gap-4 mt-6 pt-6 border-t">
                <button type="button" onclick="closeModal('create-cat1-modal')" 
                        class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
                    Cancelar
                </button>
                <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">
                    Crear Categoría
                </button>
            </div>
        </form>
    </div>
</div>

<div id="edit-cat1-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md p-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Editar Categoría Principal</h2>
        <form method="POST" action="index.php?page=gestionar_categorias">
            <input type="hidden" name="action" value="update_cat1">
            <input type="hidden" name="current_tab" value="cat1">
            <input type="hidden" name="id" id="edit-cat1-id">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Nombre</label>
                    <input type="text" name="nombre" id="edit-cat1-nombre" 
                           class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Orden</label>
                    <input type="number" name="orden" id="edit-cat1-orden" 
                           class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
                <div>
                    <label class="flex items-center">
                        <input type="checkbox" name="activo" id="edit-cat1-activo" class="mr-2">
                        <span class="text-sm font-medium text-gray-700">Activo</span>
                    </label>
                </div>
            </div>
            <div class="flex justify-end gap-4 mt-6 pt-6 border-t">
                <button type="button" onclick="closeModal('edit-cat1-modal')" 
                        class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
                    Cancelar
                </button>
                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                    Guardar Cambios
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Modales para Categorías Nivel 2 -->
<div id="create-cat2-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md p-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Nueva Subcategoría</h2>
        <form method="POST" action="index.php?page=gestionar_categorias">
            <input type="hidden" name="action" value="create_cat2">
            <input type="hidden" name="current_tab" value="cat2">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Categoría Principal</label>
                    <select name="categoria1_id" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" required>
                        <option value="">Seleccionar...</option>
                        <?php foreach ($categorias1 as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>">
                                <?php echo htmlspecialchars($cat['nombre']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Nombre</label>
                    <input type="text" name="nombre" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Orden</label>
                    <input type="number" name="orden" value="99" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
            </div>
            <div class="flex justify-end gap-4 mt-6 pt-6 border-t">
                <button type="button" onclick="closeModal('create-cat2-modal')" 
                        class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
                    Cancelar
                </button>
                <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">
                    Crear Subcategoría
                </button>
            </div>
        </form>
    </div>
</div>

<div id="edit-cat2-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md p-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Editar Subcategoría</h2>
        <form method="POST" action="index.php?page=gestionar_categorias">
            <input type="hidden" name="action" value="update_cat2">
            <input type="hidden" name="current_tab" value="cat2">
            <input type="hidden" name="id" id="edit-cat2-id">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Categoría Principal</label>
                    <select name="categoria1_id" id="edit-cat2-cat1" 
                            class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" required>
                        <?php foreach ($categorias1 as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>">
                                <?php echo htmlspecialchars($cat['nombre']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Nombre</label>
                    <input type="text" name="nombre" id="edit-cat2-nombre" 
                           class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Orden</label>
                    <input type="number" name="orden" id="edit-cat2-orden" 
                           class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
                <div>
                    <label class="flex items-center">
                        <input type="checkbox" name="activo" id="edit-cat2-activo" class="mr-2">
                        <span class="text-sm font-medium text-gray-700">Activo</span>
                    </label>
                </div>
            </div>
            <div class="flex justify-end gap-4 mt-6 pt-6 border-t">
                <button type="button" onclick="closeModal('edit-cat2-modal')" 
                        class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
                    Cancelar
                </button>
                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                    Guardar Cambios
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Modal de Eliminación General -->
<div id="delete-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md p-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Confirmar Eliminación</h2>
        <p class="text-gray-600 mb-6">
            ¿Estás seguro de que deseas eliminar <strong id="delete-item-name"></strong>?
        </p>
        <form method="POST" action="index.php?page=gestionar_categorias" id="delete-form">
            <input type="hidden" name="action" id="delete-action">
            <input type="hidden" name="current_tab" id="delete-tab">
            <input type="hidden" name="id" id="delete-id">
            <div class="flex justify-end gap-4">
                <button type="button" onclick="closeModal('delete-modal')" 
                        class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
                    Cancelar
                </button>
                <button type="submit" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700">
                    Eliminar
                </button>
            </div>
        </form>
    </div>
</div>

<script>
// Datos de categorías para JavaScript
const categorias2Data = <?php echo json_encode($categorias2); ?>;

function openModal(modalId) {
    document.getElementById(modalId).classList.remove('hidden');
}

function closeModal(modalId) {
    document.getElementById(modalId).classList.add('hidden');
}

function openEditGrupoModal(grupo) {
    document.getElementById('edit-grupo-id').value = grupo.id;
    document.getElementById('edit-grupo-codigo').value = grupo.codigo;
    document.getElementById('edit-grupo-descripcion').value = grupo.descripcion || '';
    document.getElementById('edit-grupo-activo').checked = grupo.activo == 1;
    openModal('edit-grupo-modal');
}

function openEditMappingModal(mapeo) {
    document.getElementById('edit-mapping-id').value = mapeo.id;
    document.getElementById('edit-mapping-grupo').value = mapeo.grupo_articulo;
    document.getElementById('edit-cat1-select').value = mapeo.categoria1_id || '';
    document.getElementById('edit-mapping-activo').checked = mapeo.activo == 1;
    
    // Cargar subcategorías
    updateSubcategorias('edit-cat1-select', 'edit-cat2-select', mapeo.categoria2_id);
    
    openModal('edit-mapping-modal');
}

function openEditCat1Modal(cat) {
    document.getElementById('edit-cat1-id').value = cat.id;
    document.getElementById('edit-cat1-nombre').value = cat.nombre;
    document.getElementById('edit-cat1-orden').value = cat.orden;
    document.getElementById('edit-cat1-activo').checked = cat.activo == 1;
    openModal('edit-cat1-modal');
}

function openEditCat2Modal(cat) {
    document.getElementById('edit-cat2-id').value = cat.id;
    document.getElementById('edit-cat2-cat1').value = cat.categoria1_id;
    document.getElementById('edit-cat2-nombre').value = cat.nombre;
    document.getElementById('edit-cat2-orden').value = cat.orden;
    document.getElementById('edit-cat2-activo').checked = cat.activo == 1;
    openModal('edit-cat2-modal');
}

function openDeleteModal(type, id, name) {
    document.getElementById('delete-item-name').textContent = name;
    document.getElementById('delete-id').value = id;
    
    const actionMap = {
        'grupo': 'delete_grupo',
        'mapping': 'delete_mapping',
        'cat1': 'delete_cat1',
        'cat2': 'delete_cat2'
    };
    
    const tabMap = {
        'grupo': 'grupos',
        'mapping': 'mapeo',
        'cat1': 'cat1',
        'cat2': 'cat2'
    };
    
    document.getElementById('delete-action').value = actionMap[type];
    document.getElementById('delete-tab').value = tabMap[type];
    
    openModal('delete-modal');
}

function updateSubcategorias(cat1SelectId, cat2SelectId, selectedCat2Id = null) {
    const cat1Select = document.getElementById(cat1SelectId);
    const cat2Select = document.getElementById(cat2SelectId);
    const selectedCat1 = cat1Select.value;
    
    // Limpiar subcategorías
    cat2Select.innerHTML = '<option value="">Sin subcategoría</option>';
    
    if (selectedCat1) {
        // Filtrar subcategorías para la categoría seleccionada
        const subcats = categorias2Data.filter(c => c.categoria1_id == selectedCat1);
        
        subcats.forEach(subcat => {
            const option = document.createElement('option');
            option.value = subcat.id;
            option.textContent = subcat.nombre;
            if (selectedCat2Id && subcat.id == selectedCat2Id) {
                option.selected = true;
            }
            cat2Select.appendChild(option);
        });
    }
}

// Event listeners para actualizar subcategorías cuando cambia la categoría principal
document.getElementById('new-cat1-select').addEventListener('change', function() {
    updateSubcategorias('new-cat1-select', 'new-cat2-select');
});

document.getElementById('edit-cat1-select').addEventListener('change', function() {
    updateSubcategorias('edit-cat1-select', 'edit-cat2-select');
});

// Cerrar modales al hacer clic fuera
document.addEventListener('click', function(event) {
    if (event.target.classList.contains('bg-opacity-50')) {
        event.target.classList.add('hidden');
    }
});
</script>

<style>
.animate-fade-in {
    animation: fadeIn 0.5s ease-in;
}
.animate-slide-up {
    animation: slideUp 0.5s ease-out;
}
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}
@keyframes slideUp {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}
</style>