@extends('layouts.app')

@section('title', __('stage_academy.courses.items.questions.title'))

@push('styles')
<link href="{{ asset('css/stage-academy.css') }}" rel="stylesheet">
@endpush

@section('content')
@php
    $courseName = app()->getLocale() === 'ar' ? $course->name_ar : $course->name_en;
    $oldQuestion = [
        'id' => old('id'),
        'question_ar' => old('question_ar'),
        'question_en' => old('question_en'),
        'points' => old('points'),
        'options' => old('options'),
    ];
@endphp

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="h4 fw-bold text-dark mb-0">{{ __('stage_academy.courses.items.questions.title') }}</h2>
            <div class="text-muted small mt-1">{{ $courseName }}</div>
        </div>
        <div class="d-flex align-items-center gap-2 flex-shrink-0">
            <button type="button" class="btn btn-primary bg-gradient border-0" onclick="openAddQuestionModal()">
                <i class="bi bi-plus-lg"></i>
                {{ __('stage_academy.courses.items.questions.add_button') }}
            </button>
            <a href="{{ route('stage-academy.courses.items') }}" class="btn btn-outline-secondary">
                <i class="bi {{ app()->getLocale() == 'ar' ? 'bi-arrow-right' : 'bi-arrow-left' }}"></i> {{ __('common.back') }}
            </a>
        </div>
    </div>

    @if($errors->any())
        <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0" role="alert">
            <ul class="mb-0 ps-3">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    @endif

    <div class="sa-smart-list">
        @forelse($questions as $question)
            @php
                $localizedQuestion = app()->getLocale() === 'ar' ? $question->question_ar : $question->question_en;
                $optionsCount = $question->options->count();
                $correctCount = $question->options->where('is_correct', true)->count();
                $optionsPayload = $question->options->map(function ($opt) {
                    return [
                        'option_ar' => $opt->option_ar,
                        'option_en' => $opt->option_en,
                        'is_correct' => (bool) $opt->is_correct,
                    ];
                })->values();
            @endphp

            <div class="sa-smart-row">
                <div class="d-flex align-items-start gap-3 flex-grow-1">
                    <div class="sa-thumb">
                        <i class="bi bi-patch-question text-primary"></i>
                    </div>

                    <div class="flex-grow-1">
                        <div class="d-flex justify-content-between align-items-start gap-2 flex-wrap">
                            <div class="fw-bold text-dark">{{ $localizedQuestion }}</div>
                            <div class="d-flex align-items-center gap-2 flex-wrap">
                                <span class="badge text-bg-light">{{ __('stage_academy.courses.items.questions.list.points') }}: {{ (int) $question->points }}</span>
                                <span class="badge text-bg-light">{{ __('stage_academy.courses.items.questions.list.options_count') }}: {{ $optionsCount }}</span>
                                <span class="badge text-bg-light">{{ __('stage_academy.courses.items.questions.list.correct_count') }}: {{ $correctCount }}</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="d-flex align-items-center gap-2 flex-shrink-0">
                    <button
                        type="button"
                        class="btn btn-light btn-sm sa-action-btn text-primary"
                        data-id="{{ $question->id }}"
                        data-question-ar="{{ $question->question_ar }}"
                        data-question-en="{{ $question->question_en }}"
                        data-points="{{ (int) $question->points }}"
                        data-options='@json($optionsPayload)'
                        onclick="openEditQuestionModal(this)"
                        title="{{ __('common.edit') }}"
                    >
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button
                        type="button"
                        class="btn btn-light btn-sm sa-action-btn text-danger"
                        data-question-id="{{ $question->id }}"
                        onclick="openDeleteModal(this)"
                        title="{{ __('common.delete') }}"
                    >
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        @empty
            <div class="text-center py-5 text-muted">
                <i class="bi bi-inbox fs-1 d-block mb-3 opacity-50"></i>
                <p class="mb-0">{{ __('stage_academy.courses.items.questions.empty') }}</p>
            </div>
        @endforelse
    </div>
</div>

<div
    id="courseQuestionsConfig"
    data-course-id="{{ $course->id }}"
    data-store-route="{{ route('stage-academy.courses.items.questions.store', $course->id) }}"
    data-update-route-template="{{ route('stage-academy.courses.items.questions.update', [$course->id, 0]) }}"
    data-destroy-route-template="{{ route('stage-academy.courses.items.questions.destroy', [$course->id, 0]) }}"
    data-add-title="{{ __('stage_academy.courses.items.questions.add_button') }}"
    data-edit-title="{{ __('common.edit') }}"
    data-correct-required="{{ __('stage_academy.courses.items.questions.validation.correct_required') }}"
    data-options-required="{{ __('stage_academy.courses.items.questions.validation.options_required') }}"
    data-has-errors="{{ $errors->any() ? '1' : '0' }}"
    data-old='@json($oldQuestion)'
></div>

<div class="modal fade" id="questionModal" tabindex="-1" aria-labelledby="questionModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content">
            <form id="questionForm" method="POST">
                @csrf
                <input type="hidden" name="_method" id="questionMethodField" value="POST">
                <input type="hidden" name="id" id="questionId" value="{{ old('id') }}">

                <div class="modal-header">
                    <h5 class="modal-title" id="questionModalLabel">{{ __('stage_academy.courses.items.questions.add_button') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-12 col-md-6">
                            <label for="question_ar" class="form-label">{{ __('stage_academy.courses.items.questions.form.question_ar') }}</label>
                            <textarea class="form-control" id="question_ar" name="question_ar" required rows="3">{{ old('question_ar') }}</textarea>
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="question_en" class="form-label">{{ __('stage_academy.courses.items.questions.form.question_en') }}</label>
                            <textarea class="form-control" id="question_en" name="question_en" required rows="3">{{ old('question_en') }}</textarea>
                        </div>
                        <div class="col-12 col-md-4">
                            <label for="points" class="form-label">{{ __('stage_academy.courses.items.questions.form.points') }}</label>
                            <input type="number" class="form-control" id="points" name="points" required min="0" step="1" value="{{ old('points', 0) }}">
                        </div>
                    </div>

                    <div class="mt-4">
                        <div class="d-flex justify-content-between align-items-center gap-2 flex-wrap">
                            <div class="fw-semibold text-dark">{{ __('stage_academy.courses.items.questions.form.correct_answers') }}</div>
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="addOptionRow()">
                                <i class="bi bi-plus-lg"></i>
                                {{ __('stage_academy.courses.items.questions.form.add_option') }}
                            </button>
                        </div>

                        <div id="optionsWrap" class="mt-3 d-grid gap-2"></div>
                        <div id="optionsError" class="invalid-feedback d-block d-none"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">{{ __('common.cancel') }}</button>
                    <button type="submit" class="btn btn-primary bg-gradient border-0">{{ __('common.save') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form id="deleteForm" method="POST">
                @csrf
                @method('DELETE')

                <div class="modal-header border-bottom-0 pb-0">
                    <h5 class="modal-title text-danger" id="deleteModalLabel">{{ __('common.confirm_delete_title') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body py-4">
                    <p class="mb-0 fs-5 text-center">{{ __('common.confirm_delete_message') }}</p>
                </div>
                <div class="modal-footer border-top-0 pt-0 justify-content-center">
                    <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal">{{ __('common.cancel') }}</button>
                    <button type="submit" class="btn btn-danger px-4">{{ __('common.confirm_delete_action') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    const config = document.getElementById('courseQuestionsConfig');
    const storeRoute = config.dataset.storeRoute;
    const updateRouteTemplate = config.dataset.updateRouteTemplate;
    const destroyRouteTemplate = config.dataset.destroyRouteTemplate;
    const addTitle = config.dataset.addTitle;
    const editTitle = config.dataset.editTitle;
    const correctRequiredMessage = config.dataset.correctRequired;
    const optionsRequiredMessage = config.dataset.optionsRequired;

    let optionIndex = 0;

    function setOptionsError(message) {
        const el = document.getElementById('optionsError');
        if (!message) {
            el.classList.add('d-none');
            el.textContent = '';
            return;
        }
        el.classList.remove('d-none');
        el.textContent = message;
    }

    function addOptionRow(data = {}) {
        const wrap = document.getElementById('optionsWrap');
        const index = optionIndex++;

        const row = document.createElement('div');
        row.className = 'border rounded-3 p-3 sa-option-row';
        row.dataset.index = index;

        row.innerHTML = `
            <div class="row g-3 align-items-start">
                <div class="col-12 col-md-5">
                    <label class="form-label">{{ __('stage_academy.courses.items.questions.form.option_ar') }}</label>
                    <input type="text" class="form-control" name="options[${index}][option_ar]" required>
                </div>
                <div class="col-12 col-md-5">
                    <label class="form-label">{{ __('stage_academy.courses.items.questions.form.option_en') }}</label>
                    <input type="text" class="form-control" name="options[${index}][option_en]" required>
                </div>
                <div class="col-12 col-md-2 d-flex flex-column gap-2">
                    <div class="form-check mt-4">
                        <input class="form-check-input" type="checkbox" value="1" name="options[${index}][is_correct]">
                        <label class="form-check-label">{{ __('stage_academy.courses.items.questions.form.correct') }}</label>
                    </div>
                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeOptionRow(this)">
                        <i class="bi bi-x-lg"></i>
                    </button>
                </div>
            </div>
        `;

        wrap.appendChild(row);

        row.querySelector(`input[name="options[${index}][option_ar]"]`).value = data.option_ar ?? '';
        row.querySelector(`input[name="options[${index}][option_en]"]`).value = data.option_en ?? '';
        row.querySelector(`input[name="options[${index}][is_correct]"]`).checked = !!data.is_correct;

        setOptionsError('');
    }

    function removeOptionRow(button) {
        const row = button.closest('[data-index]');
        if (row) {
            row.remove();
        }
    }

    function openAddQuestionModal(clear = true) {
        const form = document.getElementById('questionForm');
        form.action = storeRoute;
        document.getElementById('questionMethodField').value = "POST";
        document.getElementById('questionModalLabel').innerText = addTitle;

        if (clear) {
            document.getElementById('questionId').value = "";
            document.getElementById('question_ar').value = "";
            document.getElementById('question_en').value = "";
            document.getElementById('points').value = "0";
            document.getElementById('optionsWrap').innerHTML = "";
            optionIndex = 0;
            addOptionRow();
        }

        setOptionsError('');

        const modal = new bootstrap.Modal(document.getElementById('questionModal'));
        modal.show();
    }

    function openEditQuestionModal(button) {
        const id = button.dataset.id;
        const form = document.getElementById('questionForm');
        form.action = updateRouteTemplate.replace('/0', '/' + id);

        document.getElementById('questionMethodField').value = "PUT";
        document.getElementById('questionId').value = id;
        document.getElementById('questionModalLabel').innerText = editTitle;

        document.getElementById('question_ar').value = button.dataset.questionAr ?? "";
        document.getElementById('question_en').value = button.dataset.questionEn ?? "";
        document.getElementById('points').value = button.dataset.points ?? "0";

        const wrap = document.getElementById('optionsWrap');
        wrap.innerHTML = "";
        optionIndex = 0;

        let options = [];
        try {
            options = JSON.parse(button.dataset.options || '[]');
        } catch (e) {
            options = [];
        }

        if (!options.length) {
            addOptionRow();
        } else {
            options.forEach((opt) => addOptionRow(opt));
        }

        setOptionsError('');

        const modal = new bootstrap.Modal(document.getElementById('questionModal'));
        modal.show();
    }

    function openDeleteModal(button) {
        const id = button.dataset.questionId;
        const form = document.getElementById('deleteForm');
        form.action = destroyRouteTemplate.replace('/0', '/' + id);

        const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
        modal.show();
    }

    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('questionForm').addEventListener('submit', function (event) {
            const rows = document.querySelectorAll('#optionsWrap [data-index]');
            if (!rows.length) {
                setOptionsError(optionsRequiredMessage);
                event.preventDefault();
                return;
            }

            let hasCorrect = false;
            rows.forEach((row) => {
                const checkbox = row.querySelector('input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    hasCorrect = true;
                }
            });

            if (!hasCorrect) {
                setOptionsError(correctRequiredMessage);
                event.preventDefault();
            }
        });

        const hasErrors = config.dataset.hasErrors === '1';
        if (hasErrors) {
            const oldData = JSON.parse(config.dataset.old || '{}');
            const isEdit = !!oldData.id;
            openAddQuestionModal(false);

            if (isEdit) {
                document.getElementById('questionMethodField').value = "PUT";
                document.getElementById('questionId').value = oldData.id;
                document.getElementById('questionModalLabel').innerText = editTitle;
                document.getElementById('questionForm').action = updateRouteTemplate.replace('/0', '/' + oldData.id);
            }

            document.getElementById('question_ar').value = oldData.question_ar ?? "";
            document.getElementById('question_en').value = oldData.question_en ?? "";
            document.getElementById('points').value = oldData.points ?? "0";

            const wrap = document.getElementById('optionsWrap');
            wrap.innerHTML = "";
            optionIndex = 0;

            if (Array.isArray(oldData.options) && oldData.options.length) {
                oldData.options.forEach((opt) => addOptionRow({
                    option_ar: opt.option_ar,
                    option_en: opt.option_en,
                    is_correct: !!opt.is_correct,
                }));
            } else {
                addOptionRow();
            }
        }
    });
</script>
@endsection
