<?php

namespace App\Http\Controllers\School;

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 ClassroomController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $classes = $schoolId
            ? DB::table('classrooms')
                ->leftJoin('grade_levels', 'grade_levels.id', '=', 'classrooms.grade_level_id')
                ->leftJoin('class_students', function ($join): void {
                    $join->on('class_students.classroom_id', '=', 'classrooms.id')
                        ->where('class_students.status', '=', 'active');
                })
                ->where('classrooms.school_id', $schoolId)
                ->groupBy('classrooms.id', 'classrooms.grade_level_id', 'classrooms.name', 'classrooms.capacity', 'classrooms.status', 'grade_levels.name_fa')
                ->select([
                    'classrooms.id',
                    'classrooms.grade_level_id',
                    'classrooms.name',
                    'classrooms.capacity',
                    'classrooms.status',
                    'grade_levels.name_fa as grade_name',
                    DB::raw('COUNT(class_students.id) as students_count'),
                ])
                ->orderBy('classrooms.name')
                ->get()
            : collect();

        $enabledGrades = $schoolId
            ? DB::table('school_grade_levels')
                ->join('grade_levels', 'grade_levels.id', '=', 'school_grade_levels.grade_level_id')
                ->where('school_grade_levels.school_id', $schoolId)
                ->where('school_grade_levels.enabled', true)
                ->orderBy('grade_levels.number')
                ->pluck('grade_levels.name_fa')
                ->values()
            : collect();

        return Inertia::render('School/Classes', [
            'enabledGrades' => $enabledGrades,
            'gradeOptions' => $schoolId ? $this->gradeOptions((int) $schoolId) : [],
            'classes' => $classes->map(fn ($classroom): array => [
                'id' => $classroom->id,
                'name' => $classroom->name,
                'grade' => $classroom->grade_name ?: '—',
                'gradeLevelId' => $classroom->grade_level_id,
                'studentsCount' => (int) $classroom->students_count,
                'capacity' => $classroom->capacity ? (int) $classroom->capacity : null,
                'status' => $classroom->status,
            ])->values(),
        ]);
    }

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

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

        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'grade_level_id' => ['required', 'integer'],
            'capacity' => ['nullable', 'integer', 'min:1', 'max:1000'],
        ]);

        $gradeAllowed = DB::table('school_grade_levels')
            ->where('school_id', $schoolId)
            ->where('grade_level_id', $data['grade_level_id'])
            ->where('enabled', true)
            ->exists();

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

        $exists = DB::table('classrooms')
            ->where('school_id', $schoolId)
            ->where('name', $data['name'])
            ->exists();

        if ($exists) {
            return back()->withErrors(['name' => 'کلاسی با این نام قبلا ثبت شده است.'])->withInput();
        }

        DB::table('classrooms')->insert([
            'school_id' => $schoolId,
            'grade_level_id' => $data['grade_level_id'],
            'name' => $data['name'],
            'capacity' => $data['capacity'] ?? null,
            'status' => 'active',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return redirect()->route('school.classes')->with('success', 'کلاس ثبت شد.');
    }

    public function update(Request $request, int $id): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);

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

        $exists = DB::table('classrooms')->where('id', $id)->where('school_id', $schoolId)->exists();
        abort_unless($exists, 404, 'کلاس یافت نشد.');

        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'grade_level_id' => ['required', 'integer'],
            'capacity' => ['nullable', 'integer', 'min:1', 'max:1000'],
        ]);

        $gradeAllowed = DB::table('school_grade_levels')
            ->where('school_id', $schoolId)
            ->where('grade_level_id', $data['grade_level_id'])
            ->where('enabled', true)
            ->exists();

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

        $nameConflict = DB::table('classrooms')
            ->where('school_id', $schoolId)
            ->where('name', $data['name'])
            ->where('id', '!=', $id)
            ->exists();

        if ($nameConflict) {
            return back()->withErrors(['name' => 'کلاسی با این نام قبلا ثبت شده است.'])->withInput();
        }

        DB::table('classrooms')->where('id', $id)->update([
            'grade_level_id' => $data['grade_level_id'],
            'name' => $data['name'],
            'capacity' => $data['capacity'] ?? null,
            'updated_at' => now(),
        ]);

        return redirect()->route('school.classes')->with('success', 'اطلاعات کلاس بروز شد.');
    }

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

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

        $classroom = DB::table('classrooms')->where('id', $id)->where('school_id', $schoolId)->first();
        abort_unless($classroom, 404, 'کلاس یافت نشد.');

        DB::transaction(function () use ($id): void {
            DB::table('class_students')->where('classroom_id', $id)->delete();
            DB::table('class_teachers')->where('classroom_id', $id)->delete();
            DB::table('classrooms')->where('id', $id)->delete();
        });

        return redirect()->route('school.classes')->with('success', 'کلاس حذف شد.');
    }

    private function gradeOptions(int $schoolId): array
    {
        return DB::table('school_grade_levels')
            ->join('grade_levels', 'grade_levels.id', '=', 'school_grade_levels.grade_level_id')
            ->where('school_grade_levels.school_id', $schoolId)
            ->where('school_grade_levels.enabled', true)
            ->orderBy('grade_levels.number')
            ->get(['grade_levels.id', 'grade_levels.name_fa'])
            ->map(fn ($grade): array => ['value' => $grade->id, 'label' => $grade->name_fa])
            ->values()
            ->all();
    }
}
