<?php

namespace App\Http\Controllers;

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;

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

    public function store(Request $request, TransportRoute $transportRoute): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:150'],
            'fare' => ['nullable', 'numeric', 'min:0'],
            'pickup_time' => ['nullable', 'date_format:H:i'],
        ]);

        $transportRoute->stops()->create($data + ['branch_id' => $transportRoute->branch_id, 'fare' => $data['fare'] ?? 0]);

        return back()->with('success', 'Stop added.');
    }

    public function destroy(TransportStop $stop): RedirectResponse
    {
        $stop->delete();

        return back()->with('success', 'Stop removed.');
    }
}
