@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row justify-content-center bg-white p-4 rounded shadow-sm">
        <div class="col-md-12">
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            @if (session('success'))
                <div class="alert alert-success">
                    {{ session('success') }}
                </div>
            @endif
        </div>
        <div class="col-md-12">
        <div class="mb-3">
            <h2 class="mb-3 text-start">Historial de Pagos</h2>
            <div class="d-flex flex-wrap align-items-end gap-2">
                <div class="d-flex flex-column" style="min-width: 200px;">
                    <label for="payDateFrom" class="form-label mb-1">Desde</label>
                    <input type="date" id="payDateFrom" class="form-control" autocomplete="off">
                </div>
                <div class="d-flex flex-column" style="min-width: 200px;">
                    <label for="payDateTo" class="form-label mb-1">Hasta</label>
                    <input type="date" id="payDateTo" class="form-control" autocomplete="off">
                </div>
                <button type="button" class="btn btn-primary" id="filterPayDateRange">Filtrar</button>
                <button type="button" class="btn btn-outline-secondary" id="resetPayDateRange">Mes actual</button>
                <div class="ms-auto d-flex gap-2">
                    <button
                        type="button"
                        class="btn btn-warning text-bold d-flex align-items-center gap-1"
                        download
                        data-bs-toggle="modal"
                        data-bs-target="#exportPaysModal"
                    >
                        <i class="bi bi-file"></i>
                        Excel
                    </button>
                    <a href="{{ route('admin_fit.pay.create') }}" class="btn btn-success d-flex align-items-center gap-1">
                        <i class="bi bi-plus-lg"></i>
                        Nuevo
                    </a>
                </div>
            </div>
        </div>
        <table
            id="payTable"
            class="table table-striped table-bordered"
        >
            <thead>
                <tr>
                    <th class="text-center">Estado</th>
                    <th class="text-center">Nombre</th>
                    <th class="text-center">Tipo de Pago</th>
                    <th class="text-center">Banco</th>
                    <th class="text-center">Monto</th>
                    <th class="text-center">Referencia</th>
                    <th class="text-center">Fecha de pago</th>
                    <th class="text-center">Acciones</th>
                </tr>
            </thead>
            <tbody>
                <!-- Los datos se cargarán via AJAX -->
            </tbody>
        </table>
        </div>
    </div>
</div>

<div class="modal fade" id="exportPaysModal" tabindex="-1" aria-labelledby="exportPaysModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="paysExportForm" method="POST" action="{{ route('admin_fit.pay.export') }}">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title" id="exportPaysModalLabel">Selecciona columnas para exportar</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="search_value" id="paysExportSearchValue" value="">
                    <input type="hidden" name="status" id="paysExportStatus" value="">
                    <input type="hidden" name="date_from" id="paysExportDateFrom" value="">
                    <input type="hidden" name="date_to" id="paysExportDateTo" value="">
                    <div class="row g-2">
                        @php
                            $exportFields = [
                                'status' => 'Estado',
                                'user_name' => 'Nombre',
                                'pay_type_name' => 'Tipo de Pago',
                                'bank_name' => 'Banco',
                                'amount' => 'Monto',
                                'reference' => 'Referencia',
                                'pay_date_formatted' => 'Fecha de Creación',
                            ];
                        @endphp

                        @foreach ($exportFields as $fieldKey => $fieldLabel)
                            <div class="col-12 col-md-6">
                                <div class="form-check">
                                    <input
                                        class="form-check-input"
                                        type="checkbox"
                                        value="{{ $fieldKey }}"
                                        id="exportPayField_{{ $fieldKey }}"
                                        name="fields[]"
                                        checked
                                    >
                                    <label class="form-check-label" for="exportPayField_{{ $fieldKey }}">
                                        {{ $fieldLabel }}
                                    </label>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-success">Descargar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
import { buildEndpoint } from '/resources/js/urlBuilder.js';
document.addEventListener('DOMContentLoaded', function () {
    // --- DataTable y filtro de fecha ---
    const payTable = $('#payTable');
    const dateFromInput = document.getElementById('payDateFrom');
    const dateToInput = document.getElementById('payDateTo');
    const filterDateRangeButton = document.getElementById('filterPayDateRange');
    const resetDateRangeButton = document.getElementById('resetPayDateRange');
    let payDataTable = null;

    if (payTable.length) {
        payDataTable = payTable.DataTable();
        // Si ya existe, destruir para reinicializar con ajax extendido
        payDataTable.destroy();
    }

    payDataTable = payTable.DataTable({
        processing: true,
        serverSide: true,
        scrollX: true,
        autoWidth: false,
        ajax: {
            url: buildEndpoint('admin-fit/pay/json'),
            type: 'GET',
            data: function (d) {
                d.date_from = dateFromInput?.value || null;
                d.date_to = dateToInput?.value || null;
            }
        },
        columns: [
            {
                data: 'status',
                name: 'status',
                render: function(data, type) {
                    if (type !== 'display') {
                        return data;
                    }
                    const status = String(data || '').trim();
                    let statusClass = 'text-muted';
                    if (status === 'Pendiente') {
                        statusClass = 'text-warning';
                    } else if (status === 'Aprobado') {
                        statusClass = 'text-success';
                    } else if (status === 'Rechazado') {
                        statusClass = 'text-danger';
                    }
                    return `<span class="fw-semibold ${statusClass}">${status || '-'}</span>`;
                }
            },
            { data: 'first_name', name: 'first_name' },
            { data: 'pay_type_name', name: 'pay_type_name' },
            { data: 'bank_name', name: 'bank_name' },
            { data: 'amount', name: 'amount' },
            { data: 'reference', name: 'reference' },
            { data: 'pay_date_formatted', name: 'pay_date_formatted' },
            {
                data: null,
                name: 'edit',
                orderable: false,
                searchable: false,
                render: function(data, type, row) {
                    return `
                        <div class="d-flex gap-2">
                            <a href="${buildEndpoint(`admin-fit/pay/${row.id}/edit`)}" class="btn btn-sm btn-warning">Editar</a>
                        </div>
                    `;
                }
            }
        ],
        order: [[0, 'desc']],
        language: {
            "processing":     "Procesando...",
            "search":         "Buscar:",
            "lengthMenu":     "Mostrar _MENU_ registros",
            "info":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
            "infoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
            "infoFiltered":   "(filtrado de un total de _MAX_ registros)",
            "infoPostFix":    "",
            "loadingRecords": "Cargando...",
            "zeroRecords":    "No se encontraron resultados",
            "emptyTable":     "Ningún dato disponible en esta tabla",
            "paginate": {
                "first":      "Primero",
                "previous":   "Anterior",
                "next":       "Siguiente",
                "last":       "Último"
            },
            "aria": {
                "sortAscending":  ": Activar para ordenar la columna de manera ascendente",
                "sortDescending": ": Activar para ordenar la columna de manera descendente"
            }
        }
    });

    filterDateRangeButton?.addEventListener('click', function() {
        payDataTable.ajax.reload();
    });

    resetDateRangeButton?.addEventListener('click', function() {
        if (dateFromInput) dateFromInput.value = '';
        if (dateToInput) dateToInput.value = '';
        payDataTable.ajax.reload();
    });

    // --- Exportar Excel: sincronizar filtros ---
    const paysExportForm = document.getElementById('paysExportForm');
    const exportModalEl = document.getElementById('exportPaysModal');
    if (paysExportForm && exportModalEl) {
        exportModalEl.addEventListener('show.bs.modal', function () {
            // Sincronizar búsqueda global y filtros actuales de DataTable
            const searchValue = payDataTable.search() || '';
            const currentAjaxParams = payDataTable.ajax.params ? payDataTable.ajax.params() : null;
            const dateFrom = currentAjaxParams?.date_from || dateFromInput?.value || '';
            const dateTo = currentAjaxParams?.date_to || dateToInput?.value || '';
            document.getElementById('paysExportSearchValue').value = searchValue;
            document.getElementById('paysExportDateFrom').value = dateFrom;
            document.getElementById('paysExportDateTo').value = dateTo;
            // Si tienes filtro de status, sincronízalo aquí
            document.getElementById('paysExportStatus').value = '';
        });
        paysExportForm.addEventListener('submit', function(event) {
            const checkedFields = paysExportForm.querySelectorAll('input[name="fields[]"]:checked');
            if (checkedFields.length === 0) {
                event.preventDefault();
                alert('Selecciona al menos un campo para exportar.');
                return;
            }
            // Cierra el modal antes de enviar
            if (window.bootstrap?.Modal) {
                const modalInstance = window.bootstrap.Modal.getInstance(exportModalEl)
                    || new window.bootstrap.Modal(exportModalEl);
                modalInstance.hide();
            }
            paysExportForm.dataset.submitting = '1';
            setTimeout(() => {
                paysExportForm.submit();
            }, 180);
        });
    }
});
</script>

@endsection
