<?php $__env->startSection('title', 'Gestión de Proveedores'); ?>

<?php $__env->startSection('header', 'Gestión de Proveedores'); ?>

<?php $__env->startSection('content'); ?>
    <div class="page-container">
        <div class="page-header">
            <h2 class="page-title">
                <i class="fa-solid fa-truck" style="color: var(--primary-color);"></i>
                Listado de Proveedores
            </h2>
            <a href="<?php echo e(route('proveedores.create')); ?>" class="btn btn-primary">
                <i class="fa-solid fa-plus"></i>
                Nuevo Proveedor
            </a>
        </div>

        <div class="card">
            <div class="card-body p-0">
                <?php if($proveedores->count() > 0): ?>
                    <div class="search-container">
                        <div class="search-box">
                            <i class="fa-solid fa-magnifying-glass search-icon"></i>
                            <input type="text" id="searchInput" class="search-input"
                                placeholder="Buscar por nombre, documento o contacto...">
                            <button id="clearSearch" class="search-clear" style="display: none;">
                                <i class="fa-solid fa-xmark"></i>
                            </button>
                        </div>
                        <div id="searchResults" class="search-results"></div>
                    </div>
                    <div class="table-container-scroll">
                        <table class="table" id="proveedoresTable">
                            <thead>
                                <tr>
                                    <th>Documento</th>
                                    <th>Nombre / Empresa</th>
                                    <th>Contacto</th>
                                    <th class="text-center">Total Compras</th>
                                    <th>Teléfono</th>
                                    <th>Email</th>
                                    <th>Estado</th>
                                    <th>Fecha Registro</th>
                                    <th class="text-center">Acciones</th>
                                </tr>
                            </thead>
                            <tbody id="proveedoresTableBody">
                                <?php $__currentLoopData = $proveedores; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $proveedor): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <tr>
                                        <td class="fw-bold"><?php echo e($proveedor->documento); ?></td>
                                        <td><?php echo e($proveedor->nombre); ?></td>
                                        <td><?php echo e($proveedor->contacto ?? '-'); ?></td>
                                        <td class="text-center">
                                            <span class="badge badge-info"><?php echo e($proveedor->compras_count); ?></span>
                                        </td>
                                        <td><?php echo e($proveedor->telefono ?? '-'); ?></td>
                                        <td><?php echo e($proveedor->email ?? '-'); ?></td>
                                        <td>
                                            <span class="badge <?php echo e($proveedor->estado ? 'badge-success' : 'badge-danger'); ?>">
                                                <?php echo e($proveedor->estado ? 'Activo' : 'Inactivo'); ?>

                                            </span>
                                        </td>
                                        <td><?php echo e($proveedor->created_at->format('d/m/Y')); ?></td>
                                        <td>
                                            <div class="action-buttons">
                                                <a href="<?php echo e(route('proveedores.show', $proveedor)); ?>"
                                                    class="btn-action btn-view" title="Ver">
                                                    <i class="fa-solid fa-eye"></i>
                                                </a>
                                                <a href="<?php echo e(route('proveedores.edit', $proveedor)); ?>"
                                                    class="btn-action btn-edit" title="Editar">
                                                    <i class="fa-solid fa-pen-to-square"></i>
                                                </a>
                                                <form action="<?php echo e(route('proveedores.destroy', $proveedor)); ?>" method="POST"
                                                    class="d-inline"
                                                    onsubmit="return confirmarEliminacion(event, 'Este proveedor será eliminado permanentemente.');">
                                                    <?php echo csrf_field(); ?>
                                                    <?php echo method_field('DELETE'); ?>
                                                    <button type="submit" class="btn-action btn-delete" title="Eliminar">
                                                        <i class="fa-solid fa-trash-can"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="custom-pagination">
                        <div class="pagination-info">
                            <span>Mostrando <strong id="startItem">1</strong> a <strong id="endItem">10</strong> de
                                <strong id="totalItems"><?php echo e($proveedores->count()); ?></strong> registros</span>
                        </div>
                        <div class="pagination-controls">
                            <button class="pagination-btn" id="firstPage" title="Primera página">
                                <i class="fa-solid fa-angles-left"></i>
                            </button>
                            <button class="pagination-btn" id="prevPage" title="Anterior">
                                <i class="fa-solid fa-chevron-left"></i>
                            </button>
                            <div class="pagination-pages" id="paginationPages"></div>
                            <button class="pagination-btn" id="nextPage" title="Siguiente">
                                <i class="fa-solid fa-chevron-right"></i>
                            </button>
                            <button class="pagination-btn" id="lastPage" title="Última página">
                                <i class="fa-solid fa-angles-right"></i>
                            </button>
                        </div>
                        <div class="pagination-select">
                            <label>Registros por página:</label>
                            <select id="itemsPerPage" class="form-control-sm">
                                <option value="5">5</option>
                                <option value="10" selected>10</option>
                                <option value="25">25</option>
                                <option value="50">50</option>
                            </select>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="empty-state">
                        <p class="empty-message">No hay proveedores registrados</p>
                        <a href="<?php echo e(route('proveedores.create')); ?>" class="btn btn-primary">
                            Crear primer proveedor
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        // Paginación y búsqueda personalizada
        const allRows = Array.from(document.querySelectorAll('#proveedoresTableBody tr'));
        let filteredRows = [...allRows];
        let currentPage = 1;
        let itemsPerPage = 10;

        function renderPagination() {
            const totalPages = Math.ceil(filteredRows.length / itemsPerPage);

            // Mostrar/ocultar filas
            allRows.forEach(row => row.style.display = 'none');

            filteredRows.forEach((row, index) => {
                const start = (currentPage - 1) * itemsPerPage;
                const end = start + itemsPerPage;
                row.style.display = (index >= start && index < end) ? '' : 'none';
            });

            // Actualizar información
            const start = filteredRows.length > 0 ? (currentPage - 1) * itemsPerPage + 1 : 0;
            const end = Math.min(currentPage * itemsPerPage, filteredRows.length);
            document.getElementById('startItem').textContent = start;
            document.getElementById('endItem').textContent = end;
            document.getElementById('totalItems').textContent = filteredRows.length;

            // Renderizar botones de página
            const pagesContainer = document.getElementById('paginationPages');
            pagesContainer.innerHTML = '';

            if (totalPages > 0) {
                // Determinar rango de páginas a mostrar
                let startPage = Math.max(1, currentPage - 2);
                let endPage = Math.min(totalPages, currentPage + 2);

                if (currentPage <= 3) {
                    endPage = Math.min(5, totalPages);
                }
                if (currentPage >= totalPages - 2) {
                    startPage = Math.max(1, totalPages - 4);
                }

                for (let i = startPage; i <= endPage; i++) {
                    const pageBtn = document.createElement('button');
                    pageBtn.className = 'pagination-page' + (i === currentPage ? ' active' : '');
                    pageBtn.textContent = i;
                    pageBtn.onclick = () => goToPage(i);
                    pagesContainer.appendChild(pageBtn);
                }
            }

            // Habilitar/deshabilitar botones
            document.getElementById('firstPage').disabled = currentPage === 1 || totalPages === 0;
            document.getElementById('prevPage').disabled = currentPage === 1 || totalPages === 0;
            document.getElementById('nextPage').disabled = currentPage === totalPages || totalPages === 0;
            document.getElementById('lastPage').disabled = currentPage === totalPages || totalPages === 0;
        }

        function goToPage(page) {
            const totalPages = Math.ceil(filteredRows.length / itemsPerPage);
            currentPage = Math.max(1, Math.min(page, totalPages));
            renderPagination();
        }

        // Búsqueda en tiempo real
        const searchInput = document.getElementById('searchInput');
        const clearSearchBtn = document.getElementById('clearSearch');
        const searchResults = document.getElementById('searchResults');

        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase().trim();

            // Mostrar/ocultar botón de limpiar
            clearSearchBtn.style.display = searchTerm ? 'flex' : 'none';

            // Filtrar filas
            filteredRows = allRows.filter(row => {
                const cells = row.getElementsByTagName('td');
                const documento = cells[0].textContent.toLowerCase();
                const nombre = cells[1].textContent.toLowerCase();
                const contacto = cells[2].textContent.toLowerCase();
                const telefono = cells[4].textContent.toLowerCase();
                const email = cells[5].textContent.toLowerCase();

                return documento.includes(searchTerm) ||
                    nombre.includes(searchTerm) ||
                    contacto.includes(searchTerm) ||
                    telefono.includes(searchTerm) ||
                    email.includes(searchTerm);
            });

            // Actualizar resultados
            if (searchTerm && filteredRows.length === 0) {
                searchResults.innerHTML = '<p class="no-results">No se encontraron resultados para "' + searchTerm +
                    '"</p>';
                searchResults.style.display = 'block';
            } else if (searchTerm && filteredRows.length > 0) {
                searchResults.innerHTML = '<p class="results-found">Se encontraron ' + filteredRows.length +
                    ' resultado(s)</p>';
                searchResults.style.display = 'block';
            } else {
                searchResults.style.display = 'none';
            }

            // Resetear a la primera página
            currentPage = 1;
            renderPagination();
        });

        // Limpiar búsqueda
        clearSearchBtn.addEventListener('click', function() {
            searchInput.value = '';
            searchInput.dispatchEvent(new Event('input'));
            searchInput.focus();
        });

        // Event listeners de paginación
        document.getElementById('firstPage').addEventListener('click', () => goToPage(1));
        document.getElementById('prevPage').addEventListener('click', () => goToPage(currentPage - 1));
        document.getElementById('nextPage').addEventListener('click', () => goToPage(currentPage + 1));
        document.getElementById('lastPage').addEventListener('click', () => goToPage(Math.ceil(filteredRows.length /
            itemsPerPage)));

        document.getElementById('itemsPerPage').addEventListener('change', function() {
            itemsPerPage = parseInt(this.value);
            currentPage = 1;
            renderPagination();
        });

        // Inicializar paginación
        if (allRows.length > 0) {
            renderPagination();
        }
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\perfumeChimi\resources\views/proveedores/index.blade.php ENDPATH**/ ?>