@extends('layouts.admin')

@section('content')
  @php
    $questionCount = $questionsmanagemnet->count();
    $chapterOptions = collect($mathchapters ?? []);
    $selectedChapter = (string) ($selectedChapter ?? '');
    $selectedChapterResolved = false;
    $activeFilters = collect([
      $selectedSubjectId > 0 ? 'Subject Filter On' : null,
      $selectedGroupId > 0 ? 'Class Filter On' : null,
      filled($selectedChapter) ? 'Chapter Filter On' : null,
    ])->filter()->values();
  @endphp

  <div class="card-header">
    <h4>Manage Questions</h4>
    <a class="btn btn-primary float-right" href="{{ route('admin.addquestions') }}">Add Questions</a>
  </div>

  <div class="card-body">
    @include('admin.partials.flash-messages')

    <div class="portal-page-shell">
      <div class="portal-hero-card">
        <div class="portal-hero-main">
          <div class="portal-hero-copy">
            <h5>Question Modules</h5>
            <p>Manage subject-wise and class-wise question blocks before using them inside competition question sets.</p>
            <div class="portal-chip-list">
              <span class="portal-chip">Objective Questions</span>
              <span class="portal-chip">10 Slots per Module</span>
              <span class="portal-chip">{{ $questionCount }} Records</span>
              @foreach($activeFilters as $filterLabel)
                <span class="portal-chip">{{ $filterLabel }}</span>
              @endforeach
            </div>
          </div>
        </div>
      </div>

      <div class="portal-form-shell">
        <form action="{{ route('admin.managequestions') }}" method="get">
          <div class="portal-form-grid portal-form-grid-3">
            <div class="form-group portal-form-group">
              <label for="subject">Question Subject</label>
              <select name="subject" id="subject" class="form-control">
                <option value="">Select Subject</option>
                @foreach($sudentsubject as $subject)
                  <option value="{{ $subject->id }}" @selected($selectedSubjectId === (int) $subject->id)>{{ $subject->subjectname }}</option>
                @endforeach
              </select>
            </div>

            <div class="form-group portal-form-group">
              <label for="questiongoupsclass">Question Class Group</label>
              <select name="goupsclass" id="questiongoupsclass" class="form-control">
                <option value="">Select Class Group</option>
                @foreach($studentsgroup as $group)
                  <option value="{{ $group->id }}" @selected($selectedGroupId === (int) $group->id)>{{ $group->studentsgroupname }}</option>
                @endforeach
              </select>
            </div>

            <div class="form-group portal-form-group">
              <label for="chapter">Chapter</label>
              <select name="chapter" id="chapter" class="form-control">
                <option value="">All Chapters</option>
                @foreach($chapterOptions as $chapter)
                  @php
                    $chapterMatchesFilters = ($selectedSubjectId === 0 || $selectedSubjectId === (int) $chapter->subjectid)
                      && ($selectedGroupId === 0 || $selectedGroupId === (int) $chapter->classgroupid);
                    $isSelectedChapterOption = ! $selectedChapterResolved
                      && $selectedChapter === $chapter->chaptername
                      && $chapterMatchesFilters;
                    $selectedChapterResolved = $selectedChapterResolved || $isSelectedChapterOption;
                  @endphp
                  <option
                    value="{{ $chapter->chaptername }}"
                    data-group-id="{{ $chapter->classgroupid }}"
                    data-subject-id="{{ $chapter->subjectid }}"
                    @selected($isSelectedChapterOption)
                  >
                    {{ $chapter->chaptername }} ({{ $chapter->subjectname ?: 'No Subject' }} | {{ $chapter->classgroupname ?: 'No Class' }})
                  </option>
                @endforeach
                @if(filled($selectedChapter) && ! $selectedChapterResolved)
                  <option value="{{ $selectedChapter }}" selected data-legacy="true">Legacy: {{ $selectedChapter }}</option>
                @endif
              </select>
              <small class="portal-form-hint">Chapter master se direct filter choose kijiye. Subject ya class select karne par list auto short ho jayegi.</small>
            </div>

            <div class="form-group portal-form-group">
              <label>&nbsp;</label>
              <div class="portal-link-row">
                <button type="submit" class="btn btn-primary">Search</button>
                <a class="btn btn-outline-danger" href="{{ route('admin.managequestions') }}">Clear All</a>
              </div>
            </div>
          </div>
        </form>
      </div>

      <div class="portal-form-shell">
        <div class="table-responsive">
          <table class="table table-striped table-hover" id="tableExport" style="width:100%;">
            <thead>
              <tr>
                <th>#</th>
                <th>Question Details</th>
                <th>Question Subject</th>
                <th>Chapter</th>
                <th>Question Class Group</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              @forelse($questionsmanagemnet as $question)
                <tr>
                  <td>{{ $loop->iteration }}</td>
                  <td>{{ $question->questionstitle }}</td>
                  <td>{{ $question->questionsubjectname }}</td>
                  <td>{{ $question->questionchaptername ?: '-' }}</td>
                  <td>{{ $question->questiongroupname }}</td>
                  <td>
                    <a class="btn btn-success btn-sm" data-toggle="tooltip" data-placement="top" title="Edit Question" href="{{ route('admin.editquestions', ['id' => $question->id]) }}">
                      <i class="fas fa-pencil-alt"></i>
                    </a>
                    <form action="{{ route('admin.deletequestions', ['id' => $question->id]) }}" method="post" class="d-inline-block">
                      @csrf
                      <button type="submit" class="btn btn-danger deletedata" data-toggle="tooltip" data-placement="top" title="Delete Question" data-confirm-message="Are you sure you want to delete this question?">
                        <i class="fas fa-trash"></i>
                      </button>
                    </form>
                  </td>
                </tr>
              @empty
                <tr>
                  <td colspan="6" class="text-center text-muted">No question modules found for the selected filters.</td>
                </tr>
              @endforelse
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
@endsection

@push('scripts')
  <script>
    (function () {
      var subjectSelect = document.getElementById('subject');
      var groupSelect = document.getElementById('questiongoupsclass');
      var chapterSelect = document.getElementById('chapter');

      if (!subjectSelect || !groupSelect || !chapterSelect) {
        return;
      }

      var syncChapterOptions = function () {
        var selectedSubjectId = subjectSelect.value || '';
        var selectedGroupId = groupSelect.value || '';

        Array.prototype.forEach.call(chapterSelect.options, function (option, index) {
          if (index === 0 || option.getAttribute('data-legacy') === 'true') {
            option.hidden = false;
            option.disabled = false;
            return;
          }

          var optionSubjectId = option.getAttribute('data-subject-id') || '';
          var optionGroupId = option.getAttribute('data-group-id') || '';
          var subjectMatches = selectedSubjectId === '' || optionSubjectId === selectedSubjectId;
          var groupMatches = selectedGroupId === '' || optionGroupId === selectedGroupId;
          var isVisible = subjectMatches && groupMatches;

          option.hidden = !isVisible;
          option.disabled = !isVisible;
        });

        var selectedOption = chapterSelect.options[chapterSelect.selectedIndex];
        if (selectedOption && selectedOption.value && (selectedOption.hidden || selectedOption.disabled)) {
          chapterSelect.value = '';
        }
      };

      subjectSelect.addEventListener('change', syncChapterOptions);
      groupSelect.addEventListener('change', syncChapterOptions);
      syncChapterOptions();
    })();
  </script>
@endpush
