<?php

namespace App\Http\Controllers\School;

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

class ScheduleController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $schedules = $schoolId
            ? DB::table('schedules')
                ->join('classrooms', 'classrooms.id', '=', 'schedules.classroom_id')
                ->join('subjects', 'subjects.id', '=', 'schedules.subject_id')
                ->join('teachers', 'teachers.id', '=', 'schedules.teacher_id')
                ->where('schedules.school_id', $schoolId)
                ->select([
                    'schedules.day_of_week',
                    'schedules.starts_at',
                    'schedules.ends_at',
                    'schedules.room',
                    'classrooms.name as classroom_name',
                    'subjects.name as subject_name',
                    'teachers.first_name',
                    'teachers.last_name',
                ])
                ->orderBy('schedules.day_of_week')
                ->orderBy('schedules.starts_at')
                ->limit(80)
                ->get()
            : collect();

        return Inertia::render('Schedule/ScheduleBuilder', [
            'schedules' => $schedules->map(fn ($schedule): array => [
                'day' => $this->dayName((int) $schedule->day_of_week),
                'time' => substr((string) $schedule->starts_at, 0, 5).' - '.substr((string) $schedule->ends_at, 0, 5),
                'classroom' => $schedule->classroom_name,
                'subject' => $schedule->subject_name,
                'teacher' => trim($schedule->first_name.' '.$schedule->last_name),
                'room' => $schedule->room ?: '—',
            ])->values(),
        ]);
    }

    private function dayName(int $day): string
    {
        return [
            0 => 'شنبه',
            1 => 'یکشنبه',
            2 => 'دوشنبه',
            3 => 'سه‌شنبه',
            4 => 'چهارشنبه',
            5 => 'پنجشنبه',
            6 => 'جمعه',
        ][$day] ?? '—';
    }
}
