<?php

namespace App\Http\Controllers;

use App\Models\TransportRoute;
use App\Support\BranchContext;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

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

    public function index(): View
    {
        $routes = TransportRoute::withCount(['stops', 'students', 'vehicles'])->orderBy('name')->get();

        return view('transport.routes.index', compact('routes'));
    }

    public function create(): View
    {
        return view('transport.routes.create', ['route' => new TransportRoute()]);
    }

    public function store(Request $request, BranchContext $context): RedirectResponse
    {
        $data = $this->validateData($request);
        $data['branch_id'] = $context->currentId() ?? auth()->user()->branch_id ?? \App\Models\Branch::min('id');
        $r = TransportRoute::create($data);

        return redirect()->route('transport-routes.show', $r)->with('success', 'Route created. Add its stops below.');
    }

    public function show(TransportRoute $transportRoute): View
    {
        $transportRoute->load([
            'stops', 'vehicles',
            'students' => fn ($q) => $q->where('status', 'active')->with(['schoolClass', 'section', 'transportStop'])->orderBy('name'),
        ]);

        return view('transport.routes.show', ['route' => $transportRoute]);
    }

    public function edit(TransportRoute $transportRoute): View
    {
        return view('transport.routes.edit', ['route' => $transportRoute]);
    }

    public function update(Request $request, TransportRoute $transportRoute): RedirectResponse
    {
        $transportRoute->update($this->validateData($request));

        return redirect()->route('transport-routes.index')->with('success', 'Route updated.');
    }

    public function destroy(TransportRoute $transportRoute): RedirectResponse
    {
        if ($transportRoute->students()->exists()) {
            return back()->with('error', 'Students are assigned to this route.');
        }
        $transportRoute->delete();

        return redirect()->route('transport-routes.index')->with('success', 'Route deleted.');
    }

    private function validateData(Request $request): array
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:150'],
            'code' => ['nullable', 'string', 'max:30'],
            'fare' => ['nullable', 'numeric', 'min:0'],
            'is_active' => ['nullable', 'boolean'],
        ]);
        $data['is_active'] = (bool) ($data['is_active'] ?? false);
        $data['fare'] = $data['fare'] ?? 0;

        return $data;
    }
}
