<?php
  $questionRecord = $questionRecord ?? null;
  $formAction = $formAction ?? '#';
  $submitLabel = $submitLabel ?? 'Save';
  $heroTitle = $heroTitle ?? 'Question Builder';
  $heroDescription = $heroDescription ?? 'Create or update objective questions with bilingual content and answer options.';
  $mathSubjectId = (int) ($mathSubjectId ?? 5);
  $mathChapterOptions = collect($mathchapters ?? []);

  $readQuestionArray = function (string $field, ?array $fallback = null) {
      $oldValue = old($field);
      if (is_array($oldValue)) {
          return array_pad($oldValue, 10, '');
      }

      return array_pad($fallback ?? [], 10, '');
  };

  $extractSelectedId = function (string $fieldName, $storedId): int {
      $oldValue = old($fieldName);

      if (is_string($oldValue) && str_contains($oldValue, '<=>')) {
          [$id] = explode('<=>', $oldValue, 2);
          return is_numeric($id) ? (int) $id : 0;
      }

      if (is_numeric($oldValue)) {
          return (int) $oldValue;
      }

      return is_numeric($storedId) ? (int) $storedId : 0;
  };

  $selectedSubjectId = $extractSelectedId('questionsubject', $questionRecord?->questionsubjectid);
  $selectedGroupId = $extractSelectedId('questiongoupsclass', $questionRecord?->questiongroupid);
  $selectedChapterName = old('questionchapter', $questionRecord?->questionchaptername ?? '');
  $hasSubjectSelected = $selectedSubjectId > 0;

  $questionList = $readQuestionArray('questionsection', $questionRecord?->questionlist);
  $questionHindiList = $readQuestionArray('questionsectionhndi', $questionRecord?->questionhindi);
  $optionAList = $readQuestionArray('questionsectionobjectfirst', $questionRecord?->questionobjectfirst);
  $optionAHindiList = $readQuestionArray('questionsectionobjectfirsthindi', $questionRecord?->questionobjectfirsthindi);
  $optionBList = $readQuestionArray('questionsectionseond', $questionRecord?->questionobjectsecond);
  $optionBHindiList = $readQuestionArray('questionsectionseondhindi', $questionRecord?->questionobjectsecondhindi);
  $optionCList = $readQuestionArray('questionsectionthird', $questionRecord?->questionobjectthird);
  $optionCHindiList = $readQuestionArray('questionsectionthirdhindi', $questionRecord?->questionobjectthirdhindi);
  $optionDList = $readQuestionArray('questionsectionfouth', $questionRecord?->questionobjectfourth);
  $optionDHindiList = $readQuestionArray('questionsectionfouthhindi', $questionRecord?->questionobjectfourthhindi);
  $answerList = $readQuestionArray('questionobjectanswer', $questionRecord?->questionobjectanswer);

  $filledSlots = collect($questionList)->filter(fn ($value) => filled($value))->count();
  $summaryCards = $questionRecord
      ? [
          'Question ID' => '#'.$questionRecord->id,
          'Filled Slots' => number_format($filledSlots),
          'Subject' => old('questionsubject', $questionRecord->questionsubjectname ?? '-'),
          'Class Group' => old('questiongoupsclass', $questionRecord->questiongroupname ?? '-'),
      ]
      : [
          'Question Slots' => '10',
          'Minimum Required' => '1 Question',
          'Answer Options' => 'A to D',
          'Format' => 'English + Hindi',
      ];

  if (filled($selectedChapterName)) {
      $summaryCards['Chapter'] = $selectedChapterName;
  }
?>

<div class="portal-page-shell">
  <div class="portal-hero-card">
    <div class="portal-hero-main">
      <div class="portal-hero-copy">
        <h5><?php echo e($heroTitle); ?></h5>
        <p><?php echo e($heroDescription); ?></p>
        <div class="portal-chip-list">
          <span class="portal-chip">Objective Pattern</span>
          <span class="portal-chip">Bilingual Ready</span>
          <span class="portal-chip">10 Slots per Record</span>
        </div>
        <div class="portal-hero-actions">
          <a href="<?php echo e(route('admin.managequestions')); ?>" class="btn btn-outline-primary btn-sm">Back to Questions</a>
        </div>
      </div>
    </div>
  </div>

  <div class="portal-summary-grid">
    <?php $__currentLoopData = $summaryCards; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $label => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
      <div class="portal-summary-card">
        <span><?php echo e($label); ?></span>
        <strong><?php echo e($value); ?></strong>
      </div>
    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
  </div>

  <form action="<?php echo e($formAction); ?>" method="post" class="portal-form-shell">
    <?php echo csrf_field(); ?>
    <?php if($questionRecord): ?>
      <input type="hidden" name="editid" value="<?php echo e($questionRecord->id); ?>">
    <?php endif; ?>

    <div class="portal-form-section">
      <h6>Question Details</h6>
      <p>Choose the subject and class group, then fill the question slots below.</p>
      <div class="portal-form-grid">
        <div class="form-group portal-form-group portal-form-group-full">
          <label for="questiontitle">Question Title</label>
          <input type="text" class="form-control" id="questiontitle" name="questiontitle" value="<?php echo e(old('questiontitle', $questionRecord->questionstitle ?? '')); ?>" maxlength="2000" placeholder="Question title" required>
        </div>
        <div class="form-group portal-form-group">
          <label for="questionsubject">Question Subject</label>
          <select name="questionsubject" id="questionsubject" class="form-control" data-math-subject-id="<?php echo e($mathSubjectId); ?>" required>
            <option value="">Select Subject</option>
            <?php $__currentLoopData = $sudentsubject; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $subject): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
              <?php ($subjectValue = $subject->id.'<=>'.$subject->subjectname); ?>
              <option value="<?php echo e($subjectValue); ?>" <?php if($selectedSubjectId === (int) $subject->id): echo 'selected'; endif; ?>>
                <?php echo e($subject->subjectname); ?>

              </option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
          </select>
        </div>
        <div class="form-group portal-form-group" id="questionchapterField" <?php if(! $hasSubjectSelected): ?> style="display: none;" <?php endif; ?>>
          <label for="questionchapter">Chapter</label>
          <select class="form-control" id="questionchapter" name="questionchapter">
            <option value="">Select Chapter</option>
            <?php $__currentLoopData = $mathChapterOptions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $chapter): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
              <option
                value="<?php echo e($chapter->chaptername); ?>"
                data-group-id="<?php echo e($chapter->classgroupid); ?>"
                data-subject-id="<?php echo e($chapter->subjectid); ?>"
                <?php if($selectedChapterName === $chapter->chaptername && $selectedGroupId === (int) $chapter->classgroupid && $selectedSubjectId === (int) $chapter->subjectid): echo 'selected'; endif; ?>
              >
                <?php echo e($chapter->chaptername); ?> (<?php echo e($chapter->subjectname); ?> | <?php echo e($chapter->classgroupname); ?>)
              </option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            <?php if(filled($selectedChapterName) && ! $mathChapterOptions->contains(fn ($chapter) => $chapter->chaptername === $selectedChapterName && $selectedGroupId === (int) $chapter->classgroupid && $selectedSubjectId === (int) $chapter->subjectid)): ?>
              <option value="<?php echo e($selectedChapterName); ?>" data-group-id="<?php echo e($selectedGroupId); ?>" data-subject-id="<?php echo e($selectedSubjectId); ?>" data-legacy="true" selected>
                Legacy: <?php echo e($selectedChapterName); ?>

              </option>
            <?php endif; ?>
          </select>
          <small class="portal-form-hint">Selected subject ke liye chapter master se chapter choose kijiye.</small>
          <div class="portal-loading-note" id="questionchapterEmptyNote" style="display: none;">No chapter found for the selected subject and class group. Please create chapter first.</div>
        </div>
        <div class="form-group portal-form-group">
          <label for="questiongoupsclass">Question Class Group</label>
          <select name="questiongoupsclass" id="questiongoupsclass" class="form-control" required>
            <option value="">Select Class Group</option>
            <?php $__currentLoopData = $studentsgroup; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $group): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
              <?php ($groupValue = $group->id.'<=>'.$group->studentsgroupname); ?>
              <option value="<?php echo e($groupValue); ?>" <?php if($selectedGroupId === (int) $group->id): echo 'selected'; endif; ?>>
                <?php echo e($group->studentsgroupname); ?>

              </option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
          </select>
        </div>
      </div>
    </div>

    <div class="portal-form-section">
      <h6>Question Slots</h6>
      <p>The first slot should always be filled. Remaining slots can be used as needed in the same record.</p>
      <div class="portal-question-stack">
        <?php for($questionIndex = 0; $questionIndex < 10; $questionIndex++): ?>
          <div class="portal-question-card">
            <div class="portal-question-head">
              <h6>Question <?php echo e($questionIndex + 1); ?></h6>
              <span class="portal-question-index">Slot <?php echo e($questionIndex + 1); ?></span>
            </div>

            <div class="portal-question-grid">
              <div class="form-group portal-form-group portal-form-group-full">
                <label for="questionsection<?php echo e($questionIndex); ?>">Question (English)</label>
                <textarea class="form-control" id="questionsection<?php echo e($questionIndex); ?>" name="questionsection[<?php echo e($questionIndex); ?>]" maxlength="3000" placeholder="Question English"><?php echo e($questionList[$questionIndex] ?? ''); ?></textarea>
              </div>
              <div class="form-group portal-form-group portal-form-group-full">
                <label for="questionsectionhndi<?php echo e($questionIndex); ?>">Question (Hindi)</label>
                <textarea class="form-control" id="questionsectionhndi<?php echo e($questionIndex); ?>" name="questionsectionhndi[<?php echo e($questionIndex); ?>]" maxlength="3000" placeholder="Question Hindi"><?php echo e($questionHindiList[$questionIndex] ?? ''); ?></textarea>
              </div>

              <div class="form-group portal-form-group">
                <label for="questionsectionobjectfirst<?php echo e($questionIndex); ?>">Option A</label>
                <input type="text" class="form-control" id="questionsectionobjectfirst<?php echo e($questionIndex); ?>" name="questionsectionobjectfirst[<?php echo e($questionIndex); ?>]" value="<?php echo e($optionAList[$questionIndex] ?? ''); ?>" maxlength="1000" placeholder="Option A">
              </div>
              <div class="form-group portal-form-group">
                <label for="questionsectionobjectfirsthindi<?php echo e($questionIndex); ?>">Option A (Hindi)</label>
                <input type="text" class="form-control" id="questionsectionobjectfirsthindi<?php echo e($questionIndex); ?>" name="questionsectionobjectfirsthindi[<?php echo e($questionIndex); ?>]" value="<?php echo e($optionAHindiList[$questionIndex] ?? ''); ?>" maxlength="1000" placeholder="Option A Hindi">
              </div>

              <div class="form-group portal-form-group">
                <label for="questionsectionseond<?php echo e($questionIndex); ?>">Option B</label>
                <input type="text" class="form-control" id="questionsectionseond<?php echo e($questionIndex); ?>" name="questionsectionseond[<?php echo e($questionIndex); ?>]" value="<?php echo e($optionBList[$questionIndex] ?? ''); ?>" maxlength="1000" placeholder="Option B">
              </div>
              <div class="form-group portal-form-group">
                <label for="questionsectionseondhindi<?php echo e($questionIndex); ?>">Option B (Hindi)</label>
                <input type="text" class="form-control" id="questionsectionseondhindi<?php echo e($questionIndex); ?>" name="questionsectionseondhindi[<?php echo e($questionIndex); ?>]" value="<?php echo e($optionBHindiList[$questionIndex] ?? ''); ?>" maxlength="1000" placeholder="Option B Hindi">
              </div>

              <div class="form-group portal-form-group">
                <label for="questionsectionthird<?php echo e($questionIndex); ?>">Option C</label>
                <input type="text" class="form-control" id="questionsectionthird<?php echo e($questionIndex); ?>" name="questionsectionthird[<?php echo e($questionIndex); ?>]" value="<?php echo e($optionCList[$questionIndex] ?? ''); ?>" maxlength="1000" placeholder="Option C">
              </div>
              <div class="form-group portal-form-group">
                <label for="questionsectionthirdhindi<?php echo e($questionIndex); ?>">Option C (Hindi)</label>
                <input type="text" class="form-control" id="questionsectionthirdhindi<?php echo e($questionIndex); ?>" name="questionsectionthirdhindi[<?php echo e($questionIndex); ?>]" value="<?php echo e($optionCHindiList[$questionIndex] ?? ''); ?>" maxlength="1000" placeholder="Option C Hindi">
              </div>

              <div class="form-group portal-form-group">
                <label for="questionsectionfouth<?php echo e($questionIndex); ?>">Option D</label>
                <input type="text" class="form-control" id="questionsectionfouth<?php echo e($questionIndex); ?>" name="questionsectionfouth[<?php echo e($questionIndex); ?>]" value="<?php echo e($optionDList[$questionIndex] ?? ''); ?>" maxlength="1000" placeholder="Option D">
              </div>
              <div class="form-group portal-form-group">
                <label for="questionsectionfouthhindi<?php echo e($questionIndex); ?>">Option D (Hindi)</label>
                <input type="text" class="form-control" id="questionsectionfouthhindi<?php echo e($questionIndex); ?>" name="questionsectionfouthhindi[<?php echo e($questionIndex); ?>]" value="<?php echo e($optionDHindiList[$questionIndex] ?? ''); ?>" maxlength="1000" placeholder="Option D Hindi">
              </div>

              <div class="form-group portal-form-group portal-form-group-full">
                <label for="questionobjectanswer<?php echo e($questionIndex); ?>">Correct Answer</label>
                <select name="questionobjectanswer[<?php echo e($questionIndex); ?>]" id="questionobjectanswer<?php echo e($questionIndex); ?>" class="form-control">
                  <?php $__currentLoopData = ['A', 'B', 'C', 'D']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $optionKey): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option value="<?php echo e($optionKey); ?>" <?php if(($answerList[$questionIndex] ?? 'A') === $optionKey): echo 'selected'; endif; ?>>Option <?php echo e($optionKey); ?></option>
                  <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
              </div>
            </div>
          </div>
        <?php endfor; ?>
      </div>
    </div>

    <div class="portal-form-actions">
      <p class="portal-security-note">Questions are stored in fixed 10-slot groups, so keep each slot aligned with its correct answer.</p>
      <button type="submit" class="btn btn-primary"><?php echo e($submitLabel); ?></button>
    </div>
  </form>
</div>

<?php $__env->startPush('scripts'); ?>
  <script>
    (function () {
      var subjectSelect = document.getElementById('questionsubject');
      var groupSelect = document.getElementById('questiongoupsclass');
      var chapterField = document.getElementById('questionchapterField');
      var chapterInput = document.getElementById('questionchapter');
      var chapterEmptyNote = document.getElementById('questionchapterEmptyNote');

      if (!subjectSelect || !groupSelect || !chapterField || !chapterInput || !chapterEmptyNote) {
        return;
      }

      var mathSubjectId = subjectSelect.getAttribute('data-math-subject-id') || '';
      var parseCompoundId = function (value) {
        return value && value.indexOf('<=>') > -1 ? value.split('<=>')[0] : '';
      };

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

        Array.prototype.forEach.call(chapterInput.options, function (option, index) {
          if (index === 0) {
            option.hidden = false;
            option.disabled = false;
            return;
          }

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

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

          if (isVisible) {
            hasVisibleChapter = true;
          }
        });

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

        chapterEmptyNote.textContent = selectedSubjectId === ''
          ? 'Select subject first to load chapters.'
          : selectedGroupId === ''
            ? 'Select class group first to load chapters.'
            : 'No chapter found for the selected subject and class group. Please create chapter first.';
        chapterEmptyNote.style.display = selectedSubjectId !== '' && selectedGroupId !== '' && !hasVisibleChapter ? '' : 'none';
      };

      var toggleChapterField = function () {
        var selectedValue = subjectSelect.value || '';
        var selectedSubjectId = selectedValue.indexOf('<=>') > -1 ? selectedValue.split('<=>')[0] : '';
        var hasSubjectSelected = selectedSubjectId !== '';

        chapterField.style.display = hasSubjectSelected ? '' : 'none';
        chapterInput.required = hasSubjectSelected;
        syncChapterOptions();
        chapterEmptyNote.style.display = hasSubjectSelected ? chapterEmptyNote.style.display : 'none';

        if (!hasSubjectSelected) {
          chapterInput.value = '';
        }
      };

      subjectSelect.addEventListener('change', toggleChapterField);
      groupSelect.addEventListener('change', toggleChapterField);
      toggleChapterField();
    })();
  </script>
<?php $__env->stopPush(); ?>
<?php /**PATH C:\xampp\htdocs\examproject\examproject_new\resources\views/admin/questions/partials/question-form.blade.php ENDPATH**/ ?>