@extends('layouts.frontend')

@section('content')
<div class="container" style="min-height: 450px;">
    <div class="row archivio-news">
        <br>
        <div class="title-section col-sm-12">
            <h1 style="width: 90%"><span>Archivio Calendari</span></h1>
        </div>

        <div class="col-sm-12">
            <form id="archiveFilterForm">
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="season">Stagione:</label>
                            <select id="season" name="season_id" class="form-control">
                                <option value="">Seleziona Stagione</option>
                                @foreach($seasons as $season)
                                    <option value="{{ $season->id }}">{{ $season->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>

                <div class="row mt-3" id="typeSection" style="display: none;">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="type">Tipo:</label>
                            <select id="type" name="type" class="form-control">
                                <option value="">Seleziona Tipo</option>
                                @foreach($categories->pluck('type')->unique() as $type)
                                    <option value="{{ $type }}">
                                        @if($type == 'nation')
                                            NAZIONALE
                                        @elseif($type == 'region')
                                            REGIONALE
                                        @else
                                            {{ strtoupper($type) }}
                                        @endif
                                    </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>

                <div class="row mt-3" id="categorySection" style="display: none;">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="category">Categoria:</label>
                            <select id="category" name="category_id" class="form-control">
                                <option value="">Seleziona Categoria</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="row mt-3" id="groupSection" style="display: none;">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="group">Gruppo:</label>
                            <select id="group" name="group_id" class="form-control">
                                <option value="">Seleziona Gruppo</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="row mt-4" id="resultSection" style="display: none;">
                    <div class="col-md-12 text-center">
                        <div id="searchButtonSection">
                            <button type="button" id="searchButton" class="btn btn-primary">
                                Vai al Calendario
                            </button>
                        </div>
                        <div id="noResultsSection" style="display: none;">
                            <p class="text-danger">Nessun calendario in archivio per i dati inseriti</p>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

@stop
@section('extra_js')
<script>
$(document).ready(function() {
    const categories = @json($categories);
    const groups = @json($groups);
    const archivedCalendars = @json($archivedCalendars);

    function findCalendarsForSeason(seasonId) {
        return archivedCalendars.filter(cal => cal.season_id === parseInt(seasonId));
    }

    function findCalendarsForType(seasonId, type) {
        return archivedCalendars.filter(cal =>
            cal.season_id === parseInt(seasonId) &&
            cal.category?.type === type
        );
    }

    function findCalendarsForCategory(seasonId, categoryId) {
        return archivedCalendars.filter(cal =>
            cal.season_id === parseInt(seasonId) &&
            cal.category_id === parseInt(categoryId)
        );
    }

    $('#season').on('change', function() {
        const seasonId = $(this).val();
        if (seasonId) {
            const seasonCalendars = findCalendarsForSeason(seasonId);
            if (seasonCalendars.length > 0) {
                $('#typeSection').show();
                $('#resultSection, #noResultsSection').hide();
            } else {
                $('#typeSection, #categorySection, #groupSection').hide();
                $('#resultSection').show();
                $('#searchButtonSection').hide();
                $('#noResultsSection').show();
            }
        } else {
            $('#typeSection, #categorySection, #groupSection, #resultSection').hide();
            $('#type, #category, #group').val('');
        }
    });

    $('#type').on('change', function() {
        const selectedType = $(this).val();
        const seasonId = $('#season').val();

        if (selectedType && seasonId) {
            const typeCalendars = findCalendarsForType(seasonId, selectedType);

            if (typeCalendars.length > 0) {
                const filteredCategories = categories.filter(cat =>
                    cat.type === selectedType &&
                    typeCalendars.some(cal => cal.category_id === cat.id)
                );

                const categorySelect = $('#category');
                categorySelect.empty().append('<option value="">Seleziona Categoria</option>');
                filteredCategories.forEach(category => {
                    categorySelect.append(`<option value="${category.id}">${category.name}</option>`);
                });

                $('#categorySection').show();
                $('#groupSection').hide();
                $('#group').val('');
                $('#resultSection, #noResultsSection').hide();
            } else {
                $('#categorySection, #groupSection').hide();
                $('#resultSection').show();
                $('#searchButtonSection').hide();
                $('#noResultsSection').show();
            }
        } else {
            $('#categorySection, #groupSection, #resultSection').hide();
            $('#category, #group').val('');
        }
    });

    $('#category').on('change', function() {
        const selectedCategoryId = $(this).val();
        const seasonId = $('#season').val();

        if (selectedCategoryId && seasonId) {
            const categoryCalendars = findCalendarsForCategory(seasonId, selectedCategoryId);

            if (categoryCalendars.length > 0) {
                const filteredGroups = groups.filter(group =>
                    group.category_id === parseInt(selectedCategoryId) &&
                    categoryCalendars.some(cal => cal.group_id === group.id)
                );

                if (filteredGroups.length > 0) {
                    const groupSelect = $('#group');
                    groupSelect.empty().append('<option value="">Seleziona Gruppo</option>');
                    filteredGroups.forEach(group => {
                        groupSelect.append(`<option value="${group.id}">${group.name}</option>`);
                    });
                    $('#groupSection').show();
                } else {
                    $('#searchButtonSection').show();
                    $('#noResultsSection').hide();
                }
                $('#resultSection').show();
            } else {
                $('#groupSection').hide();
                $('#resultSection').show();
                $('#searchButtonSection').hide();
                $('#noResultsSection').show();
            }
        } else {
            $('#groupSection, #searchButtonSection').hide();
            $('#group').val('');
        }
    });

    $('#group').on('change', function() {
        const groupId = $(this).val();
        if (groupId) {
            $('#searchButtonSection').show();
            $('#noResultsSection').hide();
        }
    });

    $('#searchButton').on('click', function() {
        const seasonId = $('#season').val();
        const categoryId = $('#category').val();
        const groupId = $('#group').val();
        const type = $('#type').val();

        const calendar = archivedCalendars.find(cal =>
            cal.season_id === parseInt(seasonId) &&
            cal.category_id === parseInt(categoryId) &&
            (!groupId || cal.group_id === parseInt(groupId)) &&
            cal.category?.type === type
        );

        if (calendar) {
            const categorySlug = calendar.category.name.toLowerCase()
                .normalize('NFD')
                .replace(/[\u0300-\u036f]/g, '')
                .replace(/[^\w\s-]/g, '')
                .replace(/\s+/g, '-');

            const groupSlug = calendar.group ? calendar.group.name.toLowerCase()
                .normalize('NFD')
                .replace(/[\u0300-\u036f]/g, '')
                .replace(/[^\w\s-]/g, '')
                .replace(/\s+/g, '-')
                : '';

            const url = `/calendario/${categorySlug}-${groupSlug}/${calendar.id}`;
            window.location.href = url;
        }
    });
});
</script>
@stop
