<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckOrderPaid
{
    public function handle(Request $request, Closure $next): Response
    {
        $order = $request->route('order');

        if (! $order || $order->user_id !== $request->user()->id) {
            abort(403, 'Unauthorized access.');
        }

        if ($order->status !== 'paid') {
            return redirect()->route('orders.show', $order)->with('error', 'Payment has not been completed yet.');
        }

        return $next($request);
    }
}
