@extends('layouts.app')

@section('content')
    @php
        $hasFilters = ($filters['q'] ?? '') !== '' ||
                      ($filters['subject_id'] ?? '') !== '' ||
                      ($filters['school_id'] ?? '') !== '' ||
                      ($filters['grade'] ?? '') !== '' ||
                      ($filters['lang'] ?? '') !== '' ||
                      ($filters['year'] ?? '') !== '' ||
                      ($filters['active'] ?? '') !== '';
    @endphp

    <div class="row justify-content-center">
        <div class="col-12 col-xl-11">

            <div class="d-flex flex-wrap justify-content-between align-items-center mb-3 gap-2">
                <h1 class="h5 m-0">{{ __('app.admin.exams.title') }}</h1>
                <div class="d-flex flex-wrap gap-2">
                    <a href="{{ route('admin.dashboard') }}" class="btn btn-outline-secondary btn-sm">← {{ __('app.admin.exams.back') }}</a>
                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalCreate">
                        {{ __('app.admin.exams.actions.add_new') }}
                    </button>
                    <button id="filterToggleBtn" class="btn btn-outline-primary btn-sm"
                            data-bs-toggle="collapse" data-bs-target="#filtersCollapse" aria-expanded="{{ $hasFilters ? 'true' : 'false' }}">
                        {{ $hasFilters ? __('app.admin.exams.filters.hide_filters') : __('app.admin.exams.filters.show_filters') }}
                    </button>
                </div>
            </div>

            @if ($errors->any())
                <div class="alert alert-danger">{{ $errors->first() }}</div>
            @endif
            @if (session('status'))
                <div class="alert alert-success">{{ session('status') }}</div>
            @endif

            <div class="collapse {{ $hasFilters ? 'show' : '' }}" id="filtersCollapse">
                <div class="card shadow-sm mb-3">
                    <div class="card-header bg-white fw-semibold">{{ __('app.admin.exams.filters.title') }}</div>
                    <div class="card-body">
                        <form method="GET" action="{{ route('admin.exams.index') }}" class="row g-2 align-items-end">
                            <div class="col-12 col-md-3">
                                <label class="form-label">{{ __('app.admin.exams.filters.title_label') }}</label>
                                <input type="text" name="q" class="form-control" value="{{ $filters['q'] ?? '' }}" placeholder="{{ __('app.admin.exams.filters.title_label') }}">
                            </div>
                            <div class="col-6 col-md-2">
                                <label class="form-label">{{ __('app.admin.exams.filters.subject') }}</label>
                                <select name="subject_id" class="form-select">
                                    <option value="">{{ __('app.admin.exams.filters.all') }}</option>
                                    @foreach($subjects as $s)
                                        <option value="{{ $s->id }}" @selected(($filters['subject_id'] ?? '') == $s->id)>{{ $s->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-6 col-md-2">
                                <label class="form-label">{{ __('app.admin.exams.filters.school') }}</label>
                                <select name="school_id" class="form-select">
                                    <option value="">{{ __('app.admin.exams.filters.all') }}</option>
                                    @foreach($schools as $sc)
                                        <option value="{{ $sc->id }}" @selected(($filters['school_id'] ?? '') == $sc->id)>{{ $sc->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-6 col-md-1">
                                <label class="form-label">{{ __('app.admin.exams.filters.grade') }}</label>
                                <input type="text" name="grade" class="form-control" value="{{ $filters['grade'] ?? '' }}">
                            </div>
                            <div class="col-6 col-md-1">
                                <label class="form-label">{{ __('app.admin.exams.filters.lang') }}</label>
                                <select name="lang" class="form-select">
                                    <option value="">{{ __('app.admin.exams.filters.all') }}</option>
                                    <option value="en" @selected(($filters['lang'] ?? '')==='en')>EN</option>
                                    <option value="ar" @selected(($filters['lang'] ?? '')==='ar')>AR</option>
                                </select>
                            </div>
                            <div class="col-6 col-md-1">
                                <label class="form-label">{{ __('app.admin.exams.filters.year') }}</label>
                                <select name="year" class="form-select">
                                    <option value="">{{ __('app.admin.exams.filters.all') }}</option>
                                    @foreach($years as $y)
                                        <option value="{{ $y }}" @selected(($filters['year'] ?? '')==$y)>{{ $y }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-6 col-md-2">
                                <label class="form-label">{{ __('app.admin.exams.filters.active') }}</label>
                                <select name="active" class="form-select">
                                    <option value="">{{ __('app.admin.exams.filters.all') }}</option>
                                    <option value="1" @selected(($filters['active'] ?? '')==='1')>{{ __('app.common.yes') }}</option>
                                    <option value="0" @selected(($filters['active'] ?? '')==='0')>{{ __('app.common.no') }}</option>
                                </select>
                            </div>
                            <div class="col-12 d-flex gap-2">
                                <button type="submit" class="btn btn-primary">{{ __('app.admin.exams.filters.filter') }}</button>
                                <a href="{{ route('admin.exams.index') }}" class="btn btn-outline-secondary">{{ __('app.admin.exams.filters.reset') }}</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table align-middle">
                            <thead>
                            <tr>
                                <th style="width:70px;">{{ __('app.admin.exams.table.id') }}</th>
                                <th>{{ __('app.admin.exams.table.title') }}</th>
                                <th style="width:160px;">{{ __('app.admin.exams.table.subject') }}</th>
                                <th style="width:180px;">{{ __('app.admin.exams.table.school') }}</th>
                                <th style="width:80px;">{{ __('app.admin.exams.table.grade') }}</th>
                                <th style="width:80px;">{{ __('app.admin.exams.table.lang') }}</th>
                                <th style="width:80px;">{{ __('app.admin.exams.table.year') }}</th>
                                <th style="width:120px;">{{ __('app.admin.exams.table.date') }}</th>
                                <th style="width:120px;">{{ __('app.admin.exams.table.type') }}</th>
                                <th style="width:70px;">#Q</th>
                                <th style="width:90px;">{{ __('app.admin.exams.table.active') }}</th>
                                <th style="width:110px;" class="text-end">{{ __('app.admin.exams.actions.actions') }}</th>
                            </tr>
                            </thead>
                            <tbody>
                            @forelse ($exams as $e)
                                <tr>
                                    <td>#{{ $e->id }}</td>
                                    <td>{{ $e->title }}</td>
                                    <td>{{ $e->subject?->name ?? '—' }}</td>
                                    <td>{{ $e->school?->name ?? '—' }}</td>
                                    <td>{{ $e->grade ?? '—' }}</td>
                                    <td>{{ strtoupper($e->question_language) }}</td>
                                    <td>{{ $e->year ?? '—' }}</td>
                                    <td>{{ $e->exam_date?->format('Y-m-d') ?? '—' }}</td>
                                    <td>{{ $e->type ?? '—' }}</td>
                                    <td>{{ $e->num_questions }}</td>
                                    <td>
                                        @if($e->is_active)
                                            <span class="badge text-bg-success">{{ __('app.common.yes') }}</span>
                                        @else
                                            <span class="badge text-bg-secondary">{{ __('app.common.no') }}</span>
                                        @endif
                                    </td>
                                    <td class="text-end">
                                        <button class="btn btn-sm btn-outline-primary p-1 js-edit me-1"
                                                data-id="{{ $e->id }}"
                                                data-bs-toggle="modal"
                                                data-bs-target="#modalEdit"
                                                data-bs-toggle1="tooltip" title="{{ __('app.admin.exams.actions.edit') }}"
                                                aria-label="{{ __('app.admin.exams.actions.edit') }}">
                                            <i class="bi bi-pencil-square"></i><span class="visually-hidden">{{ __('app.admin.exams.actions.edit') }}</span>
                                        </button>
                                        <form action="{{ route('admin.exams.destroy', $e->id) }}" method="POST" class="d-inline js-delete">
                                            @csrf @method('DELETE')
                                            <button type="submit" class="btn btn-sm btn-outline-danger p-1"
                                                    data-bs-toggle="tooltip" title="{{ __('app.admin.exams.actions.delete') }}"
                                                    aria-label="{{ __('app.admin.exams.actions.delete') }}">
                                                <i class="bi bi-trash"></i><span class="visually-hidden">{{ __('app.admin.exams.actions.delete') }}</span>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            @empty
                                <tr><td colspan="12" class="text-muted">{{ __('app.admin.exams.empty') }}</td></tr>
                            @endforelse
                            </tbody>
                        </table>
                    </div>

                    <div class="mt-3">
                        {{ $exams->onEachSide(1)->links() }}
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Create Modal --}}
    <div class="modal fade" id="modalCreate" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <form method="POST" action="{{ route('admin.exams.store') }}">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title">{{ __('app.admin.exams.actions.add_new') }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{{ __('app.admin.exams.actions.cancel') }}"></button>
                    </div>
                    <div class="modal-body">
                        @include('admin.exams.partials.form', ['mode' => 'create', 'subjects' => $subjects, 'schools' => $schools])
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{{ __('app.admin.exams.actions.cancel') }}</button>
                        <button type="submit" class="btn btn-primary">{{ __('app.admin.exams.actions.save') }}</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    {{-- Edit Modal --}}
    <div class="modal fade" id="modalEdit" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <form id="editForm" method="POST" action="#">
                    @csrf @method('PUT')
                    <div class="modal-header">
                        <h5 class="modal-title">{{ __('app.admin.exams.actions.edit') }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{{ __('app.admin.exams.actions.cancel') }}"></button>
                    </div>
                    <div class="modal-body">
                        <div id="editLoader" class="text-center my-5">
                            <div class="spinner-border" role="status"></div>
                            <div class="mt-2">{{ __('app.admin.exams.loader.loading') }}</div>
                        </div>
                        <div id="editFields" class="d-none">
                            @include('admin.exams.partials.form', ['mode' => 'edit', 'subjects' => $subjects, 'schools' => $schools])
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{{ __('app.admin.exams.actions.cancel') }}</button>
                        <button type="submit" class="btn btn-primary">{{ __('app.admin.exams.actions.save') }}</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // Tooltips
            const triggers = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"],[data-bs-toggle1="tooltip"]'));
            triggers.forEach(el => new bootstrap.Tooltip(el));

            // Delete confirm
            document.querySelectorAll('.js-delete').forEach(form => {
                form.addEventListener('submit', (e) => {
                    if (!confirm(@json(__('app.admin.exams.confirm_delete')))) e.preventDefault();
                });
            });

            // Edit loader + fetch
            const editForm   = document.getElementById('editForm');
            const editLoader = document.getElementById('editLoader');
            const editFields = document.getElementById('editFields');

            document.querySelectorAll('.js-edit').forEach(btn => {
                btn.addEventListener('click', async () => {
                    const id = btn.dataset.id;
                    editLoader.classList.remove('d-none');
                    editFields.classList.add('d-none');

                    editForm.action = @json(route('admin.exams.update', ':id')).replace(':id', id);

                    try {
                        const res = await fetch(@json(route('admin.exams.show', ':id')).replace(':id', id), { headers: { 'Accept':'application/json' }});
                        const data = await res.json();
                        fillExamForm(editFields, data);
                        editLoader.classList.add('d-none');
                        editFields.classList.remove('d-none');
                    } catch (e) {
                        alert(@json(__('app.admin.exams.loader.failed')));
                    }
                });
            });

            function fillExamForm(container, data) {
                container.querySelector('[name="title"]').value              = data.title ?? '';
                container.querySelector('[name="subject_id"]').value         = data.subject_id ?? '';
                container.querySelector('[name="question_language"]').value  = data.question_language ?? 'en';
                container.querySelector('[name="grade"]').value              = data.grade ?? '';
                container.querySelector('[name="year"]').value               = data.year ?? '';
                container.querySelector('[name="school_id"]').value          = data.school_id ?? '';
                container.querySelector('[name="exam_date"]').value          = data.exam_date ?? '';
                container.querySelector('[name="type"]').value               = data.type ?? '';
                container.querySelector('[name="num_questions"]').value      = data.num_questions ?? 15;
                container.querySelector('[name="is_active"]').checked        = !!data.is_active;
            }

            // Toggle filters label
            const filterToggleBtn = document.getElementById('filterToggleBtn');
            const filtersCollapse = document.getElementById('filtersCollapse');
            const LABEL_SHOW = @json(__('app.admin.exams.filters.show_filters'));
            const LABEL_HIDE = @json(__('app.admin.exams.filters.hide_filters'));
            filtersCollapse.addEventListener('shown.bs.collapse',  () => filterToggleBtn.textContent = LABEL_HIDE);
            filtersCollapse.addEventListener('hidden.bs.collapse', () => filterToggleBtn.textContent = LABEL_SHOW);
        });
    </script>
@endsection
