@extends('layouts.app')
@section('content')
<div class="container-fluid  p-1 p-md-4 m-1 m-md-2">
    <div class="row justify-content-center">
        <div class="col-12 col-md-12 col-lg-8 p-0">
            <div class="card border-0 shadow-sm">
                 <div class="card-header d-flex justify-content-between align-items-center bg-dark text-white    ">
                    <span>Marcar asistencia</span>
                    <a href="{{ route('admin_fit.assistance.index') }}" class="btn btn-sm btn-secondary">
                     <i class="bi bi-chevron-left"></i>
                    Volver</a>
                </div>
                <div class="card-body bg-white">
                    @if(session('success'))
                        <div class="alert alert-success" role="alert">
                            {{ session('success') }}
                        </div>
                    @endif
                    @if(session('error'))
                        <div class="alert alert-danger" role="alert">
                            {{ session('error') }}
                        </div>
                    @endif
                    <div class="mb-4">
                        <div class="row g-2 align-items-end">
                            <div class="col-12 col-md-8">
                                <label for="entry_time_id" class="form-label">Horario</label>
                                <select id="entry_time_id" class="form-select">
                                    <option value="">Selecciona un horario</option>
                                    @foreach($entry_time as $time)
                                        <option value="{{ $time->id }}" {{ (string) $selectedEntryTimeId === (string) $time->id ? 'selected' : '' }}>
                                            {{ $time->entry_time }} - {{ $time->period }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-12 col-md-4 ms-md-auto">
                                <label for="passDate" class="form-label">Fecha de asistencia</label>
                                <input
                                    id="passDate"
                                    name="passDate"
                                    type="date"
                                    class="form-control"
                                    value="{{ $passDate }}"
                                >
                            </div>
                        </div>
                    </div>

                    <form method="GET" action="{{ route('admin_fit.assistance.takeAssistance') }}" class="mb-3 preserve-entry-time-form preserve-pass-date-form" style="position: sticky; top: 0; z-index: 5; background: #fff;">
                        <input type="hidden" name="entry_time_id" class="preserve-entry-time-input" value="{{ $selectedEntryTimeId ?? '' }}">
                        <input type="hidden" name="passDate" class="preserve-pass-date-input" value="{{ $passDate }}">
                        <label for="userSearch" class="form-label">Buscar por nombre o apellido</label>
                        <div class="row g-2">
                            <div class="col-12 col-md">
                                <input
                                    id="userSearch"
                                    name="userSearch"
                                    type="text"
                                    class="form-control"
                                    value="{{ $userSearch ?? '' }}"
                                    placeholder="Escribe para buscar usuarios"
                                >
                            </div>
                            <div class="col-12 col-md-auto d-flex gap-2">
                                <button type="submit" class="btn btn-warning flex-fill">Buscar</button>
                                <a href="{{ route('admin_fit.assistance.takeAssistance') }}" class="btn btn-info flex-fill">Limpiar</a>
                            </div>
                        </div>
                    </form>

                    <form id="multipleAssistanceForm" method="POST" action="{{ route('admin_fit.assistance.createMultipleAssistance') }}" class="mb-3 d-flex flex-column flex-md-row justify-content-md-end align-items-start align-items-md-center gap-2 preserve-entry-time-form preserve-pass-date-form">
                        @csrf
                        <input type="hidden" name="selected_entry_time_id" class="preserve-entry-time-input" value="{{ $selectedEntryTimeId ?? '' }}">
                        <input type="hidden" name="pass_date" class="preserve-pass-date-input" value="{{ $passDate }}">
                        <div class="d-flex align-items-center gap-2 order-1 w-100 w-md-auto">
                            <div class="form-check form-check-inline m-0">
                                <input class="form-check-input" type="checkbox" id="selectAll" onclick="toggleSelectAll(this)">
                                <label class="form-check-label" for="selectAll">Seleccionar todos</label>
                            </div>
                            <small id="selectedCount" class="text-muted">0 seleccionados</small>
                        </div>
                        <div id="warningSelectedCount" class="alert alert-warning py-2 px-3 my-2 d-none" role="alert" style="font-size:0.95em;">
                            <strong>Advertencia:</strong> Has seleccionado más de 10 asistencias (<span id="selectedCountWarning">0</span> seleccionadas). Revisa antes de continuar.
                        </div>
                        <div id="assistancesPayload"></div>
                        <button id="submitMultipleAssistance" type="submit" class="btn btn-sm btn-primary order-2" disabled>
                            Marcar seleccionados
                        </button>
                    </form>

                    @php
                        $selectedPassDate = \Illuminate\Support\Carbon::createFromFormat('Y-m-d', $passDate, config('app.timezone'));
                    @endphp
                    <div id="entryTimeUsersList" class="d-flex flex-column gap-2" style="max-height: 420px; overflow-y: auto;">
                        @forelse($entry_time_users as $entryUser)
                            @if($entryUser->user)
                                @php
                                    $hasAssistanceToday = $entryUser->user->assistance->contains(function ($assistance) use ($entryUser, $selectedPassDate) {
                                        return (int) $assistance->entry_time_id === (int) $entryUser->entry_time_id
                                            && optional($assistance->created_at)
                                                ->setTimezone(config('app.timezone'))
                                                ->isSameDay($selectedPassDate);
                                    });
                                @endphp
                                <div class="d-flex justify-content-between align-items-center py-1 px-3 border rounded bg-white"
                                     @if($hasAssistanceToday) style="background-color: #e9f9ee; border-color: #74c88b !important;" @endif
                                      data-entry-time-id="{{ $entryUser->entry_time_id }}"
                                      data-user-name="{{ mb_strtolower($entryUser->user->name ?? '') }}">
                                    <div class="d-flex align-items-center gap-2">
                                        @if(!$hasAssistanceToday)
                                            <input
                                                type="checkbox"
                                                class="form-check-input assist-check"
                                                data-user-id="{{ $entryUser->user->id }}"
                                                data-entry-time-id="{{ $entryUser->entry_time_id }}"
                                                aria-label="Seleccionar {{ $entryUser->user->name }}"
                                            >
                                        @endif
                                        <div class="fw-semibold">{{ $entryUser->user->name }}</div>
                                        {{-- <small class="text-muted">
                                            {{ optional(optional($entryUser->user->membership_users->first())->membership)->name ?? 'Sin membresia activa' }}
                                        </small> --}}
                                    </div>
                                    @if($hasAssistanceToday)
                                        <form method="POST" action="{{ route('admin_fit.assistance.removeAssistance') }}" class="m-0 preserve-entry-time-form preserve-pass-date-form">
                                            @csrf
                                            <input type="hidden" name="user_id" value="{{ $entryUser->user->id }}">
                                            <input type="hidden" name="entry_time_id" value="{{ $entryUser->entry_time_id }}">
                                            <input type="hidden" name="selected_entry_time_id" class="preserve-entry-time-input" value="{{ $selectedEntryTimeId ?? '' }}">
                                            <input type="hidden" name="pass_date" class="preserve-pass-date-input" value="{{ $passDate }}">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">Quitar</button>
                                        </form>
                                    @else
                                        <form method="POST" action="{{ route('admin_fit.assistance.storeAssistance') }}" class="m-0 preserve-entry-time-form preserve-pass-date-form">
                                            @csrf
                                            <input type="hidden" name="user_id" value="{{ $entryUser->user->id }}">
                                            <input type="hidden" name="entry_time_id" value="{{ $entryUser->entry_time_id }}">
                                            <input type="hidden" name="selected_entry_time_id" class="preserve-entry-time-input" value="{{ $selectedEntryTimeId ?? '' }}">
                                            <input type="hidden" name="pass_date" class="preserve-pass-date-input" value="{{ $passDate }}">
                                            <button type="submit" class="btn btn-sm btn-success">Marcar</button>
                                        </form>
                                    @endif
                                </div>
                            @endif
                        @empty
                            <div class="text-muted">No hay usuarios asignados.</div>
                        @endforelse
                    </div>

                    <div id="emptyMessage" class="text-muted mt-3 d-none">
                        No hay usuarios para el horario seleccionado.
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const select = document.getElementById('entry_time_id');
        const passDateInput = document.getElementById('passDate');
        const userSearchInput = document.getElementById('userSearch');
        const rows = Array.from(document.querySelectorAll('[data-entry-time-id]'));
        const emptyMessage = document.getElementById('emptyMessage');
        const submitMultipleAssistance = document.getElementById('submitMultipleAssistance');
        const selectedCount = document.getElementById('selectedCount');
        const multipleAssistanceForm = document.getElementById('multipleAssistanceForm');
        const assistancesPayload = document.getElementById('assistancesPayload');
        const selectAllCheckbox = document.getElementById('selectAll');
        const multipleFormEntryTimeInput = multipleAssistanceForm
            ? multipleAssistanceForm.querySelector('input[name="selected_entry_time_id"]')
            : null;
        const multipleFormPassDateInput = multipleAssistanceForm
            ? multipleAssistanceForm.querySelector('input[name="pass_date"]')
            : null;
        const checkboxes = Array.from(document.querySelectorAll('.assist-check'));
        const preserveEntryTimeForms = Array.from(document.querySelectorAll('.preserve-entry-time-form'));
        const preservePassDateForms = Array.from(document.querySelectorAll('.preserve-pass-date-form'));
        const flashAlerts = Array.from(document.querySelectorAll('.alert.alert-success, .alert.alert-danger'));

        flashAlerts.forEach(function (alert) {
            setTimeout(function () {
                alert.classList.add('d-none');
            }, 5000);
        });

        function syncSelectedEntryTimeForForms() {
            const selectedEntryTimeId = select ? select.value : '';

            if (multipleFormEntryTimeInput) {
                multipleFormEntryTimeInput.value = selectedEntryTimeId;
            }

            preserveEntryTimeForms.forEach(function (form) {
                const hiddenInput = form.querySelector('.preserve-entry-time-input');
                if (!hiddenInput) {
                    return;
                }

                hiddenInput.value = selectedEntryTimeId;
            });
        }

        function syncPassDateForForms() {
            const passDate = passDateInput ? passDateInput.value : '';

            if (multipleFormPassDateInput) {
                multipleFormPassDateInput.value = passDate;
            }

            preservePassDateForms.forEach(function (form) {
                const hiddenInput = form.querySelector('.preserve-pass-date-input');
                if (!hiddenInput) {
                    return;
                }

                hiddenInput.value = passDate;
            });
        }

        function updateMultipleActionState() {
            const checked = checkboxes.filter(function (checkbox) {
                return checkbox.checked;
            });

            submitMultipleAssistance.disabled = checked.length === 0;
            selectedCount.textContent = checked.length + ' seleccionados';

            // Mostrar advertencia si hay más de 10 seleccionados
            const warningDiv = document.getElementById('warningSelectedCount');
            const warningCount = document.getElementById('selectedCountWarning');
            if (warningDiv && warningCount) {
                if (checked.length > 10) {
                    warningDiv.classList.remove('d-none');
                    warningCount.textContent = checked.length;
                } else {
                    warningDiv.classList.add('d-none');
                }
            }

            if (!selectAllCheckbox) {
                return;
            }

            if (checkboxes.length === 0) {
                selectAllCheckbox.checked = false;
                selectAllCheckbox.indeterminate = false;
                return;
            }

            if (checked.length === 0) {
                selectAllCheckbox.checked = false;
                selectAllCheckbox.indeterminate = false;
                return;
            }

            if (checked.length === checkboxes.length) {
                selectAllCheckbox.checked = true;
                selectAllCheckbox.indeterminate = false;
                return;
            }

            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = true;
        }

        window.toggleSelectAll = function (source) {
            const shouldCheckAll = !!(source && source.checked);

            checkboxes.forEach(function (checkbox) {
                checkbox.checked = shouldCheckAll;
            });

            updateMultipleActionState();
        };

        function filterUsers() {
            const selectedId = select.value;
            const searchTerm = userSearchInput
                ? userSearchInput.value.trim().toLowerCase()
                : '';
            let visibleCount = 0;

            rows.forEach(function (row) {
                const rowEntryTimeId = row.getAttribute('data-entry-time-id');
                const rowUserName = (row.getAttribute('data-user-name') || '').toLowerCase();
                const matchesEntryTime = searchTerm
                    ? true
                    : (!selectedId || rowEntryTimeId === selectedId);
                const matchesSearch = !searchTerm || rowUserName.includes(searchTerm);
                const shouldShow = matchesEntryTime && matchesSearch;

                row.classList.toggle('d-none', !shouldShow);
                if (shouldShow) {
                    visibleCount++;
                }
            });

            emptyMessage.classList.toggle('d-none', visibleCount > 0);
        }

        function reloadBySelectedEntryTime() {
            const selectedEntryTimeId = select ? select.value : '';
            const url = new URL("{{ route('admin_fit.assistance.takeAssistance') }}", window.location.origin);

            if (selectedEntryTimeId) {
                url.searchParams.set('entry_time_id', selectedEntryTimeId);
            }

            if (userSearchInput) {
                const searchValue = userSearchInput.value.trim();
                if (searchValue) {
                    url.searchParams.set('userSearch', searchValue);
                }
            }

            if (passDateInput) {
                const passDateValue = passDateInput.value.trim();
                if (passDateValue) {
                    url.searchParams.set('passDate', passDateValue);
                }
            }

            window.location.href = url.toString();
        }

        checkboxes.forEach(function (checkbox) {
            checkbox.addEventListener('change', updateMultipleActionState);
        });

        multipleAssistanceForm.addEventListener('submit', async function (event) {
            syncSelectedEntryTimeForForms();
            syncPassDateForForms();

            if (multipleFormEntryTimeInput) {
                multipleFormEntryTimeInput.value = select ? select.value : '';
            }
            if (multipleFormPassDateInput) {
                multipleFormPassDateInput.value = passDateInput ? passDateInput.value : '';
            }

            const checked = checkboxes.filter(function (checkbox) {
                return checkbox.checked;
            });

            if (checked.length === 0) {
                event.preventDefault();
                return;
            }

            // Si hay más de 10 seleccionados, mostrar confirmación con SweetAlert2
            if (checked.length > 10 && window.Swal) {
                event.preventDefault();
                const result = await window.Swal.fire({
                    title: '¿Marcar asistencia masiva?',
                    html: `Se marcarán <b>${checked.length}</b> asistencias. ¿Deseas continuar?`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Sí, marcar',
                    cancelButtonText: 'Cancelar',
                    focusCancel: true
                });
                if (!result.isConfirmed) {
                    return;
                }
            }

            assistancesPayload.innerHTML = '';

            checked.forEach(function (checkbox, index) {
                const userId = checkbox.getAttribute('data-user-id');
                const entryTimeId = checkbox.getAttribute('data-entry-time-id');

                const userInput = document.createElement('input');
                userInput.type = 'hidden';
                userInput.name = 'assistances[' + index + '][user_id]';
                userInput.value = userId;
                assistancesPayload.appendChild(userInput);

                const entryInput = document.createElement('input');
                entryInput.type = 'hidden';
                entryInput.name = 'assistances[' + index + '][entry_time_id]';
                entryInput.value = entryTimeId;
                assistancesPayload.appendChild(entryInput);
            });
            // Si fue confirmada, enviar el formulario manualmente
            if (checked.length > 10 && window.Swal) {
                multipleAssistanceForm.submit();
            }
        });

        select.addEventListener('change', syncSelectedEntryTimeForForms);
        select.addEventListener('change', reloadBySelectedEntryTime);
        if (passDateInput) {
            passDateInput.addEventListener('change', syncPassDateForForms);
            passDateInput.addEventListener('change', reloadBySelectedEntryTime);
        }
        if (userSearchInput) {
            userSearchInput.addEventListener('input', filterUsers);
        }

        preserveEntryTimeForms.forEach(function (form) {
            if (form === multipleAssistanceForm) {
                return;
            }

            form.addEventListener('submit', function () {
                syncSelectedEntryTimeForForms();
                syncPassDateForForms();
            });
        });

        syncSelectedEntryTimeForForms();
        syncPassDateForForms();
        filterUsers();
        updateMultipleActionState();
    });
</script>
@endsection