<?php

namespace App\Http\Controllers;

use App\Models\SchoolClass;
use App\Models\Student;
use App\Models\TransportRoute;
use App\Models\TransportStop;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

class TransportAssignmentController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:transport.view', only: ['index']),
            new Middleware('can:transport.update', only: ['store']),
        ];
    }

    public function index(Request $request): View
    {
        $classId = $request->integer('class_id') ?: null;

        $students = Student::active()
            ->when($classId, fn ($q) => $q->where('class_id', $classId))
            ->with(['transportRoute', 'transportStop', 'schoolClass'])
            ->orderBy('name')->get();

        return view('transport.assign.index', [
            'students' => $students,
            'classes' => SchoolClass::active()->orderBy('level')->get(),
            'routes' => TransportRoute::active()->with('stops')->orderBy('name')->get(),
            'classId' => $classId,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'student_id' => ['required', 'exists:students,id'],
            'transport_route_id' => ['nullable', 'exists:transport_routes,id'],
            'transport_stop_id' => ['nullable', 'exists:transport_stops,id'],
        ]);

        Student::where('id', $data['student_id'])->update([
            'transport_route_id' => $data['transport_route_id'] ?: null,
            'transport_stop_id' => $data['transport_stop_id'] ?: null,
        ]);

        return back()->with('success', 'Transport assignment updated.');
    }
}
