<?php
// include db connection
include '../db/db.php';
include '../includes/session_control.php';

// Obtener las variables de la URL
$idIngreso = $_GET['idIngreso'] ?? '';
$idTabla = $_GET['idTabla'] ?? '';

// Handle AJAX request to filter data
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if user is authenticated
    if (!isset($_SESSION['user'])) {
        header('Content-Type: application/json');
        echo json_encode(['error' => 'User not authenticated']);
        exit;
    }

    // Obtener las variables POST
    $referenciaCPN = $conn->real_escape_string($_POST['referenciaCPN'] ?? '');
    $searchTerm = $conn->real_escape_string($_POST['searchTerm'] ?? '');
    $descuentoDesde = $conn->real_escape_string($_POST['descuentoDesde'] ?? '');
    $descuentoHasta = $conn->real_escape_string($_POST['descuentoHasta'] ?? '');
    $descuentoAntesImpuestosDesde = $conn->real_escape_string($_POST['descuentoAntesImpuestosDesde'] ?? '');
    $descuentoAntesImpuestosHasta = $conn->real_escape_string($_POST['descuentoAntesImpuestosHasta'] ?? '');
    $inventarioDesde = $conn->real_escape_string($_POST['inventarioDesde'] ?? 0);
    $orderBy = $conn->real_escape_string($_POST['orderBy'] ?? '');
    $orderDir = $conn->real_escape_string($_POST['orderDir'] ?? 'ASC');
    $page = $conn->real_escape_string($_POST['page'] ?? 1);
    $pageSize = $conn->real_escape_string($_POST['pageSize'] ?? 10);
    $precioMarcaDesde = $conn->real_escape_string($_POST['precioMarcaDesde'] ?? '');
    $precioMarcaHasta = $conn->real_escape_string($_POST['precioMarcaHasta'] ?? '');
    $precioMarcaAntesImpuestosDesde = $conn->real_escape_string($_POST['precioMarcaAntesImpuestosDesde'] ?? '');
    $precioMarcaAntesImpuestosHasta = $conn->real_escape_string($_POST['precioMarcaAntesImpuestosHasta'] ?? '');

    // Get the final price and tecnicaTipoRango from localStorage
    $precioFinalMarca = $_POST['precioFinalMarca'] ?? 0;
    $tecnicaTipoRango = $_POST['tecnicaTipoRango'] ?? '';
    $precioFinalMarcaIva = $precioFinalMarca * 1.19;

    // Prepare dynamic SQL for searchTerm
    $searchTermCondition = "";
    if ($searchTerm !== '') {
        $words = explode(' ', $searchTerm);
        $allWordsAndSynonyms = [];

        foreach ($words as $word) {
            $word = $conn->real_escape_string(mb_strtolower(trim($word), 'UTF-8'));
            $wordSynonyms = [$word];
            $synonymQuery = $conn->query("SELECT sinonimo FROM tb_terminos_busqueda WHERE LOWER(REPLACE(valor, 'í', 'i')) = '$word'");
            while ($row = $synonymQuery->fetch_assoc()) {
                $wordSynonyms[] = mb_strtolower($row['sinonimo'], 'UTF-8');
            }
            $allWordsAndSynonyms[] = $wordSynonyms;
        }

        $searchTermConditionParts = [];
        foreach ($allWordsAndSynonyms as $synonyms) {
            $synonymConditions = [];
            foreach ($synonyms as $synonym) {
                $synonymConditions[] = "(LOWER(tb_productos.nombre) LIKE '%$synonym%' OR LOWER(tb_productos_variantes.txtColor) LIKE '%$synonym%' OR LOWER(tb_productos.descripcion) LIKE '%$synonym%' OR LOWER(tb_productos.txtMedidas) LIKE '%$synonym%' OR LOWER(tb_productos.txtMaterial) LIKE '%$synonym%')";
            }
            $searchTermConditionParts[] = '(' . implode(' OR ', $synonymConditions) . ')';
        }
        $searchTermCondition = implode(' AND ', $searchTermConditionParts);
    } else {
        $searchTermCondition = "1"; // True condition when no search term is provided
    }

    // Determine order by clause
    $orderByClause = "";
    if (in_array($orderBy, ['descuentoPVP', 'descuentoPVPantesImpuestos', 'inventario', 'precioMarcaConImpuestos', 'precioMarcaAntesImpuestos'])) {
        $orderByClause = "ORDER BY $orderBy $orderDir";
    }

    // Calculate offset for pagination
    $offset = ($page - 1) * $pageSize;

    // Use concatenation to include the PHP variable within the SQL string
    $sql = "
   SELECT 
    tb_productos_variantes.referenciaCPN,
    REPLACE(tb_imagenes_variantes.linkImagen, 'J:/images/', 'https://sistema.compranet.com.co/images/') AS urlImagen,
    CONCAT(tb_productos.nombre, ' - ', tb_productos_variantes.txtColor) AS nombreColor,
    tb_productos_variantes.inventario,
    tb_productos_variantes.id AS idVariacion,
    tb_productos_variantes.wp_id AS idwpProductoVariacion,
    tb_productos.urlExterna AS urlExterna,
    CONCAT('https://compranet.com.co/?p=', tb_productos_variantes.wp_id) AS linkProducto,
    COALESCE(
        (SELECT edv.PVPantesImpuestos 
         FROM tb_escala_descuentos_variaciones edv
         JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
         WHERE edv.idVariacion = tb_productos_variantes.id 
         AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
         ORDER BY edv.cantidadRequerida DESC 
         LIMIT 1),
        LEAST(
            IFNULL(NULLIF(tb_productos_variantes.PVPantesImpuestos, 0), 999999),
            IFNULL(NULLIF(tb_productos_variantes.PVPreducidoantesImpuestos, 0), 999999)
        )
    ) AS descuentoPVPantesImpuestos,
    COALESCE(
        (SELECT edv.PVP 
         FROM tb_escala_descuentos_variaciones edv
         JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
         WHERE edv.idVariacion = tb_productos_variantes.id 
         AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
         ORDER BY edv.cantidadRequerida DESC 
         LIMIT 1),
        LEAST(
            IFNULL(NULLIF(tb_productos_variantes.PVP, 0), 999999),
            IFNULL(NULLIF(tb_productos_variantes.PVPReducido, 0), 999999)
        )
    ) AS descuentoPVP,
    COALESCE(
        (SELECT ved.nombre 
         FROM tb_escala_descuentos_variaciones edv
         JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
         WHERE edv.idVariacion = tb_productos_variantes.id 
         AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
         ORDER BY edv.cantidadRequerida DESC 
         LIMIT 1),
        'Nivel 1'
    ) AS Nivel,
    tb_productos_variantes.minVenta,
    tb_productos_variantes.multiploVenta,
    (COALESCE(
        (SELECT edv.PVPantesImpuestos 
         FROM tb_escala_descuentos_variaciones edv
         JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
         WHERE edv.idVariacion = tb_productos_variantes.id 
         AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
         ORDER BY edv.cantidadRequerida DESC 
         LIMIT 1),
        LEAST(
            IFNULL(NULLIF(tb_productos_variantes.PVPantesImpuestos, 0), 999999),
            IFNULL(NULLIF(tb_productos_variantes.PVPreducidoantesImpuestos, 0), 999999)
        )
    ) + $precioFinalMarca) AS precioMarcaAntesImpuestos, 
    (COALESCE(
        (SELECT edv.PVP 
         FROM tb_escala_descuentos_variaciones edv
         JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
         WHERE edv.idVariacion = tb_productos_variantes.id 
         AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
         ORDER BY edv.cantidadRequerida DESC 
         LIMIT 1),
        LEAST(
            IFNULL(NULLIF(tb_productos_variantes.PVP, 0), 999999),
            IFNULL(NULLIF(tb_productos_variantes.PVPReducido, 0), 999999)
        )
    ) + $precioFinalMarcaIva) AS precioMarcaConImpuestos 
FROM 
    tb_productos_variantes
INNER JOIN tb_imagenes_variantes ON tb_productos_variantes.id = tb_imagenes_variantes.idVariante
INNER JOIN tb_productos ON tb_productos_variantes.idProducto = tb_productos.id
WHERE 
    tb_productos_variantes.PVPantesImpuestos > 0 
    AND tb_productos_variantes.inventario > 0 
    AND (tb_productos_variantes.referenciaCPN LIKE '%$referenciaCPN%' OR '$referenciaCPN' = '')
    AND ($searchTermCondition)
    AND (
        tb_productos_variantes.referenciaCPN LIKE 'CPN-M%' 
        OR tb_productos.wp_id > 0
    )
    AND ('$descuentoDesde' = '' OR 
        COALESCE(
            (SELECT edv.PVP 
             FROM tb_escala_descuentos_variaciones edv
             JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
             WHERE edv.idVariacion = tb_productos_variantes.id 
             AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
             ORDER BY edv.cantidadRequerida DESC 
             LIMIT 1),
            LEAST(
                IFNULL(NULLIF(tb_productos_variantes.PVP, 0), 999999),
                IFNULL(NULLIF(tb_productos_variantes.PVPReducido, 0), 999999)
            )
        ) >= '$descuentoDesde')
    AND ('$descuentoHasta' = '' OR 
        COALESCE(
            (SELECT edv.PVP 
             FROM tb_escala_descuentos_variaciones edv
             JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
             WHERE edv.idVariacion = tb_productos_variantes.id 
             AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
             ORDER BY edv.cantidadRequerida DESC 
             LIMIT 1),
            LEAST(
                IFNULL(NULLIF(tb_productos_variantes.PVP, 0), 999999),
                IFNULL(NULLIF(tb_productos_variantes.PVPReducido, 0), 999999)
            )
        ) <= '$descuentoHasta')
    AND ('$descuentoAntesImpuestosDesde' = '' OR 
        COALESCE(
            (SELECT edv.PVPantesImpuestos 
             FROM tb_escala_descuentos_variaciones edv
             JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
             WHERE edv.idVariacion = tb_productos_variantes.id 
             AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
             ORDER BY edv.cantidadRequerida DESC 
             LIMIT 1),
            LEAST(
                IFNULL(NULLIF(tb_productos_variantes.PVPantesImpuestos, 0), 999999),
                IFNULL(NULLIF(tb_productos_variantes.PVPreducidoantesImpuestos, 0), 999999)
            )
        ) >= '$descuentoAntesImpuestosDesde')
    AND ('$descuentoAntesImpuestosHasta' = '' OR 
        COALESCE(
            (SELECT edv.PVPantesImpuestos 
             FROM tb_escala_descuentos_variaciones edv
             JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
             WHERE edv.idVariacion = tb_productos_variantes.id 
             AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
             ORDER BY edv.cantidadRequerida DESC 
             LIMIT 1),
            LEAST(
                IFNULL(NULLIF(tb_productos_variantes.PVPantesImpuestos, 0), 999999),
                IFNULL(NULLIF(tb_productos_variantes.PVPreducidoantesImpuestos, 0), 999999)
            )
        ) <= '$descuentoAntesImpuestosHasta')
    AND ('$precioMarcaDesde' = '' OR 
        (COALESCE(
            (SELECT edv.PVP 
             FROM tb_escala_descuentos_variaciones edv
             JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
             WHERE edv.idVariacion = tb_productos_variantes.id 
             AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
             ORDER BY edv.cantidadRequerida DESC 
             LIMIT 1),
            LEAST(
                IFNULL(NULLIF(tb_productos_variantes.PVP, 0), 999999),
                IFNULL(NULLIF(tb_productos_variantes.PVPReducido, 0), 999999)
            )
        ) + $precioFinalMarca) >= '$precioMarcaDesde')
    AND ('$precioMarcaHasta' = '' OR 
        (COALESCE(
            (SELECT edv.PVP 
             FROM tb_escala_descuentos_variaciones edv
             JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
             WHERE edv.idVariacion = tb_productos_variantes.id 
             AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
             ORDER BY edv.cantidadRequerida DESC 
             LIMIT 1),
            LEAST(
                IFNULL(NULLIF(tb_productos_variantes.PVP, 0), 999999),
                IFNULL(NULLIF(tb_productos_variantes.PVPReducido, 0), 999999)
            )
        ) + $precioFinalMarca) <= '$precioMarcaHasta')
    AND ('$precioMarcaAntesImpuestosDesde' = '' OR 
        (COALESCE(
            (SELECT edv.PVPantesImpuestos 
             FROM tb_escala_descuentos_variaciones edv
             JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
             WHERE edv.idVariacion = tb_productos_variantes.id 
             AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
             ORDER BY edv.cantidadRequerida DESC 
             LIMIT 1),
            LEAST(
                IFNULL(NULLIF(tb_productos_variantes.PVPantesImpuestos, 0), 999999),
                IFNULL(NULLIF(tb_productos_variantes.PVPreducidoantesImpuestos, 0), 999999)
            )
        ) + $precioFinalMarca) >= '$precioMarcaAntesImpuestosDesde')
    AND ('$precioMarcaAntesImpuestosHasta' = '' OR 
        (COALESCE(
            (SELECT edv.PVPantesImpuestos 
             FROM tb_escala_descuentos_variaciones edv
             JOIN tb_valores_escalas_descuento ved ON edv.idValorEscalaDescuento = ved.id
             WHERE edv.idVariacion = tb_productos_variantes.id 
             AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
             ORDER BY edv.cantidadRequerida DESC 
             LIMIT 1),
            LEAST(
                IFNULL(NULLIF(tb_productos_variantes.PVPantesImpuestos, 0), 999999),
                IFNULL(NULLIF(tb_productos_variantes.PVPreducidoantesImpuestos, 0), 999999)
            )
        ) + $precioFinalMarca) <= '$precioMarcaAntesImpuestosHasta')
    AND ('$inventarioDesde' = '' OR tb_productos_variantes.inventario >= '$inventarioDesde')
GROUP BY 
    tb_productos_variantes.referenciaCPN, 
    urlImagen, 
    nombreColor, 
    descuentoPVPantesImpuestos,
    descuentoPVP,
    tb_productos_variantes.inventario, 
    tb_productos_variantes.wp_id,
    Nivel,
    minVenta,
    multiploVenta,
    precioMarcaAntesImpuestos
$orderByClause
LIMIT $pageSize OFFSET $offset;";

    $result = $conn->query($sql);

    if ($result === FALSE) {
        header('Content-Type: application/json');
        echo json_encode(['error' => $conn->error]);
        exit;
    }

    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

?>
<!DOCTYPE html>
<html>

<head>
    <title>Filtro Avanzado</title>

    <style>
        /* General styles for the wrapper */
        #buscador-wrapper {
            margin: 20px 0;
        }

        /* Styles for the search table */
        .search-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            padding: 10px;
            background-color: #0073aa;
            /* Blue background */
        }

        .search-table td {
            padding: 10px;
            color: white;
            /* White text */
            border: 1px solid #0073aa;
            /* Blue border to match background */
            background-color: #0073aa;
            /* Ensuring the background color is blue */
        }

        .search-table input[type="text"],
        .search-table input[type="number"] {
            width: calc(100% - 20px);
            padding: 5px;
            margin: 5px 0;
            background-color: white;
            /* White background for input fields */
            color: black;
            /* Black text for input fields */
        }

        .full-width {
            width: 100%;
        }

        .third-width {
            width: 33.33%;
        }

        .search-table tr:hover,
        .search-table td:hover {
            background-color: #0073aa !important;
            /* Remove hover effect */
        }

        /* Styles for the results table */
        .results-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            border: 1px solid #ddd;
        }

        .results-table th,
        .results-table td {
            padding: 10px;
            text-align: left;
            border: 1px solid #ddd;
            font-size: 14px;
            /* Adjust the font size */
        }

        .results-table th {
            background-color: #0073aa;
            /* Blue background */
            color: white;
            /* White text */
        }

        .results-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .results-table tr:hover {
            background-color: #f1f1f1;
        }

        .results-table .image-col img {
            width: 100px;
            height: auto;
        }

        .results-table .add-to-cart,
        .results-table .view-supplier {
            background-color: #0073aa;
            color: white;
            border: none;
            padding: 5px 10px;
            cursor: pointer;
            text-align: center;
            font-size: 14px;
            /* Adjust the font size */
        }

        .results-table .add-to-cart.disabled {
            background-color: #A9A9A9;
            /* Dark grey for disabled state */
            cursor: not-allowed;
        }

        .results-table .add-to-cart:hover:not(.disabled),
        .results-table .view-supplier:hover {
            background-color: #005f8d;
        }

        .results-table .price-col,
        .results-table .qty-col {
            text-align: center;
            width: 100px;
            /* Ensure columns have the same width */
        }

        /* Nivel background colors */
        .results-table .nivel-1 {
            background-color: #ffcccc;
            /* Light Red */
        }

        .results-table .nivel-2 {
            background-color: #ffffcc;
            /* Light Yellow */
        }

        .results-table .nivel-3 {
            background-color: #e0ccff;
            /* Light Purple */
        }

        .results-table .nivel-4 {
            background-color: #ccffcc;
            /* Light Green */
        }

        .results-table .nivel-5 {
            background-color: #cce0ff;
            /* Light Blue */
        }

        .results-table .nivel-6 {
            background-color: #003366;
            /* Dark Blue */
            color: white;
        }

        .price-marca {
            background-color: #cce0ff;
            /* Light Blue background */
        }

        @media screen and (max-width: 600px) {

            .results-table,
            .results-table th,
            .results-table td {
                display: block;
                width: 100%;
            }

            .results-table th {
                display: none;
                /* Hide table headers */
            }

            .results-table td {
                display: flex;
                justify-content: space-between;
                align-items: center;
                text-align: left;
                /* Align content to the left */
                padding: 10px;
                box-sizing: border-box;
                position: relative;
                border: none;
                /* Remove borders for a cleaner look */
            }

            .results-table tr {
                display: flex;
                flex-direction: column;
                margin-bottom: 10px;
                border: 1px solid #ddd;
            }

            .results-table td::before {
                content: attr(data-label);
                font-weight: bold;
                flex: 1;
                padding-right: 10px;
                text-align: left;
                min-width: 120px;
                /* Ensure a consistent width for labels */
            }

            .results-table td {
                flex: 2;
                text-align: right;
                /* Ensure the value is on the right */
            }

            .filter-input {
                width: 100%;
                padding: 10px;
                margin: 5px 0;
                box-sizing: border-box;
            }

            .add-to-cart,
            .view-supplier {
                width: 100%;
                text-align: center;
            }
        }

        #loading {
            display: none;
            text-align: center;
            margin: 20px 0;
        }

        /* Modal styles */
        #modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgb(0, 0, 0);
            background-color: rgba(0, 0, 0, 0.4);
            padding-top: 60px;
        }

        #modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        #close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        #close:hover,
        #close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="buscador-wrapper">
        <form id="searchForm">
            <table class="search-table">
                <tbody>
                    <tr>
                        <td colspan="3" class="full-width">
                            ¿Qué producto buscas? Ejemplo "Bolígrafo Azul" (La búsqueda se actualiza al escribir)
                            <input type="text" class="filter-input full-width" id="searchTerm">
                        </td>
                    </tr>
                    <tr>
                        <td class="third-width">
                            Que cantidad necesitas (Opcional). El sistema calculará el precio para la cantidad ingresada
                            <input type="number" class="filter-input" id="inventarioDesde" value="1">
                            Sabes la referencia? (Opcional)
                            <input type="text" class="filter-input" id="referenciaCPN">
                        </td>
                        <td class="third-width">
                            Rango antes de IVA (Opcional)
                            <br>Desde: <input type="number" class="filter-input" id="descuentoAntesImpuestosDesde">
                            <br>Hasta: <input type="number" class="filter-input" id="descuentoAntesImpuestosHasta">
                        </td>
                        <td class="third-width">
                            Rango IVA Incluido (Opcional)
                            <br>Desde: <input type="number" class="filter-input" id="descuentoDesde">
                            <br>Hasta: <input type="number" class="filter-input" id="descuentoHasta">
                        </td>
                    </tr>
                    <tr>
                        <td class="third-width">
                            Precio con Marca IVA Incl. (Opcional)
                            <br>Desde: <input type="number" class="filter-input" id="precioMarcaDesde">
                            <br>Hasta: <input type="number" class="filter-input" id="precioMarcaHasta">
                        </td>
                        <td class="third-width">
                            Precio con Marca Antes de IVA (Opcional)
                            <br>Desde: <input type="number" class="filter-input" id="precioMarcaAntesImpuestosDesde">
                            <br>Hasta: <input type="number" class="filter-input" id="precioMarcaAntesImpuestosHasta">
                        </td>
                    </tr>
                </tbody>
            </table>
        </form>
        <button id="actualizar">Actualizar</button>
        <p>(*) Precios aproximados por la cantidad ingresada, pero el descuento se aplicará al finalizar la compra. Click para ordenar</p>
        <table class="results-table">
            <thead>
                <tr>
                    <th>Referencia</th>
                    <th>Imagen</th>
                    <th>Nombre (Click para ver)</th>
                    <th>Nivel</th>
                    <th class="sortable price-col" data-sort="descuentoPVPantesImpuestos">Precio antes de IVA (*)</th>
                    <th class="sortable price-col" data-sort="descuentoPVP">Precio Iva Inc (*)</th>
                    <th class="sortable price-col price-marca" data-sort="precioMarcaAntesImpuestos">Precio con Marca Antes de IVA</th>
                    <th class="sortable price-col price-marca" data-sort="precioMarcaConImpuestos">Precio con Marca IVA Incl.</th>
                    <th class="sortable qty-col" data-sort="inventario">Stock</th>
                    <th>Acción</th>
                    <th>Ver en Proveedor</th>
                </tr>
            </thead>
            <tbody id="productTableBody">
                <!-- Rows will be inserted here by JavaScript -->
            </tbody>
        </table>
        <!-- Loading indicator -->
        <div id="loading">Cargando...</div>
    </div>

    <!-- Modal -->
    <div id="modal">
        <div id="modal-content">
            <span id="close">&times;</span>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            var orderBy = '';
            var orderDir = 'ASC';
            var page = 1;
            var pageSize = 10;
            var loading = false;
            var allDataLoaded = false;

            function addDataLabels() {
                $('.results-table th').each(function(index) {
                    var headerText = $(this).text();
                    $('.results-table tr').each(function() {
                        $(this).find('td').eq(index).attr('data-label', headerText);
                    });
                });
            }

            function calculateQuantity(minVenta, multiploVenta, inventarioDesde) {
                let qty = Math.max(minVenta, inventarioDesde);
                if (qty % multiploVenta !== 0) {
                    qty = Math.ceil(qty / multiploVenta) * multiploVenta;
                }
                return qty;
            }

            function updateAddToCartButtons() {
                var qty = parseInt($('#inventarioDesde').val(), 10);
                $('.add-to-cart').each(function() {
                    var minVenta = parseInt($(this).data('minventa'), 10);
                    var multiploVenta = parseInt($(this).data('multiploventa'), 10);
                    var adjustedQty = calculateQuantity(minVenta, multiploVenta, qty);
                    $(this).text('Agregar ' + adjustedQty + ' und');
                    $(this).data('adjustedqty', adjustedQty);
                });
            }

            function applyNivelBackground() {
                $('td.nivel-col').each(function() {
                    var nivelText = $(this).text().trim();
                    switch (nivelText) {
                        case 'Nivel 1':
                            $(this).addClass('nivel-1');
                            break;
                        case 'Nivel 2':
                            $(this).addClass('nivel-2');
                            break;
                        case 'Nivel 3':
                            $(this).addClass('nivel-3');
                            break;
                        case 'Nivel 4':
                            $(this).addClass('nivel-4');
                            break;
                        case 'Nivel 5':
                            $(this).addClass('nivel-5');
                            break;
                        case 'Nivel 6':
                            $(this).addClass('nivel-6');
                            break;
                        default:
                            break;
                    }
                });
            }

            $('#inventarioDesde').on('input', function() {
                updateAddToCartButtons();
            });

            $('.sortable').on('click', function() {
                var sortField = $(this).data('sort');
                if (orderBy === sortField) {
                    orderDir = (orderDir === 'ASC') ? 'DESC' : 'ASC';
                } else {
                    orderBy = sortField;
                    orderDir = 'ASC';
                }
                resetData();
                filterData();
            });

            $('#actualizar').on('click', function() {
                resetData();
                filterData();
            });

            $(window).on('scroll', function() {
                if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) { // Trigger earlier
                    if (!loading && !allDataLoaded) {
                        page++;
                        filterData();
                    }
                }
            });

            $('.filter-input').on('keyup change', function() {
                resetData();
                filterData();
            });

            function resetData() {
                page = 1;
                allDataLoaded = false;
                $('#productTableBody').html('');
            }

            function formatCurrency(value) {
                return new Intl.NumberFormat('es-CO', {
                    style: 'currency',
                    currency: 'COP',
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 0
                }).format(value);
            }

            function formatNumber(value) {
                return new Intl.NumberFormat('es-CO', {
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 0
                }).format(value);
            }

            function filterData() {
                var referenciaCPN = $('#referenciaCPN').val();
                var searchTerm = $('#searchTerm').val();
                var descuentoDesde = $('#descuentoDesde').val();
                var descuentoHasta = $('#descuentoHasta').val();
                var descuentoAntesImpuestosDesde = $('#descuentoAntesImpuestosDesde').val();
                var descuentoAntesImpuestosHasta = $('#descuentoAntesImpuestosHasta').val();
                var inventarioDesde = $('#inventarioDesde').val();
                var precioMarcaDesde = $('#precioMarcaDesde').val();
                var precioMarcaHasta = $('#precioMarcaHasta').val();
                var precioMarcaAntesImpuestosDesde = $('#precioMarcaAntesImpuestosDesde').val();
                var precioMarcaAntesImpuestosHasta = $('#precioMarcaAntesImpuestosHasta').val();

                // Obtener el precio final y tecnicaTipoRango desde localStorage
                var precioFinalMarca = localStorage.getItem('precioFinalMarca') || 0;
                var tecnicaTipoRango = localStorage.getItem('tecnicaTipoRango') || '';
                var precioFinalMarcaIva = precioFinalMarca * 1.19;

                loading = true;
                $('#loading').show(); // Mostrar indicador de carga

                $.ajax({
                    type: 'POST',
                    url: '../cotizaciones/buscadorcotizaciones.php', // Ruta del archivo PHP
                    data: {
                        referenciaCPN: referenciaCPN,
                        searchTerm: searchTerm,
                        descuentoDesde: descuentoDesde,
                        descuentoHasta: descuentoHasta,
                        descuentoAntesImpuestosDesde: descuentoAntesImpuestosDesde,
                        descuentoAntesImpuestosHasta: descuentoAntesImpuestosHasta,
                        inventarioDesde: inventarioDesde,
                        precioMarcaDesde: precioMarcaDesde,
                        precioMarcaHasta: precioMarcaHasta,
                        precioMarcaAntesImpuestosDesde: precioMarcaAntesImpuestosDesde,
                        precioMarcaAntesImpuestosHasta: precioMarcaAntesImpuestosHasta,
                        precioFinalMarca: precioFinalMarca,
                        tecnicaTipoRango: tecnicaTipoRango,
                        precioFinalMarcaIva: precioFinalMarcaIva,
                        orderBy: orderBy,
                        orderDir: orderDir,
                        page: page,
                        pageSize: pageSize,
                        idTabla: '<?php echo $idTabla; ?>', // Pasar idTabla desde PHP
                        idIngreso: '<?php echo $idIngreso; ?>' // Pasar idIngreso desde PHP
                    },
                    dataType: 'json',
                    success: function(data) {
                        if (data.error) {
                            console.error('Error:', data.error);
                            return;
                        }
                        if (data.length < pageSize) {
                            allDataLoaded = true;
                        }
                        var rows = '';
                        data.forEach(function(item) {
                            var adjustedQty = calculateQuantity(item.minVenta, item.multiploVenta, inventarioDesde);
                            var minVentaText = item.minVenta > 1 ? '<br>Venta mínima = ' + item.minVenta + ' unds' : '';
                            var multiploVentaText = item.multiploVenta > 1 ? '<br>Venta en múltiplos de ' + item.multiploVenta + ' unds' : '';

                            var marcaText = '';
                            if (precioFinalMarca > 0) {
                                marcaText = '<br>(' + formatCurrency(precioFinalMarcaIva) + ' de marca)';
                            }


                            var marcaText2 = '';
                            if (precioFinalMarca > 0) {
                                marcaText2 = '<br>(' + formatCurrency(precioFinalMarca) + ' de marca)';
                            }
                            var buttonClass = '<?php echo $idTabla; ?>' ? 'add-to-cart' : 'add-to-cart disabled';

                            rows += '<tr>' +
                                '<td data-label="Referencia">' + item.referenciaCPN + '</td>' +
                                '<td class="image-col" data-label="Imagen"><img src="' + item.urlImagen + '"></td>' +
                                '<td data-label="Nombre y Color"><a href="' + item.linkProducto + '" target="_blank">' + item.nombreColor + '</a></td>' +
                                '<td class="nivel-col" data-label="Nivel">' + (item.Nivel || 'Nivel 1') + '</td>' +
                                '<td class="price-col" data-label="Precio antes de IVA (*)">' + formatCurrency(item.descuentoPVPantesImpuestos) + '</td>' +
                                '<td class="price-col" data-label="Precio Iva Inc (*)">' + formatCurrency(item.descuentoPVP) + '</td>' +
                                '<td class="price-col price-marca" data-label="Precio con Marca Antes de IVA">' + formatCurrency(item.precioMarcaAntesImpuestos) + marcaText2 + '</td>' +
                                '<td class="price-col price-marca" data-label="Precio con Marca IVA Incl.">' + formatCurrency(item.precioMarcaConImpuestos) + marcaText + '</td>' +
                                '<td class="qty-col" data-label="Stock">' + item.inventario + '</td>' +
                                '<td data-label="Acción">' +
                                '<button class="' + buttonClass + '" data-id="' + item.idVariacion + '" data-name="' + item.nombreColor + '" data-minventa="' + item.minVenta + '" data-multiploventa="' + item.multiploVenta + '" data-adjustedqty="' + adjustedQty + '" data-idtabla="' + '<?php echo $idTabla; ?>' + '" data-idingreso="' + '<?php echo $idIngreso; ?>' + '" data-precioventa="' + item.precioMarcaAntesImpuestos + '">Agregar ' + adjustedQty + ' und</button>' +
                                minVentaText + multiploVentaText +
                                '</td>' +
                                '<td data-label="Ver en Proveedor"><button class="view-supplier" onclick="window.open(\'' + item.urlExterna + '\', \'_blank\')">Ver</button></td>' +
                                '</tr>';
                        });
                        $('#productTableBody').append(rows);
                        loading = false;
                        $('#loading').hide(); // Ocultar indicador de carga

                        updateAddToCartButtons(); // Actualizar botones inicialmente
                        applyNivelBackground(); // Aplicar colores de fondo a la columna Nivel
                        addDataLabels(); // Agregar atributos data-label

                        $('.add-to-cart').off('click').on('click', function() {
                            if ($(this).hasClass('disabled')) return;

                            var idTabla = $(this).data('idtabla');
                            var idIngreso = $(this).data('idingreso');
                            var idVariacion = $(this).data('id');
                            var cantidad = $(this).data('adjustedqty');
                            var precioVenta = $(this).data('precioventa');
                            var observaciones = precioFinalMarca > 0 ? 'Incluye ' + tecnicaTipoRango : 'No incluye marcacion';

                            console.log("Datos enviados:", {
                                idTabla: idTabla,
                                idIngreso: idIngreso,
                                idVariacion: idVariacion,
                                cantidad: cantidad,
                                precioVenta: precioVenta,
                                observaciones: observaciones
                            });

                            $.ajax({
                                type: 'POST',
                                url: '../cotizaciones/agregarProducto.php', // URL de tu script de inserción
                                data: {
                                    idTabla: idTabla,
                                    idIngreso: idIngreso,
                                    idVariacion: idVariacion,
                                    cantidad: cantidad,
                                    precioVenta: precioVenta,
                                    observaciones: observaciones
                                },
                                success: function(response) {
                                    console.log(response);
                                    alert('Producto agregado exitosamente');
                                    // Llamar a la función para refrescar los detalles de la cotización
                                    loadCotizacionDetails(idIngreso); // Asegúrate de que idIngreso esté definido y accesible
                                },
                                error: function(xhr, status, error) {
                                    console.error('Error al agregar producto:', status, error);
                                }
                            });
                        });

                        // Vincular evento click a botones view-supplier para el modal
                        $('.view-supplier').off('click').on('click', function() {
                            var url = $(this).data('url');
                            $('#modal-content').load(url, function(response, status, xhr) {
                                if (status == "error") {
                                    alert("Error: " + xhr.status + " " + xhr.statusText);
                                } else {
                                    $('#modal').show();
                                }
                            });
                        });
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX Error:', status, error);
                        loading = false;
                        $('#loading').hide(); // Ocultar indicador de carga
                    }
                });
            }

            // Cargar datos iniciales
            filterData();

            // Configuración del modal
            $('#close').on('click', function() {
                $('#modal').hide();
            });

            $(window).on('keydown', function(event) {
                if (event.key === 'Escape') {
                    $('#modal').hide();
                }
            });
        });

        // Función para cargar los detalles de la cotización
        function loadCotizacionDetails(cotizacionId) {
            $.ajax({
                url: '../cotizaciones/get_cotizacion_details.php',
                type: 'GET',
                data: {
                    cotizacionId: cotizacionId
                },
                dataType: 'json',
                success: function(data) {
                    let tipoCotizacionId = $('#tipoCotizacionSelect').val();
                    let tableContent = '';
                    let subtotal = 0;
                    let iva = 0;

                    data.forEach(item => {
                        let productoLink = `https://compranet.com.co/?p=${item.wp_id}`;
                        let imagenUrl = item.linkImagen.replace('J:/images', 'https://sistema.compranet.com.co/images/');
                        let subtotalItem = item.precioVenta * item.cantidad;
                        let ivaItem = subtotalItem * item.Impuesto;
                        let totalItem = subtotalItem + ivaItem;

                        if (tipoCotizacionId == 1) {
                            subtotal += subtotalItem;
                            iva += ivaItem;
                        }

                        tableContent += `
                    <tr>
                        <td>${item.referenciaCPN}</td>
                        <td><img src="${imagenUrl}" alt="Imagen" style="width: 50px; height: 50px;"></td>
                        <td><a href="${productoLink}" target="_blank">${item.Producto} - ${item.txtColor}</a></td>
                        <td contenteditable="true" class="editable qty-col" data-field="cantidad" data-id="${item.id}" style="background-color: #d1ecf1; text-align: right;">${item.cantidad}</td>
                        <td contenteditable="true" class="editable price-col" data-field="precioVenta" data-id="${item.id}" style="background-color: #d1ecf1; text-align: right;">${item.precioVenta.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                        <td class="price-col">${subtotalItem.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                        <td class="price-col">${ivaItem.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                        <td class="price-col">${totalItem.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                        <td contenteditable="true" class="editable" data-field="observaciones" data-id="${item.id}" style="background-color: #d1ecf1;">${item.observaciones}</td>
                        <td>${item.inventario}</td>
                        <td>${item.fechaActualizacion}</td>
                        <td><button class="btn btn-link" onclick="window.open('${item.urlExterna}', '_blank')">VerEx</button></td>
                        <td><button class="btn btn-link" onclick="openImagenWP(${item.id})">ImagenWP</button></td>
                        <td><button class="btn btn-danger delete-item" data-id="${item.id}">Eliminar</button></td>
                    </tr>
                `;
                    });

                    $('#cotizacionTable').html(tableContent);

                    if (tipoCotizacionId == 1) {
                        let total = subtotal + iva;
                        $('#totalesCotizacion').html(`
                    <tr>
                        <td colspan="5"></td>
                        <td>Subtotal</td>
                        <td>${subtotal.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                    </tr>
                    <tr>
                        <td colspan="5"></td>
                        <td>IVA</td>
                        <td>${iva.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                    </tr>
                    <tr>
                        <td colspan="5"></td>
                        <td>Total</td>
                        <td>${total.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                    </tr>
                `).show();
                    } else {
                        $('#totalesCotizacion').hide();
                    }

                    $('#cotizacionDetails').show();

                    $('.editable').blur(function() {
                        let field = $(this).data('field');
                        let id = $(this).data('id');
                        let value = $(this).text();

                        $.ajax({
                            url: '../cotizaciones/update_cotizacion_detalle.php',
                            type: 'POST',
                            data: {
                                field: field,
                                id: id,
                                value: value
                            },
                            success: function(response) {
                                console.log('Detalle de cotización actualizado.');
                                loadCotizacionDetails(cotizacionId);
                            },
                            error: function(xhr, status, error) {
                                console.log(xhr.responseText);
                            }
                        });
                    });

                    $('.editable').keydown(function(event) {
                        if (event.key === 'Enter') {
                            event.preventDefault();
                            $(this).blur();
                        }
                    });

                    $('.delete-item').click(function() {
                        let id = $(this).data('id');
                        $.ajax({
                            url: '../cotizaciones/delete_cotizacion_detalle.php',
                            type: 'POST',
                            data: {
                                id: id
                            },
                            success: function(response) {
                                console.log('Producto eliminado.');
                                loadCotizacionDetails(cotizacionId);
                            },
                            error: function(xhr, status, error) {
                                console.log(xhr.responseText);
                            }
                        });
                    });
                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText);
                }
            });
        }
    </script>
</body>

</html>