@extends('layouts.app')

@section('title', 'Gestión de Ventas')

@section('header', 'Gestión de Ventas')

@section('content')
    <div class="page-container">
        <div class="page-header">
            <h2 class="page-title">
                <i class="fa-solid fa-cash-register" style="color: var(--primary-color);"></i>
                Listado de Ventas
            </h2>
            <a href="{{ route('ventas.create') }}" class="btn btn-primary">
                <i class="fa-solid fa-plus"></i>
                Nueva Venta
            </a>
        </div>

        <div class="card">
            <div class="card-body p-0">
                @if ($ventas->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 número, cliente o fecha...">
                            <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="ventasTable">
                            <thead>
                                <tr>
                                    <th>N° Venta</th>
                                    <th>Cliente</th>
                                    <th>Fecha</th>
                                    <th>Total</th>
                                    <th>Tipo Pago</th>
                                    <th>Estado</th>
                                    <th class="text-center">Acciones</th>
                                </tr>
                            </thead>
                            <tbody id="ventasTableBody">
                                @foreach ($ventas as $venta)
                                    <tr>
                                        <td class="fw-bold">{{ $venta->numero_venta }}</td>
                                        <td>{{ $venta->cliente->nombre }} {{ $venta->cliente->apellido }}</td>
                                        <td>{{ $venta->fecha_venta->format('d/m/Y') }}</td>
                                        <td class="fw-bold">${{ number_format($venta->total, 0, ',', '.') }}</td>
                                        <td>
                                            @if($venta->tipo_pago === 'efectivo')
                                                <span class="badge badge-success">Efectivo</span>
                                            @elseif($venta->tipo_pago === 'tarjeta')
                                                <span class="badge badge-info">Tarjeta</span>
                                            @else
                                                <span class="badge badge-warning">Transferencia</span>
                                            @endif
                                        </td>
                                        <td>
                                            @if($venta->estado === 'completada')
                                                <span class="badge badge-success">Completada</span>
                                            @elseif($venta->estado === 'pendiente')
                                                <span class="badge badge-warning">Pendiente</span>
                                            @else
                                                <span class="badge badge-danger">Cancelada</span>
                                            @endif
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <a href="{{ route('ventas.show', $venta) }}"
                                                    class="btn-action btn-view" title="Ver">
                                                    <i class="fa-solid fa-eye"></i>
                                                </a>
                                                <a href="{{ route('ventas.pdf', $venta) }}"
                                                    class="btn-action" style="color: #ef4444;" title="Descargar PDF" target="_blank">
                                                    <i class="fa-solid fa-file-pdf"></i>
                                                </a>
                                                <form action="{{ route('ventas.destroy', $venta) }}" method="POST"
                                                    class="d-inline"
                                                    onsubmit="return confirmarEliminacion(event, 'Se devolverá el stock de los productos de esta venta.');">
                                                    @csrf
                                                    @method('DELETE')
                                                    <button type="submit" class="btn-action btn-delete" title="Eliminar">
                                                        <i class="fa-solid fa-trash-can"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                @endforeach
                            </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">{{ $ventas->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>
                @else
                    <div class="empty-state">
                        <p class="empty-message">No hay ventas registradas</p>
                        <a href="{{ route('ventas.create') }}" class="btn btn-primary">
                            Registrar primera venta
                        </a>
                    </div>
                @endif
            </div>
        </div>
    </div>

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

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

            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';
            });

            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;

            const pagesContainer = document.getElementById('paginationPages');
            pagesContainer.innerHTML = '';

            if (totalPages > 0) {
                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);
                }
            }

            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();
        }

        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();
            clearSearchBtn.style.display = searchTerm ? 'flex' : 'none';

            filteredRows = allRows.filter(row => {
                const cells = row.getElementsByTagName('td');
                const numero = cells[0].textContent.toLowerCase();
                const cliente = cells[1].textContent.toLowerCase();
                const fecha = cells[2].textContent.toLowerCase();

                return numero.includes(searchTerm) ||
                    cliente.includes(searchTerm) ||
                    fecha.includes(searchTerm);
            });

            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';
            }

            currentPage = 1;
            renderPagination();
        });

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

        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();
        });

        if (allRows.length > 0) {
            renderPagination();
        }
    </script>
@endsection
