<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Services\AnalyticsTracker;
use App\Services\GenericPaymentGatewayService;
use Illuminate\Http\Request;
use RuntimeException;

class OnlinePaymentController extends Controller
{
    public function show(Request $request, Order $order, GenericPaymentGatewayService $gateway, AnalyticsTracker $analytics)
    {
        abort_unless(! $order->user_id || $request->user()?->id === $order->user_id || $request->user()?->isAdmin(), 403);

        try {
            $attempt = $gateway->initiate($order);
        } catch (RuntimeException $exception) {
            return redirect()->route('orders.show', $order)->withErrors(['payment' => $exception->getMessage()]);
        }

        $analytics->track($request, 'payment_started', 'order', $order->id, [
            'gateway' => 'online_gateway',
            'attempt_id' => $attempt->id,
            'amount_minor' => $attempt->amount_minor,
        ]);

        $checkoutUrl = data_get($attempt->response_payload, 'checkout_url', data_get($attempt->response_payload, 'redirect_url'));

        if ($checkoutUrl) {
            return redirect()->away($checkoutUrl);
        }

        return view('payments.online', [
            'order' => $order->load('items'),
            'attempt' => $attempt,
        ]);
    }
}
