<?php

namespace App\Http\Controllers\Teacher;

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

class ExamController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $classes = $schoolId
            ? DB::table('classrooms')
                ->where('school_id', $schoolId)
                ->where('status', 'active')
                ->orderBy('name')
                ->get(['id', 'name'])
            : collect();

        $subjects = $schoolId
            ? DB::table('subjects')
                ->where('school_id', $schoolId)
                ->where('status', 'active')
                ->orderBy('name')
                ->get(['id', 'name'])
            : collect();

        $recentExams = $schoolId
            ? DB::table('exams')
                ->leftJoin('classrooms', 'classrooms.id', '=', 'exams.classroom_id')
                ->leftJoin('subjects', 'subjects.id', '=', 'exams.subject_id')
                ->where('exams.school_id', $schoolId)
                ->select(['exams.id', 'exams.title', 'exams.status', 'exams.starts_at', 'classrooms.name as classroom_name', 'subjects.name as subject_name'])
                ->latest('exams.created_at')
                ->limit(10)
                ->get()
            : collect();

        return Inertia::render('Exams/ExamBuilder', [
            'classes' => $classes->map(fn ($classroom): array => ['value' => $classroom->id, 'label' => $classroom->name])->values(),
            'subjects' => $subjects->map(fn ($subject): array => ['value' => $subject->id, 'label' => $subject->name])->values(),
            'recentExams' => $recentExams->map(fn ($exam): array => [
                'id' => (int) $exam->id,
                'title' => $exam->title,
                'classroom' => $exam->classroom_name ?: '—',
                'subject' => $exam->subject_name ?: '—',
                'status' => $exam->status,
                'startsAt' => $exam->starts_at ? $this->jalaliDate($exam->starts_at, true) : '—',
            ])->values(),
        ]);
    }

    public function store(StoreExamRequest $request): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);

        abort_unless($schoolId, 422, 'مدرسه مشخص نیست.');

        $data = $request->validated();
        $teacherId = $this->teacherId($request, (int) $schoolId);

        if (! $teacherId) {
            return back()->withErrors(['teacher_id' => 'برای کاربر فعلی معلمی ثبت نشده است.'])->withInput();
        }

        $classOk = DB::table('classrooms')->where('school_id', $schoolId)->where('id', $data['classroom_id'])->exists();
        $subjectOk = DB::table('subjects')->where('school_id', $schoolId)->where('id', $data['subject_id'])->exists();

        if (! $classOk || ! $subjectOk) {
            return back()->withErrors(['classroom_id' => 'کلاس یا درس برای این مدرسه معتبر نیست.'])->withInput();
        }

        $examId = DB::table('exams')->insertGetId([
            'school_id' => $schoolId,
            'classroom_id' => $data['classroom_id'],
            'subject_id' => $data['subject_id'],
            'teacher_id' => $teacherId,
            'title' => $data['title'],
            'type' => $data['type'],
            'starts_at' => $data['starts_at'] ?? null,
            'ends_at' => $data['ends_at'] ?? null,
            'duration_minutes' => $data['duration_minutes'] ?? null,
            'max_score' => $data['max_score'] ?? 20,
            'status' => 'draft',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return redirect()->route('teacher.exam.questions', ['id' => $examId])->with('success', 'امتحان ساخته شد. اکنون سوال‌ها را اضافه کنید.');
    }

    private function teacherId(Request $request, int $schoolId): ?int
    {
        $userId = $request->user()?->id;

        return DB::table('teachers')
            ->where('school_id', $schoolId)
            ->when($userId, fn ($query) => $query->where('user_id', $userId))
            ->value('id')
            ?: DB::table('teachers')->where('school_id', $schoolId)->value('id');
    }
}
