@extends('layouts.admin')

@section('title', 'Edit Quiz')
@section('page-title', 'Edit Quiz: ' . $quiz->title)

@section('content')
    <div class="card">
        <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
            <h3>Edit Quiz</h3>
            <div style="display: flex; gap: 10px;">
                <a href="{{ route('admin.quizzes.export', $quiz->id) }}" class="btn btn-secondary">
                    <i class="fas fa-download"></i> Export JSON
                </a>
            </div>
        </div>
        
        <div style="padding: 0 30px 30px 30px;">
            <!-- Quiz Info Form -->
            <form method="POST" action="{{ route('admin.quizzes.update', $quiz->id) }}" style="margin-bottom: 40px;">
                @csrf
                @method('PUT')
                
                <div class="form-group">
                    <label for="title">Quiz Title *</label>
                    <input type="text" id="title" name="title" value="{{ old('title', $quiz->title) }}" required>
                </div>
                
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea id="description" name="description" rows="3">{{ old('description', $quiz->description) }}</textarea>
                </div>
                
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px;">
                    <div class="form-group">
                        <label for="level">Level *</label>
                        <select id="level" name="level" required>
                            <option value="1" {{ old('level', $quiz->level) == '1' ? 'selected' : '' }}>Beginner</option>
                            <option value="2" {{ old('level', $quiz->level) == '2' ? 'selected' : '' }}>Intermediate</option>
                            <option value="3" {{ old('level', $quiz->level) == '3' ? 'selected' : '' }}>Advanced</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="course_id">Course (Optional)</label>
                        <select id="course_id" name="course_id">
                            <option value="">None</option>
                            @foreach($courses as $course)
                                <option value="{{ $course->id }}" {{ old('course_id', $quiz->course_id) == $course->id ? 'selected' : '' }}>
                                    {{ $course->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="book_id">Book (Optional)</label>
                        <select id="book_id" name="book_id">
                            <option value="">None</option>
                            @foreach($books as $book)
                                <option value="{{ $book->id }}" {{ old('book_id', $quiz->book_id) == $book->id ? 'selected' : '' }}>
                                    {{ $book->title }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="time_limit_minutes">Time Limit (Minutes, Optional)</label>
                        <input type="number" id="time_limit_minutes" name="time_limit_minutes" value="{{ old('time_limit_minutes', $quiz->time_limit_minutes) }}" min="1" placeholder="e.g., 30">
                        <small style="color: #888; font-size: 12px; display: block; margin-top: 5px;">Leave empty for no time limit</small>
                    </div>
                </div>
                
                <div class="form-group" style="margin-top: 20px;">
                    <label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
                        <input type="checkbox" name="is_active" value="1" {{ old('is_active', $quiz->is_active) ? 'checked' : '' }}>
                        <span>Active (visible to students)</span>
                    </label>
                </div>
                
                <div style="margin-top: 20px;">
                    <button type="submit" class="btn btn-primary">Update Quiz Info</button>
                </div>
            </form>
            
            <!-- Questions Section -->
            <div style="border-top: 2px solid #404040; padding-top: 30px;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3>Questions ({{ $quiz->questions->count() }})</h3>
                    <button type="button" onclick="showAddQuestionForm()" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add Question
                    </button>
                </div>
                
                <!-- Add Question Form (Hidden by default) -->
                <div id="add-question-form" style="display: none; background: #2d2d2d; padding: 25px; border-radius: 8px; margin-bottom: 30px; border: 1px solid #404040;">
                    <h4 style="margin-bottom: 20px; color: #4a9eff;">Add New Question</h4>
                    <form method="POST" action="{{ route('admin.quizzes.questions.store', $quiz->id) }}">
                        @csrf
                        <div class="form-group">
                            <label for="new_question">Question *</label>
                            <textarea id="new_question" name="question" rows="3" required></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="new_question_type">Question Type *</label>
                            <select id="new_question_type" name="question_type" required>
                                <option value="multiple_choice">Multiple Choice</option>
                                <option value="true_false">True/False</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="new_explanation">Explanation (shown when answer is wrong)</label>
                            <textarea id="new_explanation" name="explanation" rows="2"></textarea>
                        </div>
                        
                        <div id="answers-container">
                            <label style="display: block; margin-bottom: 10px; font-weight: bold;">Answers *</label>
                            <div id="answer-inputs">
                                <div class="answer-input" style="margin-bottom: 10px;">
                                    <div style="display: flex; gap: 10px; align-items: center;">
                                        <input type="text" name="answers[0][text]" placeholder="Answer text" required style="flex: 1;">
                                        <label style="display: flex; align-items: center; gap: 5px; cursor: pointer;">
                                            <input type="radio" name="correct_answer" value="0" required>
                                            <span>Correct</span>
                                        </label>
                                        <button type="button" onclick="removeAnswer(this)" class="btn btn-secondary" style="padding: 6px 12px;">Remove</button>
                                    </div>
                                </div>
                                <div class="answer-input" style="margin-bottom: 10px;">
                                    <div style="display: flex; gap: 10px; align-items: center;">
                                        <input type="text" name="answers[1][text]" placeholder="Answer text" required style="flex: 1;">
                                        <label style="display: flex; align-items: center; gap: 5px; cursor: pointer;">
                                            <input type="radio" name="correct_answer" value="1" required>
                                            <span>Correct</span>
                                        </label>
                                        <button type="button" onclick="removeAnswer(this)" class="btn btn-secondary" style="padding: 6px 12px;">Remove</button>
                                    </div>
                                </div>
                            </div>
                            <button type="button" onclick="addAnswerInput()" class="btn btn-secondary" style="margin-top: 10px;">
                                <i class="fas fa-plus"></i> Add Answer
                            </button>
                        </div>
                        
                        <div style="margin-top: 20px; display: flex; gap: 10px;">
                            <button type="submit" class="btn btn-primary">Add Question</button>
                            <button type="button" onclick="hideAddQuestionForm()" class="btn btn-secondary">Cancel</button>
                        </div>
                    </form>
                </div>
                
                <!-- Existing Questions -->
                @if($quiz->questions->count() > 0)
                    @foreach($quiz->questions as $index => $question)
                        <div class="card" style="background: #2d2d2d; border: 1px solid #404040; margin-bottom: 20px;">
                            <div style="padding: 20px;">
                                <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 15px;">
                                    <div>
                                        <span style="background: #4a9eff; color: white; padding: 5px 12px; border-radius: 4px; font-size: 12px; font-weight: bold; margin-right: 10px;">
                                            Question {{ $index + 1 }}
                                        </span>
                                        <span style="color: #888; font-size: 12px;">{{ ucfirst(str_replace('_', ' ', $question->question_type)) }}</span>
                                    </div>
                                    <div style="display: flex; gap: 8px;">
                                        <button type="button" onclick="editQuestion({{ $question->id }})" class="btn btn-secondary" style="padding: 6px 12px; font-size: 12px;">
                                            <i class="fas fa-edit"></i> Edit
                                        </button>
                                        <button type="button" onclick="openConfirmationModal('Delete Question', 'Are you sure you want to delete this question?', '{{ route('admin.quizzes.questions.destroy', ['quiz' => $quiz->id, 'question' => $question->id]) }}', 'DELETE')" class="btn btn-secondary" style="padding: 6px 12px; font-size: 12px; background: #dc3545; border: none;">
                                            <i class="fas fa-trash"></i> Delete
                                        </button>
                                    </div>
                                </div>
                                
                                <div style="font-size: 16px; font-weight: 500; margin-bottom: 15px; color: #e0e0e0;">
                                    {{ $question->question }}
                                </div>
                                
                                @if($question->explanation)
                                    <div style="color: #888; font-size: 13px; margin-bottom: 15px; font-style: italic;">
                                        <strong>Explanation:</strong> {{ $question->explanation }}
                                    </div>
                                @endif
                                
                                <div style="margin-top: 15px;">
                                    <strong style="color: #888; font-size: 13px; display: block; margin-bottom: 8px;">Answers:</strong>
                                    @foreach($question->answers as $answer)
                                        <div style="padding: 8px 12px; margin-bottom: 5px; background: #1a1a1a; border-radius: 4px; border-left: 3px solid {{ $answer->is_correct ? '#6bff6b' : '#404040' }};">
                                            <span style="color: {{ $answer->is_correct ? '#6bff6b' : '#e0e0e0' }};">
                                                {{ $answer->answer_text }}
                                                @if($answer->is_correct)
                                                    <i class="fas fa-check-circle" style="margin-left: 8px;"></i>
                                                @endif
                                            </span>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                    @endforeach
                @else
                    <div style="text-align: center; padding: 40px; color: #888;">
                        <p>No questions yet. Add your first question to get started!</p>
                    </div>
                @endif
            </div>
        </div>
    </div>
@endsection

@push('scripts')
<script>
    let answerIndex = 2;
    
    function showAddQuestionForm() {
        document.getElementById('add-question-form').style.display = 'block';
        document.getElementById('add-question-form').scrollIntoView({ behavior: 'smooth' });
    }
    
    function hideAddQuestionForm() {
        document.getElementById('add-question-form').style.display = 'none';
        document.getElementById('add-question-form').querySelector('form').reset();
        answerIndex = 2;
        // Reset to 2 answers
        const container = document.getElementById('answer-inputs');
        while (container.children.length > 2) {
            container.removeChild(container.lastChild);
        }
    }
    
    function addAnswerInput() {
        const container = document.getElementById('answer-inputs');
        const div = document.createElement('div');
        div.className = 'answer-input';
        div.style.marginBottom = '10px';
        div.innerHTML = `
            <div style="display: flex; gap: 10px; align-items: center;">
                <input type="text" name="answers[${answerIndex}][text]" placeholder="Answer text" required style="flex: 1;">
                <label style="display: flex; align-items: center; gap: 5px; cursor: pointer;">
                    <input type="radio" name="correct_answer" value="${answerIndex}" required>
                    <span>Correct</span>
                </label>
                <button type="button" onclick="removeAnswer(this)" class="btn btn-secondary" style="padding: 6px 12px;">Remove</button>
            </div>
        `;
        container.appendChild(div);
        answerIndex++;
    }
    
    function removeAnswer(btn) {
        const container = document.getElementById('answer-inputs');
        if (container.children.length > 2) {
            btn.closest('.answer-input').remove();
        } else {
            alert('You must have at least 2 answers.');
        }
    }
    
    function editQuestion(questionId) {
        // This would open a modal or navigate to edit page
        // For now, we'll use a simple approach - you can enhance this later
        alert('Edit question functionality - you can enhance this to open a modal or navigate to an edit page');
    }
    
    // Convert radio buttons to proper format for backend
    document.querySelector('#add-question-form form').addEventListener('submit', function(e) {
        const correctAnswerIndex = parseInt(this.querySelector('input[name="correct_answer"]:checked').value);
        
        // Get all answer text inputs
        const answerTextInputs = Array.from(this.querySelectorAll('input[name^="answers"][name$="[text]"]'));
        
        // Create proper answer format
        answerTextInputs.forEach((input, index) => {
            const answerIndex = parseInt(input.name.match(/\[(\d+)\]/)[1]);
            const isCorrect = answerIndex === correctAnswerIndex;
            
            // Update the input name to match expected format
            input.name = `answers[${index}][text]`;
            
            // Add hidden input for is_correct
            const correctInput = document.createElement('input');
            correctInput.type = 'hidden';
            correctInput.name = `answers[${index}][is_correct]`;
            correctInput.value = isCorrect ? '1' : '0';
            input.parentElement.appendChild(correctInput);
        });
        
        // Remove radio buttons (they're not needed in the submission)
        this.querySelectorAll('input[name="correct_answer"]').forEach(radio => {
            radio.remove();
        });
    });
</script>
@endpush

