<?php

namespace App\Http\Controllers\Admin;

use App\Models\Question;
use App\Models\Lesson;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Imports\QuestionBankImport;
use App\Exports\QuestionBankFormatExport;
use Maatwebsite\Excel\Facades\Excel;

class QuestionBankController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Inertia\Response
     */
    public function index()
    {
        $questions = Question::when(request()->q, function ($questions) {
            $questions = $questions->where('question', 'like', '%' . request()->q . '%');
        })
        ->when(request()->lesson_id, function($q) {
            $q->where('lesson_id', request()->lesson_id);
        })
        ->with(['lesson'])
        ->latest()
        ->paginate(10);

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

        $lessons = Lesson::all();

        return inertia('Admin/QuestionBank/Index', [
            'questions' => $questions,
            'lessons' => $lessons,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Inertia\Response
     */
    public function create()
    {
        $lessons = Lesson::all();

        return inertia('Admin/QuestionBank/Create', [
            'lessons' => $lessons,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        /* Minimal validation for this example */
        $request->validate([
            'lesson_id' => 'required',
            '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',
        ]);

        $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, // the cast handles array for json
        ]);

        if ($request->has('add_more')) {
            return redirect()->back();
        }
        return redirect()->route('admin.questions.index');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Inertia\Response
     */
    public function edit($id)
    {
        $question = Question::findOrFail($id);
        $lessons = Lesson::all();

        return inertia('Admin/QuestionBank/Edit', [
            'question' => $question,
            'lessons' => $lessons,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $id)
    {
        $question = Question::findOrFail($id);

        $request->validate([
            'lesson_id' => 'required',
            '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',
        ]);

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

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

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

            if ($request->hasFile($field)) {
                // Delete old file if exists
                $oldFile = $question->{$field};
                if ($oldFile && \Illuminate\Support\Facades\Storage::disk('public')->exists('questions/' . $oldFile)) {
                    \Illuminate\Support\Facades\Storage::disk('public')->delete('questions/' . $oldFile);
                }
                // Store new file
                $optionImageData[$field] = basename($request->file($field)->store('questions', 'public'));
            } elseif ($request->boolean($removeFlag)) {
                // Remove existing image
                $oldFile = $question->{$field};
                if ($oldFile && \Illuminate\Support\Facades\Storage::disk('public')->exists('questions/' . $oldFile)) {
                    \Illuminate\Support\Facades\Storage::disk('public')->delete('questions/' . $oldFile);
                }
                $optionImageData[$field] = null;
            } else {
                // Keep existing value
                $optionImageData[$field] = $question->{$field};
            }
        }

        $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' => $optionImageData['option_1_image'],
            'option_2_image' => $optionImageData['option_2_image'],
            'option_3_image' => $optionImageData['option_3_image'],
            'option_4_image' => $optionImageData['option_4_image'],
            'option_5_image' => $optionImageData['option_5_image'],
            'answer' => $request->answer,
        ]);

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        $question = Question::findOrFail($id);
        
        $oldImageName = basename($question->image);
        if ($oldImageName && \Illuminate\Support\Facades\Storage::disk('public')->exists('questions/' . $oldImageName)) {
            \Illuminate\Support\Facades\Storage::disk('public')->delete('questions/' . $oldImageName);
        }

        // Hapus semua file option image yang ada dari storage
        for ($i = 1; $i <= 5; $i++) {
            $optionImageField = "option_{$i}_image";
            $optionImage = $question->{$optionImageField};
            if ($optionImage) {
                $optionImageName = basename($optionImage);
                if ($optionImageName && \Illuminate\Support\Facades\Storage::disk('public')->exists('questions/' . $optionImageName)) {
                    \Illuminate\Support\Facades\Storage::disk('public')->delete('questions/' . $optionImageName);
                }
            }
        }

        $question->delete();
        return redirect()->route('admin.questions.index');
    }

    /**
     * Download format import excel untuk bank soal.
     *
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function exportFormat()
    {
        return Excel::download(new QuestionBankFormatExport(), 'format-import-bank-soal.xlsx');
    }

    /**
     * Handle import soal ke bank soal dari excel.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function storeImport(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:csv,xls,xlsx|max:5120',
        ]);

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

        $failures = $import->failures();
        $rowsImported = $import->getRowsImported();

        if ($failures->isNotEmpty()) {
            $errors = [];
            foreach ($failures as $failure) {
                foreach ($failure->errors() as $error) {
                    $errors[] = "Baris {$failure->row()}: {$error}";
                }
            }

            if ($rowsImported > 0) {
                // Sebagian berhasil, sebagian gagal
                return redirect()->route('admin.questions.index')
                    ->with('success', "{$rowsImported} soal berhasil diimport.")
                    ->withErrors($errors);
            }

            // Semua gagal
            return redirect()->route('admin.questions.index')
                ->withErrors($errors);
        }

        if ($rowsImported === 0) {
            return redirect()->route('admin.questions.index')
                ->with('error', 'Tidak ada soal yang diimport. Pastikan file tidak kosong dan sesuai format.');
        }

        return redirect()->route('admin.questions.index')
            ->with('success', "{$rowsImported} soal berhasil diimport ke Bank Soal!");
    }
}
