@extends('layouts.self-paced-dashboard')

@section('title', 'Exam Results')
@section('page-title', 'Exam Results')
@section('page-subtitle', 'View and export all trainee exam results')

@section('hero-actions')
    <a href="{{ route('self-paced.dashboard.results.export') . '?' . http_build_query(request()->only(['course_id', 'passed', 'date_from', 'date_to'])) }}"
       class="inline-flex items-center gap-2 px-4 py-2 bg-white/10 hover:bg-white/20 text-white text-sm font-medium rounded-lg transition border border-white/30">
        <i class="fas fa-file-csv"></i> Export CSV
    </a>
@endsection

@section('content')
<div x-data="resultIndex()" x-init="init()">

    {{-- Filters & Search Bar --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4 mb-5">
        <div class="flex flex-col sm:flex-row gap-3 flex-wrap">

            {{-- Search --}}
            <div class="relative flex-1 min-w-[200px]">
                <span class="absolute inset-y-0 left-3 flex items-center text-gray-400 pointer-events-none">
                    <i class="fas fa-search text-sm"></i>
                </span>
                <input type="text"
                       x-model="search"
                       @input.debounce.400ms="fetchResults()"
                       placeholder="Search by trainee name or course…"
                       class="w-full pl-9 pr-4 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition">
            </div>

            {{-- Course filter --}}
            <select x-model="courseId"
                    @change="fetchResults()"
                    class="text-sm border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition bg-white">
                <option value="">All Courses</option>
                @foreach($courses as $course)
                    <option value="{{ $course->id }}">{{ $course->title }}</option>
                @endforeach
            </select>

            {{-- Pass/Fail filter --}}
            <select x-model="passed"
                    @change="fetchResults()"
                    class="text-sm border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition bg-white">
                <option value="">All Results</option>
                <option value="1">Passed</option>
                <option value="0">Failed</option>
            </select>

            {{-- Date From --}}
            <input type="date"
                   x-model="dateFrom"
                   @change="fetchResults()"
                   title="Date from"
                   class="text-sm border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition bg-white">

            {{-- Date To --}}
            <input type="date"
                   x-model="dateTo"
                   @change="fetchResults()"
                   title="Date to"
                   class="text-sm border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition bg-white">

            {{-- Clear --}}
            <button @click="clearFilters()"
                    x-show="search || courseId || passed !== '' || dateFrom || dateTo"
                    x-cloak
                    class="inline-flex items-center gap-1.5 px-3 py-2 text-sm text-gray-500 hover:text-gray-700 border border-gray-200 rounded-lg hover:bg-gray-50 transition">
                <i class="fas fa-times text-xs"></i> Clear
            </button>
        </div>
    </div>

    {{-- Table Card --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">

        {{-- Loading overlay --}}
        <div x-show="loading" x-cloak class="flex items-center justify-center py-16">
            <i class="fas fa-spinner fa-spin text-indigo-400 text-2xl"></i>
        </div>

        <div x-show="!loading" x-cloak>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr>
                            <th class="bg-indigo-50 text-indigo-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide w-10">#</th>
                            <th class="bg-purple-50 text-purple-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Trainee</th>
                            <th class="bg-blue-50 text-blue-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Course</th>
                            <th class="bg-green-50 text-green-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Score</th>
                            <th class="bg-amber-50 text-amber-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Result</th>
                            <th class="bg-teal-50 text-teal-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Threshold</th>
                            <th class="bg-rose-50 text-rose-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Date</th>
                            <th class="bg-gray-50 text-gray-600 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="results-tbody" class="divide-y divide-gray-50">
                        @include('self-paced.dashboard.results.partials.table', ['results' => $results])
                    </tbody>
                </table>
            </div>

            {{-- Pagination --}}
            @if($results->hasPages())
            <div class="px-4 py-3 border-t border-gray-100" id="results-pagination">
                {{ $results->links() }}
            </div>
            @endif
        </div>
    </div>

</div>
@endsection

@push('scripts')
<script>
function resultIndex() {
    return {
        search: '',
        courseId: '',
        passed: '',
        dateFrom: '',
        dateTo: '',
        loading: false,

        init() {
            const params = new URLSearchParams(window.location.search);
            this.search   = params.get('search')    || '';
            this.courseId = params.get('course_id') || '';
            this.passed   = params.get('passed')    ?? '';
            this.dateFrom = params.get('date_from') || '';
            this.dateTo   = params.get('date_to')   || '';
        },

        fetchResults(page) {
            this.loading = true;
            const params = new URLSearchParams();
            if (this.search)          params.set('search',    this.search);
            if (this.courseId)        params.set('course_id', this.courseId);
            if (this.passed !== '')   params.set('passed',    this.passed);
            if (this.dateFrom)        params.set('date_from', this.dateFrom);
            if (this.dateTo)          params.set('date_to',   this.dateTo);
            if (page)                 params.set('page',      page);

            axios.get('{{ route('self-paced.dashboard.results.index') }}?' + params.toString(), {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(res => {
                document.getElementById('results-tbody').innerHTML = res.data.html;
                const pag = document.getElementById('results-pagination');
                if (pag && res.data.pagination) pag.innerHTML = res.data.pagination;
            })
            .catch(() => {})
            .finally(() => { this.loading = false; });
        },

        clearFilters() {
            this.search   = '';
            this.courseId = '';
            this.passed   = '';
            this.dateFrom = '';
            this.dateTo   = '';
            this.fetchResults();
        },
    };
}
</script>
@endpush
