<?php
// buscar_productos_simplificado.php
include 'db_connection.php';

// Parámetro de búsqueda
$searchQuery = isset($_GET['query']) ? trim($_GET['query']) : '';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

// Columnas en las que se buscará
$searchable_columns = [
    'CodigoInterno',
    'CodigoBarra',
    'NombreComercial',
    'laboratorio',
    'NombreGenerico',
];

// Paginación
$limit = 7;
$offset = ($page - 1) * $limit;

// Inicializar variables
$total_products = 0;
$total_pages = 0;
$products = [];

// Función para ejecutar una consulta preparada
function execute_prepared_query($conn, $sql, $types = '', $params = []) {
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return ['success' => false, 'message' => 'Error en la preparación de la consulta: ' . $conn->error];
    }
    if (!empty($types) && !empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    if (!$stmt->execute()) {
        return ['success' => false, 'message' => 'Error en la ejecución de la consulta: ' . $stmt->error];
    }
    $result = $stmt->get_result();
    if ($result === false && $types !== '') {
        return ['success' => false, 'message' => 'Error al obtener el resultado de la consulta: ' . $stmt->error];
    }
    if ($result) {
        $data = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        return ['success' => true, 'data' => $data];
    } else {
        $stmt->close();
        return ['success' => true, 'data' => []];
    }
}

$base_select_fields = "id, CodigoInterno, CodigoBarra, NombreComercial, NombreGenerico, laboratorio, PrecioVentaUnidad, PrecioVentaBlister, PrecioVentaMayor, PrecioVentaMixto, CostoUnidad, CostoBlister, CostoMayor, CostoMixto, CostoUnidadSinIva, CostoBlisterSinIva, CostoMayorSinIva, CostoMixtoSinIva, FechaIngreso, FechaVencimiento, existencia, exento_iva";

// Si hay una consulta de búsqueda
if (!empty($searchQuery)) {
    // 1. Búsqueda Exacta por CodigoInterno o CodigoBarra (LA MÁS ALTA PRIORIDAD)
    $exact_sql = "SELECT $base_select_fields FROM productos WHERE CodigoInterno = ? OR CodigoBarra = ? LIMIT ? OFFSET ?";
    $exact_params = [$searchQuery, $searchQuery, $limit, $offset];
    $exact_types = "ssii";
    $exact_result = execute_prepared_query($conn, $exact_sql, $exact_types, $exact_params);

    if ($exact_result['success'] && count($exact_result['data']) > 0) {
        $products = $exact_result['data'];
        $count_exact_sql = "SELECT COUNT(*) as total FROM productos WHERE CodigoInterno = ? OR CodigoBarra = ?";
        $count_exact_params = [$searchQuery, $searchQuery];
        $count_exact_types = "ss";
        $count_exact_result = execute_prepared_query($conn, $count_exact_sql, $count_exact_types, $count_exact_params);
        if ($count_exact_result['success'] && count($count_exact_result['data']) > 0) {
            $total_products = intval($count_exact_result['data'][0]['total']);
            $total_pages = ceil($total_products / $limit);
        }
    } else {
        // 2. NUEVO: Búsqueda por Frase Completa (SEGUNDA PRIORIDAD)
        $phrase_param = '%' . $searchQuery . '%';
        $phrase_search_columns = ['NombreComercial', 'NombreGenerico', 'laboratorio'];
        $phrase_where_clauses = [];
        foreach ($phrase_search_columns as $col) {
            $phrase_where_clauses[] = "$col LIKE ?";
        }
        $phrase_where_sql = implode(' OR ', $phrase_where_clauses);

        // Contar resultados de la frase
        $count_phrase_sql = "SELECT COUNT(*) as total FROM productos WHERE $phrase_where_sql";
        $count_phrase_params = array_fill(0, count($phrase_search_columns), $phrase_param);
        $count_phrase_types = str_repeat('s', count($phrase_search_columns));
        $count_phrase_result = execute_prepared_query($conn, $count_phrase_sql, $count_phrase_types, $count_phrase_params);

        if ($count_phrase_result['success'] && $count_phrase_result['data'][0]['total'] > 0) {
            $total_products = intval($count_phrase_result['data'][0]['total']);
            $total_pages = ceil($total_products / $limit);

            // Obtener productos de la frase
            $phrase_sql = "SELECT $base_select_fields FROM productos WHERE $phrase_where_sql LIMIT ? OFFSET ?";
            $phrase_params = array_merge($count_phrase_params, [$limit, $offset]);
            $phrase_types = $count_phrase_types . "ii";
            $phrase_result = execute_prepared_query($conn, $phrase_sql, $phrase_types, $phrase_params);

            if ($phrase_result['success']) {
                $products = $phrase_result['data'];
            }
        } else {
            // 3. Búsqueda por Términos Separados (FALLBACK - Lógica anterior)
            $terms = array_filter(explode(' ', $searchQuery));

            if (!empty($terms)) {
                $where_clauses = [];
                $params = [];
                $param_types = '';

                foreach ($terms as $term) {
                    $term_clauses = [];
                    foreach ($searchable_columns as $column) {
                        $term_clauses[] = "$column LIKE ?";
                        $params[] = '%' . $term . '%';
                        $param_types .= 's';
                    }
                    $where_clauses[] = '(' . implode(' OR ', $term_clauses) . ')';
                }

                $where_sql = implode(' AND ', $where_clauses);
                
                $count_partial_sql = "SELECT COUNT(*) as total FROM productos WHERE $where_sql";
                $count_partial_result = execute_prepared_query($conn, $count_partial_sql, $param_types, $params);

                if ($count_partial_result['success'] && count($count_partial_result['data']) > 0) {
                    $total_products = intval($count_partial_result['data'][0]['total']);
                    $total_pages = ceil($total_products / $limit);
                }
                
                $partial_sql = "SELECT $base_select_fields FROM productos WHERE $where_sql LIMIT ? OFFSET ?";
                $partial_params = array_merge($params, [$limit, $offset]);
                $partial_types = $param_types . "ii";
                $partial_result = execute_prepared_query($conn, $partial_sql, $partial_types, $partial_params);

                if ($partial_result['success']) {
                    $products = $partial_result['data'];
                }
            }
        }
    }
} else {
    // 4. Sin términos de búsqueda, devolver todos los productos con paginación
    $count_sql = "SELECT COUNT(*) as total FROM productos";
    $count_result = execute_prepared_query($conn, $count_sql);
    if ($count_result['success'] && count($count_result['data']) > 0) {
        $total_products = intval($count_result['data'][0]['total']);
        $total_pages = ceil($total_products / $limit);
    }

    $sql = "SELECT $base_select_fields FROM productos LIMIT ? OFFSET ?";
    $all_params = [$limit, $offset];
    $all_types = "ii";
    $all_result = execute_prepared_query($conn, $sql, $all_types, $all_params);

    if ($all_result['success']) {
        $products = $all_result['data'];
    }
}

// 5. Generar la tabla HTML con los resultados
$output = '
<link rel="stylesheet" href="editable_prices.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<style>
  table#productos-lista { border-collapse: collapse; width: 100%; }
  .date-field { cursor: pointer; }
  .existencia-field { font-weight: bold; }
  table#productos-lista th, table#productos-lista td {
    border: 1px solid #ddd;
    padding: 6px;
    text-align: left;
    font-size: .75rem;
    vertical-align: middle;
  }
  table#productos-lista th {
    background-color: #f0f0f0;
    color: #333;
  }
  table#productos-lista tr:nth-child(even) {
    background-color: #f9f9f9;
  }
  table#productos-lista tr:hover {
    background-color: #f5f5f5;
  }
  .btn-danger {
    background-color: #dc3545 !important;
    color: white !important;
  }
  .btn-sm {
    padding: .25rem .5rem;
    font-size: .75rem;
    line-height: 1.5;
    border-radius: .2rem;
  }
  .pagination {
    margin-top: 10px;
  }
  .editable {
    cursor: pointer;
    position: relative;
  }
  .editable:hover::after {
    content: "✎";
    position: absolute;
    right: 5px;
    color: #666;
  }
  .editing input {
    width: 100%;
    padding: 5px;
    border: 2px solid #007bff;
    border-radius: 3px;
    font-size: .75rem;
  }
  .save-indicator {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 10px 20px;
    background: rgba(40, 167, 69, 0.9);
    color: white;
    border-radius: 5px;
    display: none;
    z-index: 1000;
  }
  .costo-sin-iva {
      color: #888;
      font-size: 0.9em;
  }
</style>
<div class="save-indicator">Guardando cambios...</div>
<table id="productos-lista" class="table">
  <thead>
    <tr>
      <th>Códigos</th>
      <th>Nombre Comercial</th>
      <th>Nombre Genérico</th>
      <th>Laboratorio</th>
      <th>Costo Unidad</th>
      <th>Costo Blister</th>
      <th>Costo Mayor</th>
      <th>Costo Mixto</th>
      <th>Precio Venta Unidad</th>
      <th>Precio Venta Blister</th>
      <th>Venta Mayor</th>
      <th>Venta Mixto</th>
      <th>Fecha Ingreso</th>
      <th>Fecha Vencimiento</th>
      <th>Existencia</th>
      <th>Exento IVA</th>
      <th>Acciones</th>
    </tr>
  </thead>
  <tbody>
';

if (count($products) > 0) {
    foreach ($products as $row) {
        $codigoInterno   = htmlspecialchars($row['CodigoInterno'] ?? '', ENT_QUOTES, 'UTF-8');
        $codigoBarra     = htmlspecialchars($row['CodigoBarra'] ?? '', ENT_QUOTES, 'UTF-8');
        $nombreComercial = htmlspecialchars($row['NombreComercial'] ?? '', ENT_QUOTES, 'UTF-8');
        $nombreGenerico  = htmlspecialchars($row['NombreGenerico'] ?? '', ENT_QUOTES, 'UTF-8');
        $laboratorio     = htmlspecialchars($row['laboratorio'] ?? '', ENT_QUOTES, 'UTF-8');

        $precioUnidad    = number_format($row['PrecioVentaUnidad'] ?? 0, 2, '.', ',');
        $precioBlister   = number_format($row['PrecioVentaBlister'] ?? 0, 2, '.', ',');
        $precioMayor     = number_format($row['PrecioVentaMayor'] ?? 0, 2, '.', ',');
        $precioMixto     = number_format($row['PrecioVentaMixto'] ?? 0, 2, '.', ',');
        
        $costoUnidad     = number_format($row['CostoUnidad'] ?? 0, 2, '.', ',');
        $costoBlister    = number_format($row['CostoBlister'] ?? 0, 2, '.', ',');
        $costoMayor      = number_format($row['CostoMayor'] ?? 0, 2, '.', ',');
        $costoMixto      = number_format($row['CostoMixto'] ?? 0, 2, '.', ',');

        $costoUnidadSinIva = number_format($row['CostoUnidadSinIva'] ?? 0, 2, '.', ',');
        $costoBlisterSinIva = number_format($row['CostoBlisterSinIva'] ?? 0, 2, '.', ',');
        $costoMayorSinIva = number_format($row['CostoMayorSinIva'] ?? 0, 2, '.', ',');
        $costoMixtoSinIva = number_format($row['CostoMixtoSinIva'] ?? 0, 2, '.', ',');

        $checked = $row['exento_iva'] ? 'checked' : '';

        $output .= "
        <tr data-id='{$row['id']}'>
          <td>
            <div class='editable' data-field='CodigoInterno'><strong>{$codigoInterno}</strong></div>
            <div class='editable' data-field='CodigoBarra'><small style='color: #777;'>{$codigoBarra}</small></div>
          </td>
          <td><div class='editable' data-field='NombreComercial'>{$nombreComercial}</div></td>
          <td><div class='editable' data-field='NombreGenerico'>{$nombreGenerico}</div></td>
          <td><div class='editable' data-field='laboratorio'>{$laboratorio}</div></td>
          <td>
            <div class='editable' data-field='CostoUnidad'>Q {$costoUnidad}</div>
            <div class='costo-sin-iva'>Q {$costoUnidadSinIva}</div>
          </td>
          <td>
            <div class='editable' data-field='CostoBlister'>Q {$costoBlister}</div>
            <div class='costo-sin-iva'>Q {$costoBlisterSinIva}</div>
          </td>
          <td>
            <div class='editable' data-field='CostoMayor'>Q {$costoMayor}</div>
            <div class='costo-sin-iva'>Q {$costoMayorSinIva}</div>
          </td>
          <td>
            <div class='editable' data-field='CostoMixto'>Q {$costoMixto}</div>
            <div class='costo-sin-iva'>Q {$costoMixtoSinIva}</div>
          </td>
          <td><div class='editable' data-field='PrecioVentaUnidad'>Q {$precioUnidad}</div></td>
          <td><div class='editable' data-field='PrecioVentaBlister'>Q {$precioBlister}</div></td>
          <td><div class='editable' data-field='PrecioVentaMayor'>Q {$precioMayor}</div></td>
          <td><div class='editable' data-field='PrecioVentaMixto'>Q {$precioMixto}</div></td>
          <td><div class='editable date-field' data-field='FechaIngreso'>{$row['FechaIngreso']}</div></td>
          <td><div class='editable date-field' data-field='FechaVencimiento'>{$row['FechaVencimiento']}</div></td>
          <td><div class='editable existencia-field' data-field='existencia'>{$row['existencia']}</div></td>
          <td><input type='checkbox' class='exento-iva-check' data-id='{$row['id']}' {$checked}></td>
          <td> <button class='btn btn-danger btn-sm delete-product-btn' data-id='{$row['id']}' title='Eliminar producto'>Eliminar</button>
          </td>
        </tr>";
    }
} else {
    $output .= "<tr><td colspan='17' class='text-center'>No se encontraron productos.</td></tr>";
}

$output .= '</tbody></table>
<script src="editable_prices.js"></script>';

// 6. Generar la paginación (sin cambios en esta sección)
if ($total_pages > 1) {
    $output .= '<nav><ul class="pagination justify-content-center">';
    if ($page > 1) {
        $prev_page = $page - 1;
        $output .= '<li class="page-item"><a class="page-link" href="#" data-page="' . $prev_page . '">&laquo;</a></li>';
    } else {
        $output .= '<li class="page-item disabled"><span class="page-link">&laquo;</span></li>';
    }
    $max_display = 5;
    $start = max(1, $page - floor($max_display / 2));
    $end = min($total_pages, $start + $max_display - 1);
    if ($end - $start + 1 < $max_display) {
        $start = max(1, $end - $max_display + 1);
    }
    for ($i = $start; $i <= $end; $i++) {
        if ($i == $page) {
            $output .= '<li class="page-item active"><span class="page-link">' . $i . '</span></li>';
        } else {
            $output .= '<li class="page-item"><a class="page-link" href="#" data-page="' . $i . '">' . $i . '</a></li>';
        }
    }
    if ($page < $total_pages) {
        $next_page = $page + 1;
        $output .= '<li class="page-item"><a class="page-link" href="#" data-page="' . $next_page . '">&raquo;</a></li>';
    } else {
        $output .= '<li class="page-item disabled"><span class="page-link">&raquo;</span></li>';
    }
    $output .= '</ul></nav>';
}

echo $output;
?>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
// This script block is from buscar_productos_simplificado.php.
// The main delete logic will be in index.php's script block.
// Flatpickr initialization and inline editing logic from your original file:
$(document).ready(function() {
    // Function to initialize Flatpickr for date fields
    function initializeDatePickers() {
        // Ensure that Flatpickr is only initialized on elements that are not already Flatpickr instances.
        $('.date-field:not(.flatpickr-input)').each(function() {
            const cell = $(this);
            const originalDate = cell.text().trim(); // Get current date text
            cell.data('original-value', originalDate); // Store it

            flatpickr(this, {
                dateFormat: "Y-m-d",
                defaultDate: originalDate === "0000-00-00" || originalDate === "" ? null : originalDate, // Set defaultDate
                locale: "es", 
                allowInput: true,
                onClose: function(selectedDates, dateStr, instance) {
                    const currentCell = $(instance.element);
                    const field = currentCell.data('field');
                    const originalValue = currentCell.data('original-value');
                    
                    // Only save if the date string has changed
                    if (dateStr !== originalValue) {
                        saveChanges(currentCell, dateStr, field, dateStr); // Pass dateStr as value and displayValue
                    } else {
                         // If no change, ensure the display is correct (e.g. if user cleared and closed)
                        currentCell.removeClass('editing').html(originalValue);
                    }
                }
            });
        });
    }

    // Function to make a general (non-date) cell editable
    function makeEditable(element) {
        const cell = $(element);
        // Prevent re-initializing if already editing or if it's a date field handled by Flatpickr
        if (cell.hasClass('editing') || cell.hasClass('date-field')) {
            return;
        }

        const currentValue = cell.text().replace(/^Q\s*/, '').trim();
        const field = cell.data('field');
        const originalText = cell.html(); // Store full original HTML content
        
        cell.addClass('editing');
        cell.data('original-html', originalText); // Store original HTML
        cell.data('original-value', currentValue); // Store original raw value

        cell.html(`<input type='text' value='${currentValue}' class='form-control form-control-sm' style='width:100%; box-sizing: border-box;'>`);
        const input = cell.find('input');
        input.focus().select();

        input.blur(function() {
            const newValue = $(this).val().trim();
            // Only save if value has changed
            if (newValue !== cell.data('original-value')) {
                const displayValue = (field.startsWith('Costo') || field.startsWith('PrecioVenta')) && !field.startsWith('Fecha') && field !== 'existencia' 
                                     ? 'Q ' + parseFloat(newValue).toFixed(2) 
                                     : newValue;
                saveChanges(cell, newValue, field, displayValue);
            } else {
                cell.removeClass('editing').html(cell.data('original-html')); // Revert to original HTML
            }
        }).keypress(function(e) {
            if (e.which === 13) { // Enter key
                $(this).blur();
            } else if (e.which === 27) { // Escape key
                cell.removeClass('editing').html(cell.data('original-html')); // Revert and remove input
            }
        });
    }

    // Function to save changes (centralized)
    function saveChanges(cell, value, field, displayValue) {
        const row = cell.closest('tr');
        const id = row.data('id');
        const saveIndicator = $('.save-indicator');
        
        if(saveIndicator.length) saveIndicator.fadeIn();

        $.ajax({
            url: 'actualizar_producto.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                id: id,
                field: field,
                value: value // Send the raw, validated value
            }),
            success: function(response) {
                if (response.success) {
                    cell.removeClass('editing').html(displayValue);
                    cell.data('original-html', displayValue); // Update stored original display
                    cell.data('original-value', value); // Update stored original raw value for dates/numbers
                    if (field.startsWith('Fecha')) { // For dates, also update original-value to new date string
                        cell.data('original-value', value);
                    }

                } else {
                    alert('Error al guardar: ' + (response.message || 'Error desconocido'));
                    cell.removeClass('editing').html(cell.data('original-html')); // Revert on error
                }
            },
            error: function(jqXHR) {
                let errorMsg = 'Error de conexión al guardar los cambios.';
                if(jqXHR.responseJSON && jqXHR.responseJSON.message){
                    errorMsg = jqXHR.responseJSON.message;
                }
                alert(errorMsg);
                cell.removeClass('editing').html(cell.data('original-html')); // Revert on error
            },
            complete: function() {
                if(saveIndicator.length) saveIndicator.fadeOut();
            }
        });
    }

    // Call initializations
    initializeDatePickers();

    // Event delegation for editable fields, attached to #productTable
    // This is fine as #productTable's content is replaced, these handlers are on the static #productTable itself.
    $('#productTable').on('click', '.editable', function(e) {
        const target = $(this);
        if (target.hasClass('date-field')) {
            // For date fields, Flatpickr handles the click to open the calendar.
            // If it's already a flatpickr input, let flatpickr manage it.
            // If not, initializeDatePickers should have caught it.
            // We explicitly do nothing here to let Flatpickr open.
        } else if (!target.hasClass('editing')) {
            makeEditable(target);
        }
    });
     // Note: The `loadProducts` function in `index.php` should ideally call `initializeDatePickers()`
     // in its success callback to ensure Flatpickr is re-applied to new content.
     // Example in index.php's loadProducts success:
     // $('#productTable').html(data);
     // if (typeof initializeDatePickersGlobal === 'function') { initializeDatePickersGlobal(); }
     // Then define initializeDatePickersGlobal in a scope accessible by index.php or pass it.
});
</script>