<?php
/**
 * ICYLAB OS - Módulo de Productos (Catálogo Centralizado)
 */
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/database.php';
require_once '../../core/format.php';

require_login();
require_permission('module.products');

$pdo = db();

$categories = $pdo->query("SELECT * FROM product_categories ORDER BY name ASC")->fetchAll();

// Mantenemos soporte por si alguien entra con un link guardado, pero aumentamos el límite
$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$cat_id = isset($_GET['category_id']) ? (int)$_GET['category_id'] : 0;

$sql = "SELECT p.*, c.name as category_name FROM products p LEFT JOIN product_categories c ON p.category_id = c.id WHERE p.is_active = 1";
$params = array();

if ($q !== '') {
    $compactQ = preg_replace('/[^0-9a-zA-Z]/', '', $q);
    $sql .= " AND (p.name LIKE ? OR p.sku LIKE ? OR REPLACE(REPLACE(p.sku, '.', ''), '-', '') LIKE ?)";
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$compactQ%";
}

if ($cat_id > 0) {
    $sql .= " AND p.category_id = ?";
    $params[] = $cat_id;
}

$sql .= " ORDER BY p.name ASC LIMIT 500"; // Aumentamos límite para que el frontend tenga qué filtrar

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll();

$page_title = 'Catálogo de Productos';

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';
?>

<main class="app-main" id="products-main">
    <style>
    /* ==========================================================================
       MODALES (Estandarizado con CRM)
       ========================================================================== */
    .product-modal-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.6); backdrop-filter: blur(4px); z-index: var(--z-modal, 1050); display: none; align-items: center; justify-content: center; opacity: 0; transition: opacity var(--motion-base); }
    .product-modal-backdrop.show { opacity: 1; }
    .product-modal-box { background: var(--surface-1); width: 860px; max-width: 95%; max-height: 90vh; border: 1px solid var(--border-default); border-radius: var(--radius-xl); box-shadow: var(--shadow-lg); display: flex; flex-direction: column; transform: translateY(20px); transition: transform var(--motion-base); }
    .product-modal-backdrop.show .product-modal-box { transform: translateY(0); }
    
    .product-modal-header { padding: var(--space-5); border-bottom: 1px solid var(--border-subtle); display: flex; justify-content: space-between; align-items: center; }
    .product-modal-body { padding: var(--space-5); overflow-y: auto; overflow-x: hidden; flex: 0 1 auto; min-height: 0; max-height: calc(100dvh - 210px); -webkit-overflow-scrolling: touch; }
    .product-modal-footer { padding: var(--space-4) var(--space-5); border-top: 1px solid var(--border-subtle); display: flex; justify-content: space-between; align-items: center; background: var(--surface-0); border-radius: 0 0 var(--radius-xl) var(--radius-xl); width: 100%; }
    
    .modal-card { background: var(--surface-2); padding: var(--space-4); border-radius: var(--radius-lg); border: 1px solid var(--border-default); }

    /* ==========================================================================
       BOTÓN CUADRADO INDESTRUCTIBLE
       ========================================================================== */
    .action-square-btn {
        height: 40px !important;
        width: 40px !important;
        min-width: 40px !important;
        max-width: 40px !important;
        padding: 0 !important;
        margin: 0 !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        flex-shrink: 0 !important;
        border-radius: var(--radius-md) !important;
    }


    #products-main .action-square-btn[hidden] {
        display: none !important;
    }

    /* ==========================================================================
       LAYOUT DE PANTALLA PRINCIPAL Y BARRA DE FILTROS
       ========================================================================== */
    .app-main { overflow: hidden !important; display: flex; flex-direction: column; }
    .content { flex: 1; display: flex; flex-direction: column; overflow: hidden; min-height: 0; }
    .card-table-container { flex: 1; display: flex; flex-direction: column; overflow: hidden; min-height: 0; margin-bottom: 0; }
    .table-container-scroll { flex: 1; overflow-y: auto; overflow-x: auto; min-height: 0; }
    .table-container-scroll thead th { position: sticky; top: 0; z-index: 10; background: var(--surface-2); box-shadow: 0 1px 0 var(--border-subtle); }

    .filter-bar-container { display: flex; gap: 12px; flex-wrap: nowrap; padding: 12px 16px; background: var(--surface-1); border: 1px solid var(--border-default); border-radius: var(--radius-xl); margin-bottom: 16px; align-items: center;}
    .input-with-icon { position: relative; width: 100%; display: flex; align-items: center; }
    .input-with-icon svg { position: absolute !important; left: 14px !important; top: 50% !important; transform: translateY(-50%) !important; width: 18px !important; height: 18px !important; color: var(--text-muted) !important; pointer-events: none; }
    .input-with-icon input { padding-left: 42px !important; width: 100%; }

    /* FILA OCULTA POR FILTRO JS */
    .product-row.is-hidden { display: none !important; }

    @media (max-width: 768px) {
        .content { padding-bottom: calc(var(--space-4) + env(safe-area-inset-bottom)) !important; }
        .page-header { display: flex !important; flex-direction: row !important; flex-wrap: nowrap !important; justify-content: space-between !important; align-items: flex-start !important; }
        .page-header-content { flex: 1; min-width: 0; padding-right: 12px; }
        .page-header-content h1 { font-size: 1.35rem !important; line-height: 1.2 !important; margin-bottom: 4px !important; word-break: break-word; }
        
        .actions-cluster { flex-shrink: 0; display: flex !important; gap: 8px !important; }
        .mobile-hidden { display: none !important; }
        .icon-btn-mobile { padding: 0 !important; width: 42px !important; height: 42px !important; display: flex; align-items: center; justify-content: center; }
        
        /* Filtros compactos */
        .filter-bar-container { flex-direction: row !important; padding: 12px !important; gap: 8px !important; }
        .filter-bar-container .form-field { margin-bottom: 0 !important; }
        .filter-bar-container .form-field:nth-child(1) { flex: 1 1 auto !important; min-width: 0 !important; }
        .filter-bar-container .form-field:nth-child(2) { flex: 0 0 auto !important; width: 160px !important; min-width: 0 !important; }
        .filter-bar-container select.select { padding-left: 10px !important; padding-right: 28px !important; font-size: 0.85rem; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; }

        /* Footers Modales */
        .product-modal-footer { flex-direction: row !important; justify-content: space-between !important; align-items: center !important; gap: 8px !important; padding: 12px 16px !important; }
        .btn-delete-mobile { padding: 0 !important; width: 42px !important; min-width: 42px !important; height: 42px !important; display: flex !important; align-items: center !important; justify-content: center !important; flex-shrink: 0 !important; }
        .btn-delete-mobile svg { margin: 0 !important; }
        .modal-footer-actions-right { display: flex !important; gap: 8px !important; justify-content: flex-end !important; flex: 1; }
        .modal-footer-actions-right .btn { padding: 0 var(--space-3) !important; height: 42px !important; font-size: 0.85rem !important; white-space: nowrap !important; }
    }


    /* P10 - Productos: acciones superiores y modales homologados */
    .product-header-actions {
        display: flex !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 10px !important;
        flex-wrap: nowrap !important;
    }
    .product-header-actions .btn {
        min-height: 42px !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        gap: 8px !important;
        white-space: nowrap !important;
    }
    .product-modal-box > form {
        display: flex !important;
        flex-direction: column !important;
        min-height: 0 !important;
        flex: 0 1 auto !important;
    }
    .product-modal-footer .btn {
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        gap: 8px !important;
        min-width: 0 !important;
        overflow: hidden !important;
    }
    .product-modal-footer .btn span {
        display: inline-block !important;
        min-width: 0 !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
        white-space: nowrap !important;
    }
    @media (max-width: 768px) {
        .product-header-actions .btn {
            width: 42px !important;
            min-width: 42px !important;
            max-width: 42px !important;
            height: 42px !important;
            padding: 0 !important;
        }
        .product-modal-backdrop {
            align-items: center !important;
            justify-content: center !important;
            padding: 12px !important;
        }
        .product-modal-box {
            width: calc(100vw - 24px) !important;
            max-width: calc(100vw - 24px) !important;
            height: auto !important;
            min-height: 0 !important;
            max-height: calc(100dvh - 24px) !important;
        }
        .product-modal-body {
            flex: 0 1 auto !important;
            min-height: 0 !important;
            max-height: calc(100dvh - 190px) !important;
            overflow-y: auto !important;
        }
        .product-modal-footer {
            display: grid !important;
            grid-template-columns: auto minmax(0, 1fr) !important;
            gap: 8px !important;
            padding: 12px 16px !important;
        }
        .product-modal-footer > form {
            min-width: 0 !important;
        }
        .modal-footer-actions-right {
            min-width: 0 !important;
            width: 100% !important;
            display: flex !important;
            justify-content: flex-end !important;
            gap: 8px !important;
            overflow: hidden !important;
        }
        .modal-footer-actions-right .btn {
            flex: 0 1 auto !important;
            max-width: 50% !important;
            height: 42px !important;
            padding: 0 10px !important;
        }
        .product-modal-footer .btn span,
        .product-modal-footer .mobile-hidden {
            display: inline-block !important;
            max-width: 9ch !important;
        }
        .btn-delete-mobile {
            width: 42px !important;
            min-width: 42px !important;
            max-width: 42px !important;
            height: 42px !important;
            padding: 0 !important;
        }
        .btn-delete-mobile span {
            display: none !important;
        }
    }


    /* P18 - Productos: alto de product-modal-box igual a Nueva oportunidad CRM */
    #products-main #productModal.product-modal-backdrop,
    #products-main #bulkEditModal.product-modal-backdrop {
        padding: 24px !important;
        align-items: center !important;
        justify-content: center !important;
        overflow: hidden !important;
    }

    #products-main #productModal .product-modal-box,
    #products-main #bulkEditModal .product-modal-box {
        height: min(500px, calc(100dvh - 100px)) !important;
        min-height: min(560px, calc(100dvh - 100px)) !important;
        max-height: calc(100dvh - 200px) !important;
        display: flex !important;
        flex-direction: column !important;
        overflow: hidden !important;
    }

    #products-main #productModal .product-modal-box > form,
    #products-main #bulkEditModal .product-modal-box > form {
        flex: 1 1 auto !important;
        min-height: 0 !important;
        display: flex !important;
        flex-direction: column !important;
        overflow: hidden !important;
    }

    #products-main #productModal .product-modal-header,
    #products-main #bulkEditModal .product-modal-header,
    #products-main #productModal .product-modal-footer,
    #products-main #bulkEditModal .product-modal-footer {
        flex: 0 0 auto !important;
    }

    #products-main #productModal .product-modal-body,
    #products-main #bulkEditModal .product-modal-body {
        flex: 1 1 auto !important;
        min-height: 0 !important;
        max-height: none !important;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        -webkit-overflow-scrolling: touch !important;
    }

    #products-main #productModal .product-modal-footer,
    #products-main #bulkEditModal .product-modal-footer {
        min-height: 76px !important;
        height: auto !important;
        max-height: none !important;
        display: flex !important;
        flex-direction: row !important;
        align-items: center !important;
        justify-content: space-between !important;
        gap: 12px !important;
        flex-wrap: nowrap !important;
        padding: 14px 20px !important;
        background: var(--surface-0) !important;
        border-top: 1px solid var(--border-subtle) !important;
        border-radius: 0 0 var(--radius-xl) var(--radius-xl) !important;
        overflow: visible !important;
    }

    #products-main #productModal .modal-footer-actions-right,
    #products-main #bulkEditModal .modal-footer-actions-right {
        display: flex !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 12px !important;
        flex: 1 1 auto !important;
        min-width: 0 !important;
        overflow: visible !important;
        flex-wrap: nowrap !important;
    }

    #products-main #productModal .product-modal-footer .btn,
    #products-main #bulkEditModal .product-modal-footer .btn {
        width: auto !important;
        min-width: 118px !important;
        max-width: none !important;
        height: 48px !important;
        min-height: 48px !important;
        padding: 0 18px !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        gap: 8px !important;
        flex: 0 0 auto !important;
        white-space: nowrap !important;
        text-align: center !important;
        overflow: visible !important;
        text-overflow: clip !important;
    }

    #products-main #productModal .product-modal-footer .btn span,
    #products-main #bulkEditModal .product-modal-footer .btn span {
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        max-width: none !important;
        overflow: visible !important;
        text-overflow: clip !important;
        white-space: nowrap !important;
        text-align: center !important;
    }

    #products-main #productModal .btn-delete-mobile,
    #products-main #bulkEditModal .btn-delete-mobile {
        width: 48px !important;
        min-width: 48px !important;
        max-width: 48px !important;
        height: 48px !important;
        min-height: 48px !important;
        padding: 0 !important;
        flex: 0 0 48px !important;
        color: var(--color-error) !important;
        border-color: rgba(255, 77, 79, 0.58) !important;
        background: rgba(255, 77, 79, 0.06) !important;
    }

    #products-main #productModal .btn-delete-mobile span,
    #products-main #bulkEditModal .btn-delete-mobile span {
        display: none !important;
    }

    @media (max-width: 768px) {
        #products-main #productModal.product-modal-backdrop,
        #products-main #bulkEditModal.product-modal-backdrop {
            padding: 12px !important;
        }

        #products-main #productModal .product-modal-box,
        #products-main #bulkEditModal .product-modal-box {
            width: calc(100vw - 24px) !important;
            max-width: calc(100vw - 24px) !important;
            height: calc(100dvh - 200px) !important;
            min-height: 0 !important;
            max-height: calc(100dvh - 200px) !important;
            border-radius: 18px !important;
        }

        #products-main #productModal .product-modal-header,
        #products-main #bulkEditModal .product-modal-header {
            padding: 16px !important;
        }

        #products-main #productModal .product-modal-body,
        #products-main #bulkEditModal .product-modal-body {
            padding: 16px !important;
            max-height: none !important;
        }

        #products-main #productModal .product-modal-footer,
        #products-main #bulkEditModal .product-modal-footer {
            min-height: 68px !important;
            display: flex !important;
            grid-template-columns: none !important;
            padding: 10px 12px calc(10px + env(safe-area-inset-bottom)) !important;
            gap: 10px !important;
        }

        #products-main #productModal .modal-footer-actions-right,
        #products-main #bulkEditModal .modal-footer-actions-right {
            gap: 10px !important;
            flex: 1 1 auto !important;
        }

        #products-main #productModal .product-modal-footer .btn,
        #products-main #bulkEditModal .product-modal-footer .btn {
            height: 44px !important;
            min-height: 44px !important;
            min-width: 98px !important;
            max-width: none !important;
            padding: 0 12px !important;
            font-size: 0.92rem !important;
            flex: 0 1 auto !important;
        }

        #products-main #productModal .product-modal-footer .btn-primary,
        #products-main #bulkEditModal .product-modal-footer .btn-primary {
            min-width: 124px !important;
        }

        #products-main #productModal .btn-delete-mobile,
        #products-main #bulkEditModal .btn-delete-mobile {
            width: 44px !important;
            min-width: 44px !important;
            max-width: 44px !important;
            height: 44px !important;
            min-height: 44px !important;
            padding: 0 !important;
            flex: 0 0 44px !important;
        }
    }

    </style>

    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content">

        <div class="page-header" style="margin-bottom: 16px; flex-shrink: 0;">
            <div class="page-header-content">
                <span class="label">Catálogo Maestro</span>
                <h1>Productos y Servicios</h1>
                <p class="text-secondary text-truncate" style="max-width: 100%;">Administra tu catálogo centralizado.</p>
            </div>

            <div class="cluster actions-cluster top-actions-cluster product-header-actions">
                <button type="button" id="syncBtn" class="btn btn-outline btn-icon-mobile" title="Actualizar catálogo desde FACTO" aria-label="Actualizar catálogo desde FACTO" onclick="window.syncProducts(this)">
                    <i data-lucide="refresh-cw"></i>
                    <span class="mobile-hidden">Actualizar</span>
                </button>
                <button type="button" id="btn-bulk-edit" class="btn btn-outline btn-icon-mobile" style="display: none;" onclick="window.openBulkEditModal()" title="Editar selección" aria-label="Editar selección">
                    <i data-lucide="edit-3"></i>
                    <span class="mobile-hidden">Editar (<span id="bulk-count">0</span>)</span>
                </button>
                <button type="button" class="btn btn-primary btn-icon-mobile" onclick="window.openCreateModal()" title="Nuevo producto" aria-label="Nuevo producto">
                    <i data-lucide="plus"></i>
                    <span class="mobile-hidden">Nuevo producto</span>
                </button>
            </div>
        </div>

        <div id="syncAlert" style="display: none;" class="alert mb-4"></div>

        <div class="filter-bar-container" style="flex-shrink: 0;">
            <div class="form-field" style="flex: 1; min-width: 0; margin: 0;">
                <div class="input-with-icon">
                    <i data-lucide="search"></i>
                    <input type="text" id="filterSearch" class="input" placeholder="Buscar por nombre o SKU..." autocomplete="off">
                </div>
            </div>
            
            <div class="form-field" style="flex: 0 0 200px; margin: 0;">
                <select id="filterCategory" class="select" style="width: 100%;">
                    <option value="0">Todas las categorías</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>">
                            <?php echo safe_text($cat['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <section class="card card-table-container">
            <div class="table-wrap table-container-scroll" style="border: 0; border-radius: 0;">
                <table class="table" id="productsTable">
                    <thead>
                        <tr>
                            <th style="width: 48px; text-align: center;">
                                <input type="checkbox" id="selectAllProducts" style="cursor: pointer; width: 16px; height: 16px;" onchange="window.toggleAllProducts(this.checked)">
                            </th>
                            <th style="width: 15%;">SKU</th>
                            <th style="width: 35%;">Nombre del Producto</th>
                            <th style="width: 15%;">Categoría</th>
                            <th class="text-right" style="width: 14%;">Precio Neto</th>
                            <th style="width: 10%; text-align: center;">Unidad</th>
                            <th style="width: 10%; text-align: center;">Stock</th>
                            <th class="text-right" style="width: 10%;">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $p): ?>
                            <tr class="product-row" 
                                data-name="<?php echo htmlspecialchars(mb_strtolower($p['name'], 'UTF-8'), ENT_QUOTES, 'UTF-8'); ?>"
                                data-sku="<?php echo htmlspecialchars(mb_strtolower($p['sku'], 'UTF-8'), ENT_QUOTES, 'UTF-8'); ?>"
                                data-category="<?php echo $p['category_id'] ?: 0; ?>">
                                
                                <td style="text-align: center;">
                                    <input type="checkbox" class="row-checkbox" value="<?php echo $p['id']; ?>" style="cursor: pointer; width: 16px; height: 16px;" onchange="window.toggleProductCheckbox()">
                                </td>
                                <td class="mono text-muted text-sm">
                                    <?php echo safe_text($p['sku'] ?: 'S/S'); ?>
                                </td>
                                <td>
                                    <strong><?php echo safe_text($p['name']); ?></strong>
                                </td>
                                <td>
                                    <span class="badge">
                                        <?php echo safe_text($p['category_name'] ?: 'Sin Categoría'); ?>
                                    </span>
                                </td>
                                <td class="text-right">
                                    <strong><?php echo clp($p['price']); ?></strong>
                                </td>
                                <td style="text-align: center;">
                                    <span class="badge"><?php echo safe_text($p['unit'] ?? 'unidad'); ?></span>
                                </td>
                                <td style="text-align: center;">
                                    <?php 
                                        $stockValue = (float)$p['stock']; 
                                        $stockColor = $stockValue > 0 ? 'var(--color-success)' : 'var(--text-muted)';
                                    ?>
                                    <strong style="color: <?php echo $stockColor; ?>;"><?php echo $stockValue; ?></strong>
                                </td>
                                <td class="text-right">
                                    <button class="btn btn-sm btn-outline" onclick="window.viewProduct(<?php echo $p['id']; ?>)" title="Ver / Editar">
                                        <i data-lucide="eye"></i>
                                        <span class="mobile-hidden">Ver</span>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>

                        <tr id="empty-results-row" style="display: <?php echo empty($products) ? '' : 'none'; ?>;">
                            <td colspan="8" class="text-center text-secondary py-8">
                                <p class="mt-4">No se encontraron productos coincidentes.</p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </section>
    </section>

    <div id="productModal" class="product-modal-backdrop">
        <div class="product-modal-box">
            
            <div class="product-modal-header" style="flex-shrink: 0; display: flex; flex-wrap: nowrap; align-items: flex-start; gap: 12px;">
                <div style="flex: 1; min-width: 0;">
                    <h2 id="modal-name" class="h3" style="font-size: 1.3rem; margin-bottom: 2px; word-break: break-word;">Cargando...</h2>
                    <span id="modal-sku" class="text-secondary text-sm" style="display: block; word-break: break-word;"></span>
                </div>
                <div class="cluster actions-cluster" style="display: flex; flex-direction: row !important; flex-wrap: nowrap !important; gap: 8px; flex-shrink: 0; align-items: center;">
                    <button type="button" class="btn btn-outline action-square-btn" id="btn-header-edit" onclick="window.switchToEditMode()" title="Editar Producto" hidden>
                        <i data-lucide="pencil" style="width: 18px; height: 18px;"></i>
                    </button>
                    <button type="button" class="btn btn-outline action-square-btn" onclick="window.closeProductModal()" title="Cerrar">
                        <i data-lucide="x" style="width: 18px; height: 18px;"></i>
                    </button>
                </div>
            </div>
            
            <div class="product-modal-body">
                <div id="modal-view-mode" style="display: none;">
                    <div class="grid grid-2 mb-4">
                        <div class="modal-card">
                            <h3 class="h3 mb-4">Rentabilidad y Costos</h3>
                            <div class="metric-row"><span class="text-secondary">Precio Neto</span><strong id="modal-price"></strong></div>
                            <div class="metric-row"><span class="text-secondary">Costo</span><strong id="modal-cost" style="color: var(--color-warning);"></strong></div>
                            <div class="metric-row"><span class="text-secondary">Margen ($)</span><strong id="modal-margin-abs"></strong></div>
                            <div class="metric-row" style="border:0;"><span class="text-secondary">Margen (%)</span><strong id="modal-margin-pct"></strong></div>
                        </div>

                        <div class="modal-card">
                            <h3 class="h3 mb-4">Información General</h3>
                            <div class="metric-row"><span class="text-secondary">Categoría</span><strong id="modal-cat"></strong></div>
                            <div class="metric-row"><span class="text-secondary">Unidad</span><strong id="modal-unit"></strong></div>
                            <div class="metric-row"><span class="text-secondary">Estado</span><span id="modal-status"></span></div>
                            <div class="metric-row" style="border:0;"><span class="text-secondary">Stock Físico</span><strong id="modal-stock"></strong></div>
                        </div>
                    </div>
                    
                    <div style="margin-top: var(--space-4);">
                        <span class="label" style="display: block; margin-bottom: var(--space-2);">Descripción / Detalles</span>
                        <div id="modal-desc" class="text-sm text-secondary" style="background: var(--surface-1); padding: var(--space-4); border-radius: var(--radius-md); border: 1px solid var(--border-default); min-height: 80px; line-height: 1.6;"></div>
                    </div>
                </div>

                <form id="modal-form-mode" action="" method="POST" style="display: none; margin: 0;">
                    <input type="hidden" name="id" id="form_id" value="">
                    <div class="form-grid form-grid-2">
                        <div class="form-field is-required">
                            <label class="label">Nombre del Producto</label>
                            <input class="input" type="text" name="name" id="form_name" required>
                        </div>
                        <div class="form-field">
                            <label class="label">SKU (Código Interno)</label>
                            <input class="input" type="text" name="sku" id="form_sku">
                        </div>
                        <div class="form-field">
                            <label class="label">Categoría</label>
                            <div style="display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: center;">
                                <select class="select" name="category_id" id="form_category_id" style="width: 100%; margin: 0;">
                                    <option value="">Sin Categoría</option>
                                    <?php foreach ($categories as $cat): ?>
                                        <option value="<?php echo $cat['id']; ?>"><?php echo safe_text($cat['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="button" class="btn btn-outline" style="width: 42px !important; min-width: 42px !important; height: 42px; padding: 0; display: flex; justify-content: center; align-items: center;" title="Nueva Categoría rápida" onclick="window.openCategoryModal('form_category_id')">
                                    <i data-lucide="plus"></i>
                                </button>
                            </div>
                        </div>
                        <div class="form-field">
                            <label class="label">Stock Disponible</label>
                            <input class="input" type="number" name="stock" id="form_stock" min="0" step="0.01">
                        </div>
                        <div class="form-field">
                            <label class="label">Unidad comercial</label>
                            <select class="select" name="unit" id="form_unit">
                                <option value="unidad">unidad</option>
                                <option value="mL">mL</option>
                                <option value="L">L</option>
                                <option value="g">g</option>
                                <option value="kg">kg</option>
                                <option value="pack">pack</option>
                                <option value="caja">caja</option>
                                <option value="servicio">servicio</option>
                            </select>
                        </div>
                        <div class="form-field is-required">
                            <label class="label">Precio Neto ($)</label>
                            <input class="input" type="number" name="price" id="form_price" min="0" step="0.01" required>
                        </div>
                        <div class="form-field">
                            <label class="label">Costo ($)</label>
                            <input class="input" type="number" name="cost" id="form_cost" min="0" step="0.01">
                        </div>
                        <div class="form-field">
                            <label class="label">Estado</label>
                            <select class="select" name="is_active" id="form_is_active">
                                <option value="1">Activo (Visible al cotizar)</option>
                                <option value="0">Inactivo (Oculto)</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-grid mt-4">
                        <div class="form-field form-field-full">
                            <label class="label">Descripción Detallada</label>
                            <textarea class="textarea" name="description" id="form_desc" rows="3"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            
            <div class="product-modal-footer" id="modal-form-footer" style="display: none;">
                <form id="modal-delete-form" action="/modules/products/product_delete.php" method="POST" onsubmit="return confirm('¿Eliminar producto?');" style="margin: 0;">
                    <input type="hidden" name="id" id="modal-delete-id" value="">
                    <button type="submit" class="btn btn-outline btn-delete-mobile" style="color: var(--color-error); border-color: var(--color-error);" title="Eliminar Producto">
                        <i data-lucide="trash-2"></i><span>Eliminar</span>
                    </button>
                </form>
                <div class="modal-footer-actions-right">
                    <button type="button" id="btn-cancel-form" class="btn btn-outline modal-cancel-btn" onclick="window.cancelProductForm()">
                        <i data-lucide="x"></i><span>Cancelar</span>
                    </button>
                    <button type="submit" form="modal-form-mode" class="btn btn-primary">
                        <i data-lucide="save"></i><span id="form-submit-text">Guardar</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div id="categoryModal" class="product-modal-backdrop" style="z-index: 1060;">
        <div class="product-modal-box" style="width: 420px; max-width: 95%;">
            <div class="product-modal-header" style="flex-shrink: 0; display: flex; flex-wrap: nowrap; align-items: flex-start; gap: 12px;">
                <div style="flex: 1; min-width: 0;">
                    <h3 class="h3" style="font-size: 1.15rem; margin-bottom: 2px; word-break: break-word;">Nueva Categoría</h3>
                    <span class="text-secondary text-sm" style="display: block; word-break: break-word;">Se asignará automáticamente al producto</span>
                </div>
                <button type="button" class="btn btn-outline action-square-btn" onclick="window.closeCategoryModal()" title="Cerrar">
                    <i data-lucide="x" style="width: 18px; height: 18px;"></i>
                </button>
            </div>
            <div class="product-modal-body">
                <div class="form-field is-required" style="margin-bottom: 0;">
                    <label class="label">Nombre de la Categoría</label>
                    <input class="input" type="text" id="ajax_category_name" placeholder="Ej: Herramientas" required>
                </div>
            </div>
            <div class="product-modal-footer">
                <div class="modal-footer-actions-right" style="width: 100%;">
                    <button type="button" class="btn btn-outline modal-cancel-btn" onclick="window.closeCategoryModal()">
                        <i data-lucide="x"></i><span>Cancelar</span>
                    </button>
                    <button type="button" class="btn btn-primary" id="btn-save-category" onclick="window.saveCategoryAjax()">
                        <i data-lucide="save"></i><span>Guardar</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div id="bulkEditModal" class="product-modal-backdrop" style="z-index: 1020;">
        <div class="product-modal-box" style="width: 480px; max-width: 95%;">
            <form id="bulk-edit-form" action="/modules/products/product_bulk_update.php" method="POST" style="margin:0;">
                <div class="product-modal-header" style="flex-shrink: 0; display: flex; flex-wrap: nowrap; align-items: flex-start; gap: 12px;">
                    <div style="flex: 1; min-width: 0;">
                        <h3 class="h3" style="font-size: 1.15rem; margin-bottom: 2px; word-break: break-word;">Edición Masiva</h3>
                        <span class="text-secondary text-sm" style="display: block; word-break: break-word;">Actualizando <span id="bulk-modal-count">0</span> productos</span>
                    </div>
                    <button type="button" class="btn btn-outline action-square-btn" onclick="window.closeBulkEditModal()" title="Cerrar">
                        <i data-lucide="x" style="width: 18px; height: 18px;"></i>
                    </button>
                </div>
                
                <div class="product-modal-body">
                    <input type="hidden" name="product_ids" id="bulk_product_ids" value="">
                    <div class="form-info-box mb-4" style="padding: 12px 16px;">
                        <i data-lucide="info"></i>
                        <span>Deja en blanco los campos que <b style="font-weight: 700;">no</b> deseas modificar.</span>
                    </div>
                    <div class="form-grid">
                        <div class="form-field">
                            <label class="label">Asignar Nueva Categoría</label>
                            <div style="display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: center;">
                                <select class="select" name="bulk_category_id" id="bulk_category_id" style="width: 100%; margin: 0;">
                                    <option value="">-- Sin cambios --</option>
                                    <option value="NULL">Quitar Categoría (Dejar sin asignar)</option>
                                    <?php foreach ($categories as $cat): ?>
                                        <option value="<?php echo $cat['id']; ?>"><?php echo safe_text($cat['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="button" class="btn btn-outline" style="width: 42px !important; min-width: 42px !important; height: 42px; padding: 0; display: flex; justify-content: center; align-items: center;" title="Nueva Categoría" onclick="window.openCategoryModal('bulk_category_id')">
                                    <i data-lucide="plus"></i>
                                </button>
                            </div>
                        </div>
                        <div class="form-field mt-2">
                            <label class="label">Cambiar unidad comercial</label>
                            <select class="select" name="bulk_unit">
                                <option value="">-- Sin cambios --</option>
                                <option value="unidad">unidad</option>
                                <option value="mL">mL</option>
                                <option value="L">L</option>
                                <option value="g">g</option>
                                <option value="kg">kg</option>
                                <option value="pack">pack</option>
                                <option value="caja">caja</option>
                                <option value="servicio">servicio</option>
                            </select>
                        </div>
                        <div class="form-field mt-2">
                            <label class="label">Cambiar Estado</label>
                            <select class="select" name="bulk_is_active">
                                <option value="">-- Sin cambios --</option>
                                <option value="1">Activo (Visible)</option>
                                <option value="0">Inactivo (Oculto)</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="product-modal-footer">
                    <button type="button" class="btn btn-outline btn-delete-mobile" style="color: var(--color-error); border-color: var(--color-error);" onclick="window.submitBulkDelete()" title="Eliminar Seleccionados">
                        <i data-lucide="trash-2"></i><span>Eliminar</span>
                    </button>
                    <div class="modal-footer-actions-right">
                        <button type="button" class="btn btn-outline modal-cancel-btn" onclick="window.closeBulkEditModal()">
                            <i data-lucide="x"></i><span>Cancelar</span>
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i data-lucide="check-circle"></i><span>Aplicar</span>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script>
    // =========================================================================
    // LÓGICA DE APLICACIÓN PROTEGIDA (SPA SAFE)
    // =========================================================================
    (function() {
        window.currentProductData = null;
        window.activeCategoryTarget = 'form_category_id'; 

        // --- FILTRADO FRONTEND (BÚSQUEDA EN VIVO) ---
        window.removeAccents = function(str) {
            if (window.ICY_NORMALIZE_SEARCH) return window.ICY_NORMALIZE_SEARCH(str);
            return (str || '').toString().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").trim();
        };

        window.applyProductFilters = function() {
            const searchInput = document.getElementById('filterSearch');
            const categorySelect = document.getElementById('filterCategory');
            if (!searchInput || !categorySelect) return;

            const searchQuery = window.removeAccents(searchInput.value);
            const compactSearchQuery = searchQuery.replace(/[^a-z0-9]/g, '');
            const catFilter = categorySelect.value;
            const rows = document.querySelectorAll('.product-row');
            
            let visibleCount = 0;

            rows.forEach(row => {
                const name = window.removeAccents(row.dataset.name);
                const sku = window.removeAccents(row.dataset.sku);
                const compactSku = sku.replace(/[^a-z0-9]/g, '');
                const cat = row.dataset.category;

                const matchesSearch = searchQuery === '' || name.includes(searchQuery) || sku.includes(searchQuery) || (compactSearchQuery.length >= 2 && compactSku.includes(compactSearchQuery));
                const matchesCat = catFilter === '0' || cat === catFilter;

                if (matchesSearch && matchesCat) {
                    row.classList.remove('is-hidden');
                    visibleCount++;
                } else {
                    row.classList.add('is-hidden');
                }
            });
            
            const emptyRow = document.getElementById('empty-results-row');
            if(emptyRow) {
                emptyRow.style.display = visibleCount === 0 ? '' : 'none';
            }
        };

        // --- MANEJO DE EVENTOS (SEGUROS) ---
        const filterSearch = document.getElementById('filterSearch');
        const filterCategory = document.getElementById('filterCategory');

        if (filterSearch) {
            filterSearch.addEventListener('input', window.applyProductFilters);
            filterSearch.addEventListener('keyup', window.applyProductFilters);
        }
        
        if (filterCategory) {
            filterCategory.addEventListener('change', window.applyProductFilters);
        }
        window.applyProductFilters();

        // --- MODALES ---
        const modalBackdrop = document.getElementById('productModal');
        const viewMode = document.getElementById('modal-view-mode');
        const formMode = document.getElementById('modal-form-mode');
        const formFooter = document.getElementById('modal-form-footer');
        const btnHeaderEdit = document.getElementById('btn-header-edit');

        window.closeProductModal = function() {
            if(modalBackdrop) {
                modalBackdrop.classList.remove('show');
                setTimeout(() => modalBackdrop.style.display = 'none', 80);
            }
        };

        window.openCreateModal = function() {
            window.currentProductData = null; 
            document.getElementById('modal-name').innerText = 'Crear Nuevo Producto';
            document.getElementById('modal-sku').innerText = 'Completa la información obligatoria';
            document.getElementById('modal-delete-form').style.display = 'none'; 
            if (btnHeaderEdit) btnHeaderEdit.hidden = true;
            
            formMode.reset();
            document.getElementById('form_id').value = '';
            document.getElementById('form_unit').value = 'unidad';
            formMode.action = '/modules/products/product_store.php'; 
            document.getElementById('form-submit-text').innerText = 'Guardar';

            viewMode.style.display = 'none';
            formMode.style.display = 'block';
            formFooter.style.display = 'flex';

            modalBackdrop.style.display = 'flex';
            setTimeout(() => modalBackdrop.classList.add('show'), 10);
        };

        window.viewProduct = function(id) {
            document.getElementById('modal-name').innerText = 'Cargando datos...';
            document.getElementById('modal-sku').innerText = 'SKU: ...';
            
            viewMode.style.display = 'none';
            formMode.style.display = 'none';
            formFooter.style.display = 'none';
            if (btnHeaderEdit) btnHeaderEdit.hidden = true;

            modalBackdrop.style.display = 'flex';
            setTimeout(() => modalBackdrop.classList.add('show'), 10);

            fetch(`/modules/products/product_get.php?id=${id}`)
                .then(res => res.json())
                .then(data => {
                    if(data.success) {
                        window.currentProductData = data.product; 
                        const p = data.product;
                        const calc = data.calculated;

                        document.getElementById('modal-name').innerText = p.name;
                        document.getElementById('modal-sku').innerText = 'SKU: ' + (p.sku || 'No asignado');
                        document.getElementById('modal-price').innerText = calc.price_formatted;
                        document.getElementById('modal-cost').innerText = calc.cost_formatted;
                        
                        const mAbs = document.getElementById('modal-margin-abs');
                        mAbs.innerText = calc.margin_abs_formatted;
                        mAbs.style.color = calc.margin_abs > 0 ? 'var(--color-success)' : 'var(--color-error)';

                        const mPct = document.getElementById('modal-margin-pct');
                        mPct.innerText = calc.margin_pct_formatted;
                        mPct.style.color = calc.margin_pct > 0 ? 'var(--color-success)' : 'var(--color-error)';

                        document.getElementById('modal-cat').innerText = p.category_name || 'Sin Categoría';
                        document.getElementById('modal-unit').innerText = p.unit || 'unidad';
                        document.getElementById('modal-status').innerHTML = p.is_active == 1 
                            ? '<span class="badge badge-success">Activo</span>' 
                            : '<span class="badge">Inactivo</span>';
                        
                        const stockEl = document.getElementById('modal-stock');
                        stockEl.innerText = parseFloat(p.stock);
                        stockEl.style.color = p.stock > 0 ? 'var(--color-success)' : 'var(--text-muted)';

                        document.getElementById('modal-desc').innerHTML = p.description ? p.description.replace(/\n/g, '<br>') : 'Sin descripción detallada.';
                        document.getElementById('modal-delete-id').value = p.id;

                        viewMode.style.display = 'block';
                        if (btnHeaderEdit) btnHeaderEdit.hidden = false; 
                    } else {
                        alert(data.message);
                        window.closeProductModal();
                    }
                })
                .catch(err => {
                    alert('Error al cargar la ficha del producto.');
                    window.closeProductModal();
                });
        };

        window.switchToEditMode = function() {
            if(!window.currentProductData) return;
            const p = window.currentProductData;

            document.getElementById('modal-name').innerText = 'Editar Producto';
            document.getElementById('modal-sku').innerText = 'SKU: ' + (p.sku || 'No asignado');

            document.getElementById('form_id').value = p.id;
            document.getElementById('form_name').value = p.name;
            document.getElementById('form_sku').value = p.sku;
            document.getElementById('form_category_id').value = p.category_id || '';
            document.getElementById('form_stock').value = parseFloat(p.stock) || 0;
            document.getElementById('form_unit').value = p.unit || 'unidad';
            document.getElementById('form_price').value = parseFloat(p.price) || 0;
            document.getElementById('form_cost').value = parseFloat(p.cost) || 0;
            document.getElementById('form_is_active').value = p.is_active;
            document.getElementById('form_desc').value = p.description || '';
            
            document.getElementById('modal-delete-form').style.display = 'block';
            if (btnHeaderEdit) btnHeaderEdit.hidden = true; // Ocultamos lápiz al editar

            formMode.action = '/modules/products/product_update.php';
            document.getElementById('form-submit-text').innerText = 'Actualizar';

            viewMode.style.display = 'none';
            formMode.style.display = 'block';
            formFooter.style.display = 'flex';
        };

        window.cancelProductForm = function() {
            if(document.getElementById('form_id').value !== '') {
                document.getElementById('modal-name').innerText = window.currentProductData.name;
                document.getElementById('modal-sku').innerText = 'SKU: ' + (window.currentProductData.sku || 'No asignado');
                formMode.style.display = 'none';
                formFooter.style.display = 'none';
                viewMode.style.display = 'block';
                if (btnHeaderEdit) btnHeaderEdit.hidden = false; // Recuperamos lápiz
            } else {
                window.closeProductModal();
            }
        };

        window.syncProducts = function(btnElement) {
            btnElement.disabled = true;
            btnElement.innerHTML = '<i data-lucide="loader" class="spin-icon"></i>';
            if (window.lucide) lucide.createIcons();
            
            const syncAlert = document.getElementById('syncAlert');
            syncAlert.style.display = 'none';
            syncAlert.className = 'alert mb-4';

            fetch('/modules/products/product_sync.php')
                .then(response => response.json())
                .then(data => {
                    btnElement.disabled = false;
                    btnElement.innerHTML = '<i data-lucide="refresh-cw"></i>';
                    if (window.lucide) lucide.createIcons();

                    syncAlert.style.display = 'block';

                    if (data.success) {
                        syncAlert.classList.add('alert-success');
                        syncAlert.innerHTML = '<strong>¡Importación Exitosa!</strong> ' + data.message;
                        setTimeout(() => { if (window.ICY_SPA_RELOAD) window.ICY_SPA_RELOAD({ force: true }); else window.location.reload(); }, 900);
                    } else {
                        syncAlert.classList.add('alert-error');
                        syncAlert.innerHTML = '<strong>Error de Sincronización:</strong> ' + data.message;
                    }
                });
        };

        // Modales Secundarios (Categoría y Bulk)
        window.openCategoryModal = function(targetId = 'form_category_id') {
            window.activeCategoryTarget = targetId; 
            document.getElementById('ajax_category_name').value = ''; 
            const catModal = document.getElementById('categoryModal');
            catModal.style.display = 'flex';
            setTimeout(() => catModal.classList.add('show'), 10);
        };

        window.closeCategoryModal = function() {
            const catModal = document.getElementById('categoryModal');
            catModal.classList.remove('show');
            setTimeout(() => catModal.style.display = 'none', 80);
        };

        window.saveCategoryAjax = function() {
            const nameInput = document.getElementById('ajax_category_name');
            const name = nameInput.value.trim();
            
            if(!name) { 
                alert('El nombre de la categoría es obligatorio'); 
                nameInput.focus();
                return; 
            }

            const btn = document.getElementById('btn-save-category');
            btn.disabled = true;
            btn.innerHTML = '<i data-lucide="loader" class="spin-icon"></i><span class="mobile-hidden">Guardando...</span>';
            if(window.lucide) lucide.createIcons();

            const formData = new FormData();
            formData.append('name', name);

            fetch('/modules/categories/category_store_ajax.php', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                btn.disabled = false;
                btn.innerHTML = '<i data-lucide="save"></i><span>Guardar</span>';
                if (window.lucide) lucide.createIcons();

                if(data.success) {
                    const selectsToSync = ['form_category_id', 'bulk_category_id'];
                    selectsToSync.forEach(selectId => {
                        const sel = document.getElementById(selectId);
                        if(sel) {
                            const opt = document.createElement('option');
                            opt.value = data.id;
                            opt.textContent = data.name;
                            sel.appendChild(opt);
                        }
                    });
                    
                    const activeSelect = document.getElementById(window.activeCategoryTarget);
                    if(activeSelect) activeSelect.value = data.id;
                    window.closeCategoryModal();
                } else {
                    alert(data.message || 'Error al guardar la categoría');
                }
            })
            .catch(err => {
                alert('Error de conexión con el servidor');
                btn.disabled = false;
                btn.innerHTML = '<i data-lucide="save"></i><span>Guardar</span>';
                if (window.lucide) lucide.createIcons();
            });
        };

        // Edición Masiva (Checkboxes)
        const selectAllCb = document.getElementById('selectAllProducts');
        const rowCbs = document.querySelectorAll('.row-checkbox');
        const btnBulkEdit = document.getElementById('btn-bulk-edit');
        const bulkInputIds = document.getElementById('bulk_product_ids');

        window.updateBulkButton = function() {
            const selected = Array.from(rowCbs).filter(cb => cb.checked).map(cb => cb.value);
            if (selected.length > 0) {
                btnBulkEdit.style.display = 'inline-flex';
                document.getElementById('bulk-count').innerText = selected.length;
                document.getElementById('bulk-modal-count').innerText = selected.length;
                bulkInputIds.value = selected.join(','); 
            } else {
                btnBulkEdit.style.display = 'none';
                bulkInputIds.value = '';
            }
        };

        window.toggleAllProducts = function(isChecked) {
            rowCbs.forEach(cb => cb.checked = isChecked);
            window.updateBulkButton();
        };

        window.toggleProductCheckbox = function() {
            if (document.querySelectorAll('.row-checkbox:checked').length === rowCbs.length) {
                if(selectAllCb) selectAllCb.checked = true;
            } else {
                if(selectAllCb) selectAllCb.checked = false;
            }
            window.updateBulkButton();
        };

        window.openBulkEditModal = function() {
            const bulkModal = document.getElementById('bulkEditModal');
            bulkModal.style.display = 'flex';
            setTimeout(() => bulkModal.classList.add('show'), 10);
        };

        window.closeBulkEditModal = function() {
            const bulkModal = document.getElementById('bulkEditModal');
            bulkModal.classList.remove('show');
            setTimeout(() => bulkModal.style.display = 'none', 80);
        };

        window.submitBulkDelete = function() {
            const count = document.getElementById('bulk-modal-count').innerText;
            if (confirm(`¿Estás seguro de eliminar los ${count} productos seleccionados?\n\nEsta acción es irreversible.`)) {
                const form = document.getElementById('bulk-edit-form');
                form.action = '/modules/products/product_bulk_delete.php';
                // Usamos submit tradicional para asegurar el POST masivo
                const submitEvent = new Event('submit', { bubbles: true, cancelable: true });
                form.dispatchEvent(submitEvent);
            }
        };

        // Listeners Globales Seguros
        if (!window.__productsGlobalClicksAttached) {
            document.addEventListener('click', function(e) {
                const productModal = document.getElementById('productModal');
                const categoryModal = document.getElementById('categoryModal');
                const bulkModal = document.getElementById('bulkEditModal');

                if (productModal && e.target === productModal) window.closeProductModal();
                if (categoryModal && e.target === categoryModal) window.closeCategoryModal();
                if (bulkModal && e.target === bulkModal) window.closeBulkEditModal();
            });
            window.__productsGlobalClicksAttached = true;
        }

    })();
    </script>
</main>

<?php require_once '../../layouts/footer.php'; ?>