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

        $teachers = $schoolId
            ? DB::table('teachers')
                ->leftJoin('class_teachers', 'class_teachers.teacher_id', '=', 'teachers.id')
                ->leftJoin('classrooms', 'classrooms.id', '=', 'class_teachers.classroom_id')
                ->leftJoin('subjects', 'subjects.id', '=', 'class_teachers.subject_id')
                ->where('teachers.school_id', $schoolId)
                ->groupBy('teachers.id', 'teachers.teacher_code', 'teachers.first_name', 'teachers.last_name', 'teachers.specialty', 'teachers.mobile', 'teachers.email', 'teachers.status')
                ->select([
                    'teachers.id',
                    'teachers.teacher_code',
                    'teachers.first_name',
                    'teachers.last_name',
                    'teachers.specialty',
                    'teachers.mobile',
                    'teachers.email',
                    'teachers.status',
                    DB::raw("GROUP_CONCAT(DISTINCT classrooms.name ORDER BY classrooms.name SEPARATOR '، ') as classes"),
                    DB::raw("GROUP_CONCAT(DISTINCT subjects.name ORDER BY subjects.name SEPARATOR '، ') as subjects"),
                ])
                ->orderBy('teachers.last_name')
                ->limit(50)
                ->get()
            : collect();

        return Inertia::render('School/Teachers', [
            'teachers' => $teachers->map(fn ($teacher): array => [
                'id' => $teacher->id,
                'fullName' => trim($teacher->first_name.' '.$teacher->last_name),
                'firstName' => $teacher->first_name,
                'lastName' => $teacher->last_name,
                'teacherCode' => $teacher->teacher_code ?? '',
                'specialty' => $teacher->specialty ?? '',
                'mobile' => $teacher->mobile ?? '',
                'email' => $teacher->email ?? '',
                'classes' => $teacher->classes ?: '—',
                'status' => $teacher->status === 'active' ? 'فعال' : 'غیرفعال',
            ])->values(),
        ]);
    }

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

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

        $data = $request->validate([
            'teacher_code' => ['nullable', 'string', 'max:80'],
            'first_name' => ['required', 'string', 'max:120'],
            'last_name' => ['required', 'string', 'max:120'],
            'mobile' => ['nullable', 'regex:/^09\d{9}$/'],
            'email' => ['nullable', 'email', 'max:190'],
            'specialty' => ['nullable', 'string', 'max:190'],
        ]);

        if (! empty($data['teacher_code'])) {
            $exists = DB::table('teachers')
                ->where('school_id', $schoolId)
                ->where('teacher_code', $data['teacher_code'])
                ->exists();

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

        DB::table('teachers')->insert([
            'school_id' => $schoolId,
            'teacher_code' => $data['teacher_code'] ?? null,
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'mobile' => $data['mobile'] ?? null,
            'email' => $data['email'] ?? null,
            'specialty' => $data['specialty'] ?? null,
            'status' => 'active',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return redirect()->route('school.teachers')->with('success', 'معلم ثبت شد.');
    }

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

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

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

        $data = $request->validate([
            'teacher_code' => ['nullable', 'string', 'max:80'],
            'first_name' => ['required', 'string', 'max:120'],
            'last_name' => ['required', 'string', 'max:120'],
            'mobile' => ['nullable', 'regex:/^09\d{9}$/'],
            'email' => ['nullable', 'email', 'max:190'],
            'specialty' => ['nullable', 'string', 'max:190'],
        ]);

        if (! empty($data['teacher_code'])) {
            $codeConflict = DB::table('teachers')
                ->where('school_id', $schoolId)
                ->where('teacher_code', $data['teacher_code'])
                ->where('id', '!=', $id)
                ->exists();

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

        DB::table('teachers')->where('id', $id)->update([
            'teacher_code' => $data['teacher_code'] ?? null,
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'mobile' => $data['mobile'] ?? null,
            'email' => $data['email'] ?? null,
            'specialty' => $data['specialty'] ?? null,
            'updated_at' => now(),
        ]);

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

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

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

        $teacher = DB::table('teachers')->where('id', $id)->where('school_id', $schoolId)->first();
        abort_unless($teacher, 404, 'معلم یافت نشد.');

        DB::table('class_teachers')->where('teacher_id', $id)->delete();
        DB::table('teachers')->where('id', $id)->delete();

        return redirect()->route('school.teachers')->with('success', 'معلم حذف شد.');
    }
}
