<?php

namespace App\Http\Controllers\Student;

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

class OnlineClassController extends Controller
{
    public function join(Request $request, int $id): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        $userId = $request->user()?->id;

        $class = DB::table('online_classes')
            ->where('id', $id)
            ->where('school_id', $schoolId)
            ->first(['id', 'meeting_url', 'classroom_id']);

        abort_unless($class, 404);

        $studentId = $userId
            ? DB::table('students')->where('school_id', $schoolId)->where('user_id', $userId)->value('id')
            : null;

        // verify student belongs to this classroom
        if ($studentId) {
            $enrolled = DB::table('class_students')
                ->where('classroom_id', $class->classroom_id)
                ->where('student_id', $studentId)
                ->where('status', 'active')
                ->exists();

            abort_unless($enrolled, 403);
        }

        DB::table('online_class_logs')->insert([
            'school_id' => $schoolId,
            'online_class_id' => $id,
            'student_id' => $studentId,
            'user_id' => $userId,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'joined_at' => now(),
        ]);

        if ($studentId) {
            $onlineClass = DB::table('online_classes')->where('id', $id)->first();
            $today = now()->toDateString();
            $todayJalali = jalaliDate($today);

            $sessionId = DB::table('attendance_sessions')
                ->where('school_id', $schoolId)
                ->where('classroom_id', $class->classroom_id)
                ->where('date', $today)
                ->whereNotNull('online_class_id')
                ->where('online_class_id', $id)
                ->value('id');

            if (! $sessionId) {
                $teacherId = $onlineClass->teacher_id ?? null;
                $subjectId = $onlineClass->subject_id ?? null;

                $sessionId = DB::table('attendance_sessions')->insertGetId([
                    'school_id' => $schoolId,
                    'classroom_id' => $class->classroom_id,
                    'subject_id' => $subjectId,
                    'teacher_id' => $teacherId,
                    'online_class_id' => $id,
                    'date' => $today,
                    'date_jalali' => $todayJalali,
                    'type' => 'online',
                    'status' => 'draft',
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            DB::table('attendance_records')->updateOrInsert(
                [
                    'attendance_session_id' => $sessionId,
                    'student_id' => $studentId,
                ],
                [
                    'school_id' => $schoolId,
                    'status' => 'present',
                    'created_at' => now(),
                    'updated_at' => now(),
                ]
            );
        }

        return redirect()->away($class->meeting_url);
    }
}
