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

        $classes = DB::table('online_classes')
            ->leftJoin('classrooms', 'classrooms.id', '=', 'online_classes.classroom_id')
            ->leftJoin('subjects', 'subjects.id', '=', 'online_classes.subject_id')
            ->leftJoin('teachers', 'teachers.id', '=', 'online_classes.teacher_id')
            ->leftJoin('users as tu', 'tu.id', '=', 'teachers.user_id')
            ->leftJoin('online_class_logs as ocl', 'ocl.online_class_id', '=', 'online_classes.id')
            ->where('online_classes.school_id', $schoolId)
            ->groupBy(
                'online_classes.id', 'online_classes.title', 'online_classes.meeting_url',
                'online_classes.starts_at', 'online_classes.ends_at',
                'classrooms.name', 'subjects.name_fa', 'tu.first_name', 'tu.last_name'
            )
            ->orderByDesc('online_classes.starts_at')
            ->limit(200)
            ->get([
                'online_classes.id',
                'online_classes.title',
                'online_classes.meeting_url',
                'online_classes.starts_at',
                'online_classes.ends_at',
                'classrooms.name as classroom_name',
                'subjects.name_fa as subject_name',
                'tu.first_name as teacher_first',
                'tu.last_name as teacher_last',
                DB::raw('COUNT(ocl.id) as join_count'),
            ]);

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

        $subjects = DB::table('subjects')
            ->where('school_id', $schoolId)
            ->orderBy('name_fa')
            ->get(['id', 'name_fa']);

        return Inertia::render('School/OnlineClasses', [
            'classes' => $classes->map(fn ($c): array => [
                'id' => (int) $c->id,
                'title' => $c->title,
                'meetingUrl' => $c->meeting_url,
                'startsAt' => $c->starts_at ? $this->jalaliDate($c->starts_at, true) : '—',
                'endsAt' => $c->ends_at ? $this->jalaliDate($c->ends_at, true) : '—',
                'classroom' => $c->classroom_name ?? '—',
                'subject' => $c->subject_name ?? '—',
                'teacher' => trim(($c->teacher_first ?? '').' '.($c->teacher_last ?? '')) ?: '—',
            'joinCount' => (int) ($c->join_count ?? 0),
            ])->values(),
            'classrooms' => $classrooms->map(fn ($c): array => [
                'id' => (int) $c->id,
                'name' => $c->name,
            ])->values(),
            'subjects' => $subjects->map(fn ($s): array => [
                'id' => (int) $s->id,
                'name' => $s->name_fa,
            ])->values(),
        ]);
    }

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

        $data = $request->validate([
            'classroom_id' => ['required', 'integer'],
            'subject_id' => ['nullable', 'integer'],
            'title' => ['required', 'string', 'max:190'],
            'meeting_url' => ['required', 'url', 'max:500'],
            'starts_at' => ['nullable', 'date_format:Y-m-d\TH:i'],
            'ends_at' => ['nullable', 'date_format:Y-m-d\TH:i'],
        ]);

        $classroom = DB::table('classrooms')
            ->where('id', $data['classroom_id'])
            ->where('school_id', $schoolId)
            ->first();
        abort_unless($classroom, 422);

        DB::table('online_classes')->insert([
            'school_id' => $schoolId,
            'classroom_id' => $data['classroom_id'],
            'subject_id' => $data['subject_id'] ?? null,
            'title' => $data['title'],
            'meeting_url' => $data['meeting_url'],
            'starts_at' => $data['starts_at'] ?? null,
            'ends_at' => $data['ends_at'] ?? null,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

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

    public function logs(Request $request, int $id): \Inertia\Response
    {
        $schoolId = $this->currentSchoolId($request);

        $class = DB::table('online_classes')->where('id', $id)->where('school_id', $schoolId)->first();
        abort_unless($class, 404);

        $logs = DB::table('online_class_logs')
            ->leftJoin('students', 'students.id', '=', 'online_class_logs.student_id')
            ->where('online_class_logs.online_class_id', $id)
            ->orderByDesc('online_class_logs.joined_at')
            ->get([
                'online_class_logs.id',
                'students.first_name',
                'students.last_name',
                'students.student_code',
                'online_class_logs.ip_address',
                'online_class_logs.joined_at',
            ]);

        return \Inertia\Inertia::render('School/OnlineClassLogs', [
            'classTitle' => $class->title,
            'logs' => $logs->map(fn ($log): array => [
                'id' => (int) $log->id,
                'student' => trim(($log->first_name ?? '').' '.($log->last_name ?? '')) ?: '—',
                'studentCode' => $log->student_code ?? '—',
                'ip' => $log->ip_address ?? '—',
                'joinedAt' => $this->jalaliDate($log->joined_at, true),
            ])->values(),
        ]);
    }

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

        $class = DB::table('online_classes')->where('id', $id)->where('school_id', $schoolId)->first();
        abort_unless($class, 404);

        DB::table('online_classes')->where('id', $id)->delete();

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