<?php

namespace App\Http\Controllers\Teacher;

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

class DashboardController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);
        $teacherId = $request->user()
            ? DB::table('teachers')->where('user_id', $request->user()->id)->value('id')
            : null;

        $classes = $schoolId && $teacherId
            ? DB::table('schedules')
                ->join('classrooms', 'classrooms.id', '=', 'schedules.classroom_id')
                ->join('subjects', 'subjects.id', '=', 'schedules.subject_id')
                ->where('schedules.school_id', $schoolId)
                ->where('schedules.teacher_id', $teacherId)
                ->orderBy('schedules.day_of_week')
                ->orderBy('schedules.starts_at')
                ->limit(20)
                ->get(['schedules.starts_at', 'classrooms.name as classroom_name', 'subjects.name as subject_name'])
            : collect();

        return Inertia::render('Teacher/MyClasses', [
            'classes' => $classes->map(fn ($item): array => [
                'time' => substr((string) $item->starts_at, 0, 5),
                'classroom' => $item->classroom_name,
                'subject' => $item->subject_name,
                'action' => 'مشاهده کلاس',
            ])->values(),
        ]);
    }
}
