<?php

namespace App\Http\Controllers\Teacher;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class ExamQuestionController extends Controller
{
    public function index(Request $request, int $examId): Response|RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        abort_unless($schoolId, 403);

        $exam = DB::table('exams')
            ->where('school_id', $schoolId)
            ->where('id', $examId)
            ->first();

        abort_unless($exam, 404);

        $questions = DB::table('exam_questions')
            ->where('school_id', $schoolId)
            ->where('exam_id', $examId)
            ->orderBy('sort_order')
            ->get(['id', 'question_type', 'body', 'score', 'sort_order'])
            ->map(function ($q): array {
                $options = [];
                if ($q->question_type === 'test') {
                    $options = DB::table('exam_options')
                        ->where('question_id', $q->id)
                        ->orderBy('sort_order')
                        ->get(['id', 'body', 'is_correct'])
                        ->map(fn ($o): array => [
                            'id' => (int) $o->id,
                            'body' => $o->body,
                            'isCorrect' => (bool) $o->is_correct,
                        ])
                        ->values()
                        ->all();
                }

                return [
                    'id' => (int) $q->id,
                    'type' => $q->question_type,
                    'body' => $q->body,
                    'score' => (float) $q->score,
                    'sortOrder' => (int) $q->sort_order,
                    'options' => $options,
                ];
            })
            ->values();

        return Inertia::render('Teacher/ExamQuestions', [
            'exam' => [
                'id' => (int) $exam->id,
                'title' => $exam->title,
                'status' => $exam->status,
                'type' => $exam->type,
            ],
            'questions' => $questions,
        ]);
    }

    public function store(Request $request, int $examId): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        abort_unless($schoolId, 403);

        $exam = DB::table('exams')->where('school_id', $schoolId)->where('id', $examId)->first();
        abort_unless($exam, 404);
        abort_if($exam->status === 'published', 422, 'امتحان منتشر شده قابل ویرایش نیست.');

        $data = $request->validate([
            'question_type' => 'required|in:test,descriptive,file',
            'body' => 'required|string|max:2000',
            'score' => 'required|numeric|min:0.5|max:100',
            'options' => 'array|min:2|max:6',
            'options.*.body' => 'required|string|max:500',
            'options.*.is_correct' => 'boolean',
        ]);

        $maxOrder = DB::table('exam_questions')
            ->where('exam_id', $examId)
            ->max('sort_order') ?? 0;

        DB::transaction(function () use ($schoolId, $examId, $data, $maxOrder): void {
            $questionId = DB::table('exam_questions')->insertGetId([
                'school_id' => $schoolId,
                'exam_id' => $examId,
                'question_type' => $data['question_type'],
                'body' => $data['body'],
                'score' => $data['score'],
                'sort_order' => $maxOrder + 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            if ($data['question_type'] === 'test' && ! empty($data['options'])) {
                foreach ($data['options'] as $idx => $opt) {
                    DB::table('exam_options')->insert([
                        'question_id' => $questionId,
                        'body' => $opt['body'],
                        'is_correct' => (bool) ($opt['is_correct'] ?? false),
                        'sort_order' => $idx,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }
        });

        return back()->with('success', 'سوال اضافه شد.');
    }

    public function destroy(Request $request, int $examId, int $questionId): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        abort_unless($schoolId, 403);

        $exam = DB::table('exams')->where('school_id', $schoolId)->where('id', $examId)->first();
        abort_unless($exam, 404);
        abort_if($exam->status === 'published', 422, 'امتحان منتشر شده قابل ویرایش نیست.');

        DB::table('exam_questions')
            ->where('school_id', $schoolId)
            ->where('exam_id', $examId)
            ->where('id', $questionId)
            ->delete();

        return back()->with('success', 'سوال حذف شد.');
    }

    public function updateStatus(Request $request, int $examId): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        abort_unless($schoolId, 403);

        $data = $request->validate(['status' => 'required|in:draft,published,archived']);

        $updated = DB::table('exams')
            ->where('school_id', $schoolId)
            ->where('id', $examId)
            ->update(['status' => $data['status'], 'updated_at' => now()]);

        abort_unless($updated, 404);

        $label = match ($data['status']) {
            'published' => 'منتشر شد',
            'draft' => 'به پیش‌نویس بازگشت',
            'archived' => 'آرشیو شد',
            default => 'بروزرسانی شد',
        };

        return back()->with('success', "امتحان {$label}.");
    }
}
