@extends('layouts.app')

@section('css')
    <link rel="stylesheet" type="text/css"
        href="{{ asset('app-assets/vendors/css/tables/datatable/dataTables.bootstrap4.min.css') }}">
    <link rel="stylesheet" type="text/css"
        href="{{ asset('app-assets/vendors/css/tables/datatable/responsive.bootstrap4.min.css') }}">
    <link rel="stylesheet" type="text/css"
        href="{{ asset('app-assets/vendors/css/tables/datatable/buttons.bootstrap4.min.css') }}">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
@endsection

@section('content')
    <section id="competition-datatable">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <p><strong>Location:</strong> {{ $competition->location }}</p>
                        <p><strong>Date:</strong> {{ $competition->start_date }} to {{ $competition->end_date }}</p>

                        {{-- FILTER FORM --}}
                        <form method="GET" class="form-inline mb-3">
                            <label class="mr-2">Type:</label>
                            <select name="type" class="form-control mr-2">
                                <option value="">All Types</option>
                                <option value="Club" {{ request('type') == 'Club' ? 'selected' : '' }}>Club</option>
                                <option value="Academy" {{ request('type') == 'Academy' ? 'selected' : '' }}>Academy
                                </option>
                                <option value="FIG" {{ request('type') == 'FIG' ? 'selected' : '' }}>FIG</option>
                            </select>

                            <label class="mr-2">Apparatus:</label>
                            <select name="apparatus" id="apparatusFilter" class="form-control mr-2">
                                <option value="final" {{ request('apparatus') == 'final' ? 'selected' : '' }}>Final Result
                                </option>
                                @foreach ($apparatusList as $name)
                                    @php $slug = Str::slug($name); @endphp
                                    <option value="{{ $slug }}"
                                        {{ request('apparatus') == $slug ? 'selected' : '' }}>{{ $name }}</option>
                                @endforeach
                            </select>

                            <label class="mr-2">Level:</label>
                            <select name="level[]" class="form-control select2 mr-2" multiple>
                                @foreach ($levels as $level)
                                    <option value="{{ $level->id }}"
                                        {{ collect(request('level'))->contains($level->id) ? 'selected' : '' }}>
                                        {{ $level->name }}
                                    </option>
                                @endforeach
                            </select>

                            <label class="mr-2">Age Category:</label>
                            <select name="age_category[]" class="form-control select2 mr-2" multiple>
                                @foreach ($ageCategories as $age)
                                    <option value="{{ $age->id }}"
                                        {{ collect(request('age_category'))->contains($age->id) ? 'selected' : '' }}>
                                        {{ $age->name }}
                                    </option>
                                @endforeach
                            </select>

                            <button type="submit" class="btn btn-primary mr-2">Apply Filter</button>
                        </form>

                        {{-- ATHLETE LIST TABLE --}}
                        <div class="table-responsive">
                            <table id="athleteTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>ID</th>
                                        <th>Type</th>
                                        <th>Club</th>
                                        <th>Level</th>
                                        <th>Age Category</th>
                                        <th id="scoreHeader">Final Result</th>
                                        <th class="d-none">SortScore</th> {{-- hidden column for sorting --}}
                                    </tr>
                                </thead>
                                <tbody>

                                    @foreach ($athletes as $item)
                                        <tr>
                                            <td>{{ $item['athlete']->first_name }} {{ $item['athlete']->last_name }}</td>
                                            <td>{{ $item['athlete']->id }}</td>
                                            <td>{{ $item['athlete']->type }}</td>
                                            <td>{{ $item['athlete']->club->name ?? '-' }}</td>
                                            <td>{{ $item['athlete']->level->name ?? '-' }}</td>
                                            <td>{{ $item['athlete']->ageCategory->name ?? '-' }}</td>
                                            <td class="score" data-final="{{ $item['final'] }}"
                                                data-real-final="{{ $item['final'] }}"
                                                @foreach ($item['scores'] as $appName => $score)
                                                data-{{ Str::slug($appName) }}="{{ $score }}" @endforeach>

                                                {{ $item['final'] }}
                                            </td>
                                            <td class="sort-score d-none" data-sort="{{ $item['final'] }}">
                                                {{ $item['final'] }}</td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div> {{-- card-body --}}
                </div> {{-- card --}}
            </div>
        </div>
    </section>
@endsection

@section('js')
    <!-- Required for Excel export -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>

    <!-- DataTables core + extensions -->
    <script src="{{ asset('app-assets/vendors/js/tables/datatable/jquery.dataTables.min.js') }}"></script>
    <script src="{{ asset('app-assets/vendors/js/tables/datatable/dataTables.bootstrap4.min.js') }}"></script>
    <script src="{{ asset('app-assets/vendors/js/tables/datatable/dataTables.buttons.min.js') }}"></script>
    <script src="{{ asset('app-assets/vendors/js/tables/datatable/buttons.bootstrap4.min.js') }}"></script>
    <script src="{{ asset('app-assets/vendors/js/tables/datatable/buttons.html5.min.js') }}"></script>
    <script src="{{ asset('app-assets/vendors/js/tables/datatable/buttons.print.min.js') }}"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.colVis.min.js"></script>
    <script src="{{ asset('app-assets/vendors/js/tables/datatable/pdfmake.min.js') }}"></script>
    <script src="{{ asset('app-assets/vendors/js/tables/datatable/vfs_fonts.js') }}"></script>
    <script src="{{ asset('app-assets/js/scripts/datatables/datatable.js') }}"></script>

    <!-- Select2 -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        const serverSelectedApparatus = '{{ $selectedApparatus ?? 'final' }}';
        const globalTop3 = @json($globalTop3); // <-- IMPORTANT
    </script>

    <script>
        $(document).ready(function() {

            // ======================
            // INIT DATATABLE
            // ======================
            var table = $('#athleteTable').DataTable({
                paging: false,
                order: [
                    [7, 'desc']
                ],
                columnDefs: [{
                    targets: 7,
                    visible: false
                }],
                dom: 'Bfrtip',
                buttons: [{
                        extend: 'print',
                        text: 'Print Table',
                        className: 'btn btn-secondary'
                    },
                    {
                        extend: 'excelHtml5',
                        text: 'Export to Excel',
                        className: 'btn btn-success'
                    },
                    {
                        extend: 'csvHtml5',
                        text: 'Export to CSV',
                        className: 'btn btn-info'
                    },
                    {
                        extend: 'pdfHtml5',
                        text: 'Export to PDF',
                        className: 'btn btn-danger'
                    },
                    {
                        extend: 'colvis',
                        text: 'Show/Hide Columns',
                        className: 'btn btn-primary'
                    }
                ]
            });

            // ======================
            // UPDATE SCORES
            // ======================
            function updateScores(apparatus) {
                $('#scoreHeader').text(
                    apparatus === 'final' ?
                    'Final Result' :
                    apparatus.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
                );

                $('#athleteTable tbody tr').each(function() {
                    const scoreCell = $(this).find('.score');
                    const sortCell = $(this).find('.sort-score');

                    const newScore = scoreCell.data(apparatus) ?? 0;

                    scoreCell.attr('data-value', newScore);
                    scoreCell.text(newScore);
                    sortCell.text(newScore);
                });

                table.rows().invalidate().draw();
            }

            // ======================
            // MEDAL LOGIC
            // GLOBAL-BASED BUT FILTER-RESTRICTED
            // ======================
            function assignMedalsGlobal() {

                // remove medals (restore apparatus score only visually)
                $('#athleteTable tbody .score').each(function() {
                    const visibleScore = $(this).attr('data-value');
                    $(this).html(visibleScore);
                });

                const table = $('#athleteTable').DataTable();
                const visibleRows = table.rows({
                    search: 'applied'
                }).nodes();

                let visibleIDs = [];
                $(visibleRows).each(function() {
                    const id = parseInt($(this).find('td').eq(1).text());
                    visibleIDs.push(id);
                });

                const allTop3Visible = globalTop3.every(id => visibleIDs.includes(id));

                if (!allTop3Visible) return;

                // assign medals using REAL FINAL SCORE
                $(visibleRows).each(function() {
                    const id = parseInt($(this).find('td').eq(1).text());
                    const scoreCell = $(this).find('.score');
                    const realFinal = scoreCell.attr('data-real-final');

                    if (id === globalTop3[0]) {
                        scoreCell.html(realFinal + ' <span class="badge badge-warning">🥇</span>');
                    }
                    if (id === globalTop3[1]) {
                        scoreCell.html(realFinal + ' <span class="badge badge-secondary">🥈</span>');
                    }
                    if (id === globalTop3[2]) {
                        scoreCell.html(realFinal + ' <span class="badge badge-orange">🥉</span>');
                    }
                });
            }



            // ======================
            // INITIAL LOAD
            // ======================
            updateScores(serverSelectedApparatus);
            assignMedalsGlobal();

            // ======================
            // APPARATUS CHANGE
            // ======================
            $('#apparatusFilter').on('change', function() {
                updateScores($(this).val());
                assignMedalsGlobal();
            });

            // ======================
            // TABLE SORTING
            // ======================
            table.on('draw', function() {
                assignMedalsGlobal();
            });

            // ======================
            // FILTER EVENTS
            // ======================
            $('.select2, select[name="type"]').on('change', function() {
                setTimeout(assignMedalsGlobal, 80);
            });

            // ======================
            // INIT SELECT2
            // ======================
            $('.select2').select2({
                placeholder: 'Select options',
                allowClear: true,
                width: '200px'
            });
        });
    </script>
@endsection
