<?php
// include db connection
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// include db connection
include 'db/db.php';

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Handle AJAX request to filter data
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $referenciaCPN = $_POST['referenciaCPN'] ?? '';
    $nombreColor = $_POST['nombreColor'] ?? '';
    $descuentoDesde = $_POST['descuentoDesde'] ?? '';
    $descuentoHasta = $_POST['descuentoHasta'] ?? '';
    $descuentoAntesImpuestosDesde = $_POST['descuentoAntesImpuestosDesde'] ?? '';
    $descuentoAntesImpuestosHasta = $_POST['descuentoAntesImpuestosHasta'] ?? '';
    $inventarioDesde = $_POST['inventarioDesde'] ?? 0;
    $orderBy = $_POST['orderBy'] ?? '';
    $orderDir = $_POST['orderDir'] ?? 'ASC';
    $page = $_POST['page'] ?? 1;
    $pageSize = $_POST['pageSize'] ?? 10;

    // Prepare dynamic SQL for nombreColor
    $nombreColorCondition = "";
    if ($nombreColor !== '') {
        $words = explode(' ', $nombreColor);
        foreach ($words as $word) {
            $nombreColorCondition .= "CONCAT(tb_productos.nombre, ' - ', tb_productos_variantes.txtColor) LIKE '%$word%' AND ";
        }
        // Remove the trailing 'AND '
        $nombreColorCondition = rtrim($nombreColorCondition, ' AND ');
    } else {
        $nombreColorCondition = "1"; // True condition when no search term is provided
    }

    // Determine order by clause
    $orderByClause = "";
    if (in_array($orderBy, ['descuentoPVP', 'descuentoPVPantesImpuestos', 'inventario'])) {
        $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.wp_id AS idwpProducto,
        tb_productos_variantes.wp_id AS idwpProductoVariacion,
        CONCAT('https://compranet.com.co/?p=', tb_productos.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 ved.isVisible = 1 
             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 ved.isVisible = 1 
             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 ved.isVisible = 1 
             AND edv.cantidadRequerida <= " . intval($inventarioDesde) . "
             ORDER BY edv.cantidadRequerida DESC 
             LIMIT 1),
            'Nivel 1'
        ) AS Nivel
    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.wp_id > 0
        AND (tb_productos_variantes.referenciaCPN LIKE '%$referenciaCPN%' OR '$referenciaCPN' = '')
        AND ($nombreColorCondition)
        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 ved.isVisible = 1 
                 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 ved.isVisible = 1 
                 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 ved.isVisible = 1 
                 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 ved.isVisible = 1 
                 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 ('$inventarioDesde' = '' OR tb_productos_variantes.inventario >= '$inventarioDesde')
    GROUP BY 
        tb_productos_variantes.referenciaCPN, 
        urlImagen, 
        nombreColor, 
        descuentoPVPantesImpuestos,
        descuentoPVP,
        tb_productos_variantes.inventario, 
        tb_productos.wp_id,
        Nivel
    $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>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid black;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th.price-col, td.price-col {
            text-align: right;
        }
        th.qty-col, td.qty-col {
            text-align: right;
        }
        .filter-input {
            width: 100%;
            box-sizing: border-box;
        }
        .sortable:hover {
            cursor: pointer;
            text-decoration: underline;
        }
        .image-col img {
            width: 100px;
        }
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>Referencia</th>
                <th>Imagen</th>
                <th>Nombre y Color</th>
                <th>Nivel</th>
                <th class="sortable price-col" data-sort="descuentoPVP">Precio con Descuento</th>
                <th class="sortable price-col" data-sort="descuentoPVPantesImpuestos">Precio con Descuento Antes de Impuestos</th>
                <th class="sortable qty-col" data-sort="inventario">Cantidad Requerida</th>
                <th>Link</th>
            </tr>
            <tr>
                <th><input type="text" class="filter-input" id="referenciaCPN"></th>
                <th></th>
                <th><input type="text" class="filter-input" id="nombreColor"></th>
                <th></th>
                <th>
                    Desde: <input type="number" class="filter-input" id="descuentoDesde"><br>
                    Hasta: <input type="number" class="filter-input" id="descuentoHasta">
                </th>
                <th>
                    Desde: <input type="number" class="filter-input" id="descuentoAntesImpuestosDesde"><br>
                    Hasta: <input type="number" class="filter-input" id="descuentoAntesImpuestosHasta">
                </th>
                <th><input type="number" class="filter-input" id="inventarioDesde"></th>
                <th></th>
            </tr>
        </thead>
        <tbody id="productTableBody">
            <!-- Rows will be inserted here by JavaScript -->
        </tbody>
    </table>

    <script>
        $(document).ready(function() {
            var orderBy = '';
            var orderDir = 'ASC';
            var page = 1;
            var pageSize = 10;
            var loading = false;
            var allDataLoaded = false;

            $('.sortable').on('click', function() {
                var sortField = $(this).data('sort');
                if (orderBy === sortField) {
                    orderDir = (orderDir === 'ASC') ? 'DESC' : 'ASC';
                } else {
                    orderBy = sortField;
                    orderDir = 'ASC';
                }
                resetData();
                filterData();
            });

            $(window).on('scroll', function() {
                if ($(window).scrollTop() + $(window).height() >= $(document).height() - 10) {
                    if (!loading && !allDataLoaded) {
                        page++;
                        filterData();
                    }
                }
            });

            // Event listeners for the filter inputs
            $('.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 nombreColor = $('#nombreColor').val();
                var descuentoDesde = $('#descuentoDesde').val();
                var descuentoHasta = $('#descuentoHasta').val();
                var descuentoAntesImpuestosDesde = $('#descuentoAntesImpuestosDesde').val();
                var descuentoAntesImpuestosHasta = $('#descuentoAntesImpuestosHasta').val();
                var inventarioDesde = $('#inventarioDesde').val();

                // Log the filter values for debugging
                console.log({
                    referenciaCPN,
                    nombreColor,
                    descuentoDesde,
                    descuentoHasta,
                    descuentoAntesImpuestosDesde,
                    descuentoAntesImpuestosHasta,
                    inventarioDesde,
                    orderBy,
                    orderDir,
                    page,
                    pageSize
                });

                loading = true;

                $.ajax({
                    type: 'POST',
                    url: '', // Current page
                    data: {
                        referenciaCPN: referenciaCPN,
                        nombreColor: nombreColor,
                        descuentoDesde: descuentoDesde,
                        descuentoHasta: descuentoHasta,
                        descuentoAntesImpuestosDesde: descuentoAntesImpuestosDesde,
                        descuentoAntesImpuestosHasta: descuentoAntesImpuestosHasta,
                        inventarioDesde: inventarioDesde,
                        orderBy: orderBy,
                        orderDir: orderDir,
                        page: page,
                        pageSize: pageSize
                    },
                    dataType: 'json',
                    success: function(data) {
                        console.log('Received data:', data); // Log received data for debugging
                        if (data.error) {
                            console.error('Error:', data.error);
                            return;
                        }
                        if (data.length < pageSize) {
                            allDataLoaded = true;
                        }
                        var rows = '';
                        data.forEach(function(item) {
                            rows += '<tr>' +
                                '<td>' + item.referenciaCPN + '</td>' +
                                '<td class="image-col"><img src="' + item.urlImagen + '"></td>' +
                                '<td>' + item.nombreColor + '</td>' +
                                '<td>' + (item.Nivel || 'Nivel 1') + '</td>' +
                                '<td class="price-col">' + formatCurrency(item.descuentoPVP) + '</td>' +
                                '<td class="price-col">' + formatCurrency(item.descuentoPVPantesImpuestos) + '</td>' +
                                '<td class="qty-col">' + formatNumber(item.inventario) + '</td>' +
                                '<td><a href="' + item.linkProducto + '" target="_blank">Ver Producto</a></td>' +
                                '</tr>';
                        });
                        $('#productTableBody').append(rows);
                        loading = false;
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX Error:', status, error);
                        console.log(xhr.responseText); // Log the response text
                        loading = false;
                    }
                });
            }

            filterData(); // Load initial data
        });
    </script>
</body>
</html>
