@extends('admin.layouts.master')

@section('page-title')
    إدارة الأسئلة - {{ $section->title }}
@stop

@section('content')
    <div class="main-content app-content">
        <div class="container-fluid">

            <!-- Page Header -->
            <div class="d-md-flex d-block align-items-center justify-content-between my-4 page-header-breadcrumb">
                <div class="my-auto">
                    <h5 class="page-title fs-21 mb-1">إدارة أسئلة القسم: {{ $section->title }}</h5>
                    <nav>
                        <ol class="breadcrumb mb-0">
                            <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}">لوحة التحكم</a></li>
                            <li class="breadcrumb-item"><a href="{{ route('courses.index') }}">الكورسات</a></li>
                            <li class="breadcrumb-item"><a href="{{ route('courses.show', $section->course_id) }}">{{ $section->course->title }}</a></li>
                            <li class="breadcrumb-item active">إدارة الأسئلة</li>
                        </ol>
                    </nav>
                </div>
                <div class="d-flex my-xl-auto right-content">
                    <button type="button" class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#importQuestionModal">
                        <i class="fas fa-file-import me-2"></i>استيراد من بنك الأسئلة
                    </button>
                    <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#createQuestionModal">
                        <i class="fas fa-plus me-2"></i>إنشاء سؤال جديد
                    </button>
                </div>
            </div>

            <!-- Alerts -->
            @include('admin.components.alerts')

            <!-- Current Questions -->
            <div class="row">
                <div class="col-xl-12">
                    <div class="card custom-card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <div class="card-title">الأسئلة المرتبطة بالقسم ({{ $section->questions->count() }})</div>
                        </div>
                        <div class="card-body">
                            @if($section->questions->count() > 0)
                                <div class="table-responsive">
                                    <table class="table table-bordered text-nowrap" id="questionsTable">
                                        <thead>
                                            <tr>
                                                <th width="50">#</th>
                                                <th>السؤال</th>
                                                <th>النوع</th>
                                                <th>الدرجة</th>
                                                <th>إجباري</th>
                                                <th>الترتيب</th>
                                                <th width="150">الإجراءات</th>
                                            </tr>
                                        </thead>
                                        <tbody id="sortableQuestions">
                                            @foreach($section->questions as $question)
                                                <tr data-question-id="{{ $question->id }}">
                                                    <td>
                                                        <i class="fas fa-grip-vertical handle" style="cursor: move;"></i>
                                                    </td>
                                                    <td>
                                                        <div class="d-flex align-items-start">
                                                            <div>
                                                                <a href="{{ route('question-bank.show', $question->id) }}" target="_blank" class="fw-semibold">
                                                                    {!! Str::limit(strip_tags($question->question_text), 100) !!}
                                                                </a>
                                                                @if($question->tags)
                                                                    <div class="mt-1">
                                                                        @foreach($question->tags as $tag)
                                                                            <span class="badge bg-secondary-transparent">{{ $tag }}</span>
                                                                        @endforeach
                                                                    </div>
                                                                @endif
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-primary-transparent">
                                                            {{ $question->questionType->display_name ?? 'غير محدد' }}
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <input type="number" step="0.01" class="form-control form-control-sm question-grade"
                                                               data-question-id="{{ $question->id }}"
                                                               value="{{ $question->pivot->question_grade ?? $question->default_grade }}"
                                                               style="width: 80px;">
                                                    </td>
                                                    <td>
                                                        <div class="form-check form-switch">
                                                            <input class="form-check-input question-required" type="checkbox"
                                                                   data-question-id="{{ $question->id }}"
                                                                   {{ $question->pivot->is_required ? 'checked' : '' }}>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-info-transparent">{{ $question->pivot->question_order }}</span>
                                                    </td>
                                                    <td>
                                                        <button type="button" class="btn btn-sm btn-icon btn-danger remove-question"
                                                                data-question-id="{{ $question->id }}"
                                                                title="إزالة من القسم">
                                                            <i class="fas fa-times"></i>
                                                        </button>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            @else
                                <div class="text-center py-5">
                                    <i class="fas fa-question-circle fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">لا توجد أسئلة مرتبطة بهذا القسم بعد</p>
                                    <button type="button" class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#importQuestionModal">
                                        استيراد من بنك الأسئلة
                                    </button>
                                    <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#createQuestionModal">
                                        إنشاء سؤال جديد
                                    </button>
                                </div>
                            @endif
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <!-- Import Question Modal -->
    <div class="modal fade" id="importQuestionModal" tabindex="-1">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h6 class="modal-title">استيراد سؤال من بنك الأسئلة</h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <input type="text" id="searchQuestions" class="form-control" placeholder="ابحث عن سؤال...">
                    </div>

                    @if($availableQuestions->count() > 0)
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>السؤال</th>
                                        <th>النوع</th>
                                        <th>الدرجة</th>
                                        <th>المصدر</th>
                                        <th width="100">إجراء</th>
                                    </tr>
                                </thead>
                                <tbody id="questionsListBody">
                                    @foreach($availableQuestions as $question)
                                        <tr class="question-row" data-search-text="{{ strtolower(strip_tags($question->question_text)) }}">
                                            <td>
                                                {!! Str::limit(strip_tags($question->question_text), 150) !!}
                                                @if($question->tags)
                                                    <div class="mt-1">
                                                        @foreach($question->tags as $tag)
                                                            <span class="badge bg-secondary-transparent">{{ $tag }}</span>
                                                        @endforeach
                                                    </div>
                                                @endif
                                            </td>
                                            <td>
                                                <span class="badge bg-primary-transparent">
                                                    {{ $question->questionType->display_name ?? 'غير محدد' }}
                                                </span>
                                            </td>
                                            <td>{{ $question->default_grade }}</td>
                                            <td>
                                                @if($question->course_id)
                                                    <span class="badge bg-success-transparent">{{ $question->course->title }}</span>
                                                @else
                                                    <span class="badge bg-info-transparent">عام</span>
                                                @endif
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-primary import-question-btn"
                                                        data-question-id="{{ $question->id }}"
                                                        data-question-grade="{{ $question->default_grade }}">
                                                    <i class="fas fa-plus me-1"></i>استيراد
                                                </button>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @else
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            لا توجد أسئلة متاحة للاستيراد. جميع الأسئلة في بنك الأسئلة تم إضافتها بالفعل.
                        </div>
                    @endif
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إغلاق</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Create Question Modal -->
    <div class="modal fade" id="createQuestionModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h6 class="modal-title">إنشاء سؤال جديد</h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p class="text-muted mb-4">اختر نوع السؤال الذي تريد إنشاءه</p>

                    <div class="row g-3">
                        @foreach($questionTypes as $type)
                            @php
                                $icons = [
                                    'multiple_choice_single' => 'fa-dot-circle',
                                    'multiple_choice_multiple' => 'fa-check-double',
                                    'true_false' => 'fa-check-circle',
                                    'short_answer' => 'fa-font',
                                    'essay' => 'fa-pen-fancy',
                                    'matching' => 'fa-arrows-alt-h',
                                    'ordering' => 'fa-sort-numeric-down',
                                    'fill_blank' => 'fa-pen-square',
                                    'fill_blanks' => 'fa-pen-square',
                                    'numerical' => 'fa-calculator',
                                    'calculated' => 'fa-square-root-alt',
                                    'drag_drop' => 'fa-hand-pointer',
                                ];
                                $iconClass = $type->icon ?? ($icons[$type->name] ?? 'fa-question');
                                if (!str_starts_with($iconClass, 'fas ') && !str_starts_with($iconClass, 'far ') && !str_starts_with($iconClass, 'fab ')) {
                                    $iconClass = 'fas ' . $iconClass;
                                }
                            @endphp
                            <div class="col-md-6 col-lg-4">
                                <a href="{{ route('sections.questions.create', [$section->id, $type->name]) }}"
                                   class="card custom-card text-center card-hover h-100">
                                    <div class="card-body">
                                        <i class="{{ $iconClass }} fa-3x text-primary mb-3"></i>
                                        <h6 class="mb-2">{{ $type->display_name }}</h6>
                                        @if($type->description)
                                            <p class="text-muted small mb-0">{{ Str::limit($type->description, 60) }}</p>
                                        @endif
                                    </div>
                                </a>
                            </div>
                        @endforeach
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إغلاق</button>
                </div>
            </div>
        </div>
    </div>
@stop

@section('script')
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<script>
$(document).ready(function() {
    const sectionId = {{ $section->id }};

    // Sortable for reordering questions
    @if($section->questions->count() > 0)
    const sortable = new Sortable(document.getElementById('sortableQuestions'), {
        animation: 150,
        handle: '.handle',
        onEnd: function(evt) {
            const questionIds = [];
            $('#sortableQuestions tr').each(function() {
                questionIds.push($(this).data('question-id'));
            });

            $.ajax({
                url: `/admin/sections/${sectionId}/questions/reorder`,
                method: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    questions: questionIds
                },
                success: function(response) {
                    if(response.success) {
                        showToast('success', response.message);
                        // Update order badges
                        $('#sortableQuestions tr').each(function(index) {
                            $(this).find('.badge.bg-info-transparent').text(index + 1);
                        });
                    }
                },
                error: function(xhr) {
                    showToast('error', 'حدث خطأ أثناء إعادة الترتيب');
                }
            });
        }
    });
    @endif

    // Import question
    $(document).on('click', '.import-question-btn', function() {
        const btn = $(this);
        const questionId = btn.data('question-id');
        const questionGrade = btn.data('question-grade');

        console.log('Import Question:', {
            questionId: questionId,
            questionGrade: questionGrade
        });

        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>جاري الاستيراد...');

        $.ajax({
            url: `/admin/sections/${sectionId}/questions/import`,
            method: 'POST',
            data: {
                _token: '{{ csrf_token() }}',
                question_id: questionId,
                question_grade: questionGrade,
                is_required: 1  // Send as 1 instead of true for Laravel validation
            },
            success: function(response) {
                console.log('Import Success:', response);
                if(response.success) {
                    showToast('success', response.message);
                    setTimeout(() => location.reload(), 1000);
                }
            },
            error: function(xhr) {
                console.error('Import Error:', xhr);
                console.error('Response:', xhr.responseJSON);
                console.error('Validation Errors:', xhr.responseJSON?.errors);
                const message = xhr.responseJSON?.message || 'حدث خطأ أثناء استيراد السؤال';
                showToast('error', message);
                btn.prop('disabled', false).html('<i class="fas fa-plus me-1"></i>استيراد');
            }
        });
    });

    // Remove question
    $(document).on('click', '.remove-question', function() {
        const questionId = $(this).data('question-id');
        const row = $(this).closest('tr');

        if(confirm('هل أنت متأكد من إزالة هذا السؤال من القسم؟')) {
            $.ajax({
                url: `/admin/sections/${sectionId}/questions/${questionId}`,
                method: 'DELETE',
                data: {
                    _token: '{{ csrf_token() }}'
                },
                success: function(response) {
                    if(response.success) {
                        showToast('success', response.message);
                        row.fadeOut(300, function() {
                            $(this).remove();
                            if($('#sortableQuestions tr').length === 0) {
                                location.reload();
                            }
                        });
                    }
                },
                error: function(xhr) {
                    showToast('error', 'حدث خطأ أثناء إزالة السؤال');
                }
            });
        }
    });

    // Update question grade
    $(document).on('change', '.question-grade', function() {
        const questionId = $(this).data('question-id');
        const grade = $(this).val();

        $.ajax({
            url: `/admin/sections/${sectionId}/questions/${questionId}/settings`,
            method: 'PUT',
            data: {
                _token: '{{ csrf_token() }}',
                question_grade: grade
            },
            success: function(response) {
                if(response.success) {
                    showToast('success', 'تم تحديث الدرجة بنجاح');
                }
            },
            error: function(xhr) {
                showToast('error', 'حدث خطأ أثناء التحديث');
            }
        });
    });

    // Update question required
    $(document).on('change', '.question-required', function() {
        const questionId = $(this).data('question-id');
        const isRequired = $(this).is(':checked');

        $.ajax({
            url: `/admin/sections/${sectionId}/questions/${questionId}/settings`,
            method: 'PUT',
            data: {
                _token: '{{ csrf_token() }}',
                is_required: isRequired
            },
            success: function(response) {
                if(response.success) {
                    showToast('success', 'تم تحديث الإعداد بنجاح');
                }
            },
            error: function(xhr) {
                showToast('error', 'حدث خطأ أثناء التحديث');
            }
        });
    });

    // Search questions in import modal
    $('#searchQuestions').on('keyup', function() {
        const searchText = $(this).val().toLowerCase();
        $('.question-row').each(function() {
            const rowText = $(this).data('search-text');
            if(rowText.includes(searchText)) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });

    function showToast(type, message) {
        const bgColor = type === 'success' ? 'bg-success' : 'bg-danger';
        const toast = `
            <div class="position-fixed top-0 end-0 p-3" style="z-index: 9999">
                <div class="toast align-items-center text-white ${bgColor} border-0 show" role="alert">
                    <div class="d-flex">
                        <div class="toast-body">${message}</div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                </div>
            </div>
        `;
        $('body').append(toast);
        setTimeout(() => $('.toast').remove(), 3000);
    }
});
</script>
@stop
