<?php

namespace App\Http\Controllers\Teacher;

use App\Http\Controllers\Concerns\RestrictsTeacherLessons;
use App\Http\Controllers\Controller;
use App\Exports\QuestionBankFormatExport;
use App\Imports\QuestionBankImport;
use App\Models\Question;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class QuestionBankController extends Controller
{
    use RestrictsTeacherLessons;

    public function index()
    {
        $questions = $this->teacherQuestions()
            ->when(request()->q, function ($query) {
                $query->where('question', 'like', '%' . request()->q . '%');
            })
            ->when(request()->lesson_id, function ($query) {
                $query->where('lesson_id', request()->lesson_id);
            })
            ->with('lesson')
            ->latest()
            ->paginate(10);

        $questions->appends(['q' => request()->q, 'lesson_id' => request()->lesson_id]);

        return inertia('Admin/QuestionBank/Index', [
            'questions' => $questions,
            'lessons' => $this->teacherLessons()->orderBy('title')->get(),
        ]);
    }

    public function create()
    {
        return inertia('Admin/QuestionBank/Create', [
            'lessons' => $this->teacherLessons()->orderBy('title')->get(),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'lesson_id' => 'required|integer|exists:lessons,id',
            'type' => 'required',
            'difficulty' => 'nullable|in:mudah,sedang,sulit',
            'question' => 'required',
            'option_1_image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
            'option_2_image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
            'option_3_image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
            'option_4_image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
            'option_5_image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
        ]);

        $this->ensureTeacherOwnsLesson((int) $request->lesson_id);

        $imageName = null;
        if ($request->hasFile('image')) {
            $imageName = basename($request->file('image')->store('questions', 'public'));
        }

        // Handle option images upload
        $optionImages = [];
        for ($i = 1; $i <= 5; $i++) {
            $field = "option_{$i}_image";
            if ($request->hasFile($field)) {
                $optionImages[$field] = basename($request->file($field)->store('questions', 'public'));
            } else {
                $optionImages[$field] = null;
            }
        }

        Question::create([
            'lesson_id' => $request->lesson_id,
            'type' => $request->type,
            'difficulty' => $request->difficulty,
            'kompetensi' => $request->kompetensi,
            'question' => $request->question,
            'image' => $imageName,
            'option_1' => $request->option_1,
            'option_1_image' => $optionImages['option_1_image'],
            'option_2' => $request->option_2,
            'option_2_image' => $optionImages['option_2_image'],
            'option_3' => $request->option_3,
            'option_3_image' => $optionImages['option_3_image'],
            'option_4' => $request->option_4,
            'option_4_image' => $optionImages['option_4_image'],
            'option_5' => $request->option_5,
            'option_5_image' => $optionImages['option_5_image'],
            'answer' => $request->answer,
        ]);

        return $request->has('add_more')
            ? redirect()->back()
            : redirect()->route('teacher.questions.index');
    }

    public function edit($id)
    {
        $question = $this->teacherQuestions()->findOrFail($id);

        return inertia('Admin/QuestionBank/Edit', [
            'question' => $question,
            'lessons' => $this->teacherLessons()->orderBy('title')->get(),
        ]);
    }

    public function update(Request $request, $id)
    {
        $question = $this->teacherQuestions()->findOrFail($id);

        $request->validate([
            'lesson_id' => 'required|integer|exists:lessons,id',
            'type' => 'required',
            'difficulty' => 'nullable|in:mudah,sedang,sulit',
            'question' => 'required',
            'option_1_image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
            'option_2_image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
            'option_3_image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
            'option_4_image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
            'option_5_image' => 'nullable|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
        ]);

        $this->ensureTeacherOwnsLesson((int) $request->lesson_id);

        $imageName = $question->image;
        if ($request->hasFile('image')) {
            if ($question->image && Storage::disk('public')->exists('questions/' . basename($question->image))) {
                Storage::disk('public')->delete('questions/' . basename($question->image));
            }
            $imageName = basename($request->file('image')->store('questions', 'public'));
        }

        if ($request->remove_image) {
            if ($question->image && Storage::disk('public')->exists('questions/' . basename($question->image))) {
                Storage::disk('public')->delete('questions/' . basename($question->image));
            }
            $imageName = null;
        }

        // Handle option images upload/replace/remove
        $optionImages = [];
        for ($i = 1; $i <= 5; $i++) {
            $field = "option_{$i}_image";
            $removeFlag = "remove_option_{$i}_image";

            $optionImages[$field] = $question->{$field};

            // Upload new option image (replace old if exists)
            if ($request->hasFile($field)) {
                $oldFile = $question->{$field};
                if ($oldFile && Storage::disk('public')->exists('questions/' . basename($oldFile))) {
                    Storage::disk('public')->delete('questions/' . basename($oldFile));
                }
                $optionImages[$field] = basename($request->file($field)->store('questions', 'public'));
            }

            // Remove option image if flag is set
            if ($request->boolean($removeFlag)) {
                $oldFile = $question->{$field};
                if ($oldFile && Storage::disk('public')->exists('questions/' . basename($oldFile))) {
                    Storage::disk('public')->delete('questions/' . basename($oldFile));
                }
                $optionImages[$field] = null;
            }
        }

        $question->update([
            'lesson_id' => $request->lesson_id,
            'type' => $request->type,
            'difficulty' => $request->difficulty,
            'kompetensi' => $request->kompetensi,
            'question' => $request->question,
            'image' => $imageName,
            'option_1' => $request->option_1,
            'option_2' => $request->option_2,
            'option_3' => $request->option_3,
            'option_4' => $request->option_4,
            'option_5' => $request->option_5,
            'option_1_image' => $optionImages['option_1_image'],
            'option_2_image' => $optionImages['option_2_image'],
            'option_3_image' => $optionImages['option_3_image'],
            'option_4_image' => $optionImages['option_4_image'],
            'option_5_image' => $optionImages['option_5_image'],
            'answer' => $request->answer,
        ]);

        return redirect()->route('teacher.questions.index');
    }

    public function destroy($id)
    {
        $question = $this->teacherQuestions()->findOrFail($id);

        if ($question->image && Storage::disk('public')->exists('questions/' . basename($question->image))) {
            Storage::disk('public')->delete('questions/' . basename($question->image));
        }

        // Delete all option images from storage
        for ($i = 1; $i <= 5; $i++) {
            $field = "option_{$i}_image";
            if ($question->$field && Storage::disk('public')->exists('questions/' . basename($question->$field))) {
                Storage::disk('public')->delete('questions/' . basename($question->$field));
            }
        }

        $question->delete();

        return redirect()->route('teacher.questions.index');
    }

    public function exportFormat()
    {
        return Excel::download(new QuestionBankFormatExport(), 'format-import-bank-soal.xlsx');
    }

    public function storeImport(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:csv,xls,xlsx|max:5120',
        ]);

        Excel::import(
            new QuestionBankImport($this->teacherLessonIds()),
            $request->file('file')
        );

        return redirect()->route('teacher.questions.index')
            ->with('success', 'Soal berhasil diimport ke Bank Soal!');
    }
}
