@extends('judge.master')

@section('judge_content')
    @forelse ($rounds as $roundNumber => $rotations)
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h4>Main Judge Overview – Round {{ $roundNumber }}</h4>

                @if ($rotations->every(fn($r) => $r->status === 'active'))
                    <form id="complete-round-form-{{ $roundNumber }}"
                        action="{{ route('main_judge.completeRound', $roundNumber) }}" method="POST" style="display: none;">
                        @csrf
                    </form>

                    <button class="btn btn-success btn-sm" onclick="confirmCompleteRound({{ $roundNumber }})">
                        ✅ Mark Round {{ $roundNumber }} as Complete
                    </button>
                @endif
            </div>

            <div class="card-body">
                @foreach ($rotations as $rotation)
                    <div class="mb-4">
                        <h5 class="mb-1">
                            Group: {{ $rotation->group->name ?? '-' }} |
                            Apparatus: {{ $rotation->apparatus->name ?? '-' }}
                            <span class="badge badge-{{ $rotation->status === 'completed' ? 'success' : 'warning' }}">
                                {{ ucfirst($rotation->status) }}
                            </span>
                        </h5>

                        @php
                            $scores = \App\Models\Score::with(['athlete', 'judge'])
                                ->where('competition_id', $rotation->competition_id)
                                ->where('group_id', $rotation->group_id)
                                ->where('apparatus_id', $rotation->apparatus_id)
                                ->where('round_number', $rotation->round_number)
                                ->get();
                        @endphp

                        @if ($scores->isEmpty())
                            <p class="text-muted">No scores submitted yet.</p>
                        @else
                            <div class="table-responsive">
                                <table class="table table-sm table-bordered">
                                    <thead class="thead-light">
                                        <tr>
                                            <th>#</th>
                                            <th>Athlete Name</th>
                                            <th>D</th>
                                            <th>E1</th>
                                            <th>E2</th>
                                            <th>E3</th>
                                            <th>E4</th>
                                            <th>Bonus</th>
                                            <th>CR</th>
                                            <th>ND</th>
                                            <th>Final</th>
                                            <th>Judge</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach ($scores as $i => $score)
                                            <tr>
                                                <td>{{ $i + 1 }}</td>
                                                <td>{{ $score->athlete->first_name }} {{ $score->athlete->last_name }}
                                                </td>

                                                @php $disabled = $rotation->status === 'completed' ? 'disabled' : ''; @endphp

                                                @foreach (['d_score', 'e1_score', 'e2_score', 'e3_score', 'e4_score', 'bonus', 'cr_score', 'nd_score'] as $field)
                                                    <td>
                                                        <input type="number" step="0.1"
                                                            class="form-control form-control-sm ajax-score-input"
                                                            data-field="{{ $field }}"
                                                            data-score-id="{{ $score->id }}"
                                                            value="{{ $score->$field }}" style="width: 80px;"
                                                            {{ $disabled }}>
                                                    </td>
                                                @endforeach

                                                <td><strong>{{ $score->final_score }}</strong></td>
                                                <td>{{ $score->judge->first_name ?? '—' }}</td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        @endif
                    </div>
                @endforeach
            </div>
        </div>
    @empty
        <div class="card">
            <div class="card-body">
                <p>No rounds found for this competition.</p>
            </div>
        </div>
    @endforelse
@endsection
@section('js')
    <script>
        function confirmCompleteRound(roundNumber) {
            Swal.fire({
                title: `Mark Round ${roundNumber} as Complete?`,
                text: "This action will finalize the current round.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, mark complete'
            }).then((result) => {
                if (result.isConfirmed) {
                    document.getElementById('complete-round-form-' + roundNumber).submit();
                }
            });
        }
    </script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 2000,
            timerProgressBar: true,
            didOpen: (toast) => {
                toast.addEventListener('mouseenter', Swal.stopTimer)
                toast.addEventListener('mouseleave', Swal.resumeTimer)
            }
        });

        const inputs = document.querySelectorAll('.ajax-score-input');

        inputs.forEach(input => {
            input.addEventListener('change', function () {
                const field = this.dataset.field;
                const scoreId = this.dataset.scoreId;
                const value = this.value;

                fetch(`/scores/${scoreId}/update-field`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    body: JSON.stringify({ field, value })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Toast.fire({
                            icon: 'success',
                            title: data.message
                        });
                    } else {
                        Toast.fire({
                            icon: 'error',
                            title: data.message || 'Failed to update.'
                        });
                    }
                })
                .catch(() => {
                    Toast.fire({
                        icon: 'error',
                        title: 'An error occurred while saving.'
                    });
                });
            });
        });
    });
</script>


@endsection
