<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title mb-0">View Annual Results</h4>
                </div>
                <div class="card-body">
                    <div class="row mb-4">
        <div class="col-12 mb-3">
            <label for="studentSearch" class="form-label">Search Student (Optional)</label>
            <div class="d-flex gap-2">
                <input wire:model.live="studentSearch" type="text" id="studentSearch" class="form-control" 
                       placeholder="Search by name or student ID...">
                @if($filteredStudentId)
                    <button wire:click="clearFilter" class="btn btn-outline-secondary">
                        <i class="fas fa-times me-1"></i>Clear Filter
                    </button>
                @endif
            </div>
            
            @if($filteredStudentId && $selectedStudent)
                <div class="mt-2 alert alert-info">
                    <i class="fas fa-filter me-2"></i>Showing results for: <strong>{{ $selectedStudent->name }}</strong> ({{ $selectedStudent->student_id }})
                </div>
            @endif
            
            @if($studentSearch && !$filteredStudentId)
                @php
                    $searchResults = $this->getStudentsForSearch();
                @endphp
                
                @if($searchResults->count() > 0)
                    <div class="mt-2 border rounded" style="max-height: 200px; overflow-y: auto;">
                        @foreach($searchResults as $student)
                            <div class="p-2 border-bottom cursor-pointer hover-bg-light" 
                                 wire:click="selectStudent({{ $student->id }})" 
                                 style="cursor: pointer;"
                                 onmouseover="this.style.backgroundColor='#f8f9fa'" 
                                 onmouseout="this.style.backgroundColor='white'">
                                <strong>{{ $student->name }}</strong> ({{ $student->student_id }})
                                @if($student->batch && $student->batch->schoolClass)
                                    <br><small class="text-muted">{{ $student->batch->schoolClass->display_name }} - {{ $student->batch->name }}</small>
                                @endif
                            </div>
                        @endforeach
                    </div>
                @endif
            @endif
        </div>
        
        <div class="col-md-12 col-lg-4">
            <label for="selectedYear" class="form-label">Select Year</label>
            <select wire:model.live="selectedYear" class="form-select" id="selectedYear">
                <option value="">Choose Year...</option>
                @foreach($years as $year)
                    <option value="{{ $year }}">{{ $year }}/{{ $year + 1 }}</option>
                @endforeach
            </select>
        </div>
        
        <div class="col-md-6 col-lg-4">
            <label for="classSelect" class="form-label">Select Class</label>
            <select wire:model.live="classId" id="classSelect" class="form-select">
                <option value="">Choose Class...</option>
                @foreach($classes as $class)
                    <option value="{{ $class->id }}">{{ $class->display_name }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-md-6 col-lg-4">
            <label for="batchSelect" class="form-label">Select Batch</label>
            <select wire:model.live="batchId" id="batchSelect" class="form-select" wire:key="batch-select-{{ $classId }}">
                <option value="">Choose Batch...</option>
                @foreach($batches as $batch)
                    <option value="{{ $batch->id }}">{{ $batch->name }}</option>
                @endforeach
            </select>
        </div>
    </div>

                    <div class="row mb-4">
                        <div class="col-12">
                            <button wire:click="loadResults"
                                    class="btn btn-lg {{ !$selectedYear ? 'btn-secondary' : 'btn-primary' }} px-4 py-2"
                                    wire:loading.attr="disabled"
                                {{ !$selectedYear ? 'disabled' : '' }}>
                                <span wire:loading.remove wire:target="loadResults">
                                    <i class="fas fa-search me-2"></i>Load Results
                                </span>
                                <span wire:loading wire:target="loadResults">
                                    <i class="fas fa-spinner fa-spin me-2"></i>Loading...
                                </span>
                            </button>
                        </div>
                    </div>

    @if($isLoaded)
        @if(count($approvedResults) > 0)
            <!-- Desktop Table -->
            <div class="d-none d-lg-block">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th>S/N</th>
                                <th>Student Name</th>
                                <th>Student ID</th>
                                <th>Class</th>
                                <th>Batch</th>
                                <th>Year</th>
                                <th>Approved Date</th>
                                <th>Approved By</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($approvedResults as $index => $result)
                                <tr>
                                    <td>{{ $index + 1 }}</td>
                                    <td>{{ $result['student']['name'] }}</td>
                                    <td>{{ $result['student']['student_id'] ?? 'N/A' }}</td>
                                    <td>{{ $result['class']['display_name'] ?? 'N/A' }}</td>
                                    <td>{{ $result['batch']['name'] ?? 'N/A' }}</td>
                                    <td>{{ $result['year'] }}/{{ $result['year'] + 1 }}</td>
                                    <td>{{ \Carbon\Carbon::parse($result['approved_at'])->format('M d, Y') }}</td>
                                    <td>{{ $result['approved_by']['name'] }}</td>
                                    <td>
                                        <button wire:click="viewStudentResult({{ $result['student']['id'] }}, {{ $result['year'] }})"
                                                class="btn btn-sm btn-success me-1">
                                            <i class="fas fa-eye me-1"></i>View
                                        </button>
                                        <a href="{{ route('results.print-student-annual', [$result['student']['student_id'], $result['year']]) }}" 
                                           class="btn btn-sm btn-primary me-1"
                                           onclick="window.open(this.href, 'printResult', 'width=794,height=1123,scrollbars=yes,resizable=yes'); return false;">
                                            <i class="fas fa-print me-1"></i>Print
                                        </a>
                                        @if($this->canUnapprove())
                                            <button onclick="confirmUnapproveAnnual('{{ $result['student']['id'] }}', '{{ $result['year'] }}', '{{ $result['student']['name'] }}')"
                                                    class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-times me-1"></i>Unapprove
                                            </button>
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Mobile Accordions -->
            <div class="d-lg-none">
                @foreach($approvedResults as $index => $result)
                    <div class="card mb-2">
                        <div class="card-header p-0">
                            <div class="d-flex">
                                <div class="flex-grow-1 p-3" data-bs-toggle="collapse" data-bs-target="#result{{ $index }}" style="cursor: pointer;">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <span class="badge bg-light text-dark me-2">{{ $index + 1 }}</span>
                                            <strong>{{ $result['student']['name'] }}</strong>
                                        </div>
                                        <div>
                                            <i class="fas fa-chevron-down text-muted" style="transform: rotate(0deg); transition: transform 0.3s ease;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="collapse" id="result{{ $index }}">
                            <div class="card-body">
                                <div class="mb-3">
                                    <div class="d-flex flex-wrap gap-2 mb-2">
                                        <span class="badge bg-primary">ID: {{ $result['student']['student_id'] ?? 'N/A' }}</span>
                                        <span class="badge bg-success">{{ $result['year'] }}/{{ $result['year'] + 1 }}</span>
                                    </div>
                                </div>
                                <p><strong>Student ID:</strong> {{ $result['student']['student_id'] ?? 'N/A' }}</p>
                                <p><strong>Class:</strong> {{ $result['class']['display_name'] ?? 'N/A' }}</p>
                                <p><strong>Batch:</strong> {{ $result['batch']['name'] ?? 'N/A' }}</p>
                                <p><strong>Approved By:</strong> {{ $result['approved_by']['name'] }}</p>
                                <p><strong>Approved On:</strong> {{ \Carbon\Carbon::parse($result['approved_at'])->format('M d, Y \a\t h:i A') }}</p>
                                <div class="d-flex flex-wrap gap-2">
                                    <button wire:click="viewStudentResult({{ $result['student']['id'] }}, {{ $result['year'] }})"
                                            class="btn btn-sm btn-success">
                                        <i class="fas fa-eye me-1"></i>View
                                    </button>
                                    <a href="{{ route('results.print-student-annual', [$result['student']['student_id'], $result['year']]) }}" 
                                       class="btn btn-sm btn-primary"
                                       onclick="window.open(this.href, 'printResult', 'width=794,height=1123,scrollbars=yes,resizable=yes'); return false;">
                                        <i class="fas fa-print me-1"></i>Print
                                    </a>
                                    @if($this->canUnapprove())
                                        <button onclick="confirmUnapproveAnnual('{{ $result['student']['id'] }}', '{{ $result['year'] }}', '{{ $result['student']['name'] }}')"
                                                class="btn btn-sm btn-outline-danger">
                                            <i class="fas fa-times me-1"></i>Unapprove
                                        </button>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        @else
            <div class="text-center py-4">
                <i class="fas fa-calendar-alt fa-3x text-muted mb-3"></i>
                <h5>No Approved Annual Results Found</h5>
                <p class="text-muted">No approved annual results found for the selected year.</p>
            </div>
        @endif
    @else
        <div class="text-center py-5">
            <i class="fas fa-calendar-alt fa-3x text-muted mb-3"></i>
            <p class="text-muted">Select year to view annual results</p>
        </div>
    @endif
    
    @if($selectedStudentData)
        <!-- Student Result Modal/Display -->
        <div class="modal fade show" style="display: block; background: rgba(0,0,0,0.5);" tabindex="-1">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <span class="modal-title text-light">Annual Result - {{ $selectedStudentData['student']->firstname }} {{ $selectedStudentData['student']->middlename }} {{ $selectedStudentData['student']->surname }}</span>
                        <button type="button" class="btn-close" wire:click="closeStudentResult"></button>
                    </div>
                    <div class="modal-body">
                        @include('results.partials.student-annual-result-display', ['data' => $selectedStudentData])
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" wire:click="closeStudentResult">Close</button>
                        <a href="{{ route('results.print-student-annual', [$selectedStudentData['student']->student_id, $selectedStudentData['year']]) }}" 
                           class="btn btn-primary"
                           onclick="window.open(this.href, 'printResult', 'width=794,height=1123,scrollbars=yes,resizable=yes'); return false;">
                            <i class="fas fa-print me-1"></i>Print Result
                        </a>
                    </div>
                </div>
            </div>
        </div>
    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function confirmUnapproveAnnual(studentId, year, studentName) {
        Swal.fire({
            title: 'Remove Annual Approval?',
            text: 'Are you sure you want to remove the annual approval for ' + studentName + ' (' + year + '/' + (parseInt(year) + 1) + ')?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d02f34',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Remove Approval',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Livewire.find(@this.id).call('unapproveResult', studentId, year);
            }
        });
    }
    
    document.addEventListener('shown.bs.collapse', function (e) {
        const chevron = e.target.previousElementSibling.querySelector('.fa-chevron-down');
        if (chevron) chevron.style.transform = 'rotate(180deg)';
    });
    
    document.addEventListener('hidden.bs.collapse', function (e) {
        const chevron = e.target.previousElementSibling.querySelector('.fa-chevron-down');
        if (chevron) chevron.style.transform = 'rotate(0deg)';
    });
</script>