<?php

namespace App\Livewire\Admin;

use App\Models\Quiz;
use App\Models\QuizQuestion;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\Attributes\On;

class QuestionManagement extends Component
{
    use WithPagination;

    public $quiz;
    public $search = '';
    public $typeFilter = '';
    public $sortField = 'order';
    public $sortDirection = 'asc';

    protected $queryString = [
        'search' => ['except' => ''],
        'typeFilter' => ['except' => ''],
        'sortField' => ['except' => 'order'],
        'sortDirection' => ['except' => 'asc'],
    ];

    public function mount(Quiz $quiz)
    {
        $this->quiz = $quiz;
    }

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortField = $field;
            $this->sortDirection = 'asc';
        }
    }

    public function clearFilters()
    {
        $this->search = '';
        $this->typeFilter = '';
        $this->sortField = 'order';
        $this->sortDirection = 'asc';
    }

    public function deleteQuestion($questionId)
    {
        $question = QuizQuestion::findOrFail($questionId);
        $question->delete();
        
        session()->flash('success', 'Question deleted successfully.');
    }

    #[On('deleteQuestion')]
    public function handleDeleteQuestion($questionId)
    {
        $this->deleteQuestion($questionId);
    }

    public function reorderQuestions($questionIds)
    {
        foreach ($questionIds as $index => $questionId) {
            QuizQuestion::where('id', $questionId)
                ->where('quiz_id', $this->quiz->id)
                ->update(['order' => $index + 1]);
        }

        session()->flash('success', 'Questions reordered successfully.');
    }

    public function render()
    {
        $questions = $this->quiz->allQuestions()
            ->when($this->search, function ($query) {
                $query->where('question_text', 'like', '%' . $this->search . '%');
            })
            ->when($this->typeFilter, function ($query) {
                $query->where('type', $this->typeFilter);
            })
            ->orderBy($this->sortField, $this->sortDirection)
            ->paginate(10);

        $questionTypes = QuizQuestion::QUESTION_TYPES;

        return view('livewire.admin.question-management', [
            'questions' => $questions,
            'questionTypes' => $questionTypes,
        ]);
    }
}