<?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;
        $sectionId = $request->integer('section_id') ?: null;
        $search = trim((string) $request->input('search', ''));

        $students = Student::active()
            ->when($classId, fn ($q) => $q->where('class_id', $classId))
            ->when($sectionId, fn ($q) => $q->where('section_id', $sectionId))
            ->when($search, function ($q, $term) {
                $like = '%'.$term.'%';
                $q->where(fn ($w) => $w->where('name', 'like', $like)
                    ->orWhere('admission_number', 'like', $like)
                    ->orWhereHas('family', fn ($f) => $f->where('father_name', 'like', $like)->orWhere('father_mobile', 'like', $like)));
            })
            ->with(['transportRoute', 'transportStop', 'schoolClass', 'section', 'family:id,father_name,father_mobile'])
            ->orderBy('name')->get();

        return view('transport.assign.index', [
            'students' => $students,
            'classes' => SchoolClass::active()->orderBy('level')->get(),
            'sections' => \App\Models\Section::active()->get(['id', 'class_id', 'name']),
            'routes' => TransportRoute::active()->with('stops')->orderBy('name')->get(),
            'classId' => $classId,
            'sectionId' => $sectionId,
            'search' => $search,
        ]);
    }

    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) ?: null,
            'transport_stop_id' => ($data['transport_stop_id'] ?? null) ?: null,
        ]);

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