<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\PaymentGateway;
use App\Services\PaymentService;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    public function show(Booking $booking)
    {
        $this->authorize('view', $booking);
        $gateways = PaymentGateway::where('enabled', true)->get();

        return view('payments.pay', compact('booking', 'gateways'));
    }

    public function process(Booking $booking, Request $request, PaymentService $payments)
    {
        $this->authorize('view', $booking);
        $request->validate([
            'gateway_id' => ['required', 'exists:payment_gateways,id'],
        ]);

        $gateway = PaymentGateway::findOrFail($request->input('gateway_id'));

        $payment = $payments->initiate($booking, $gateway);

        // Redirect to gateway if URL available, otherwise show client-side confirmation (e.g., Stripe client_secret)
        $redirect = $payment->payload['approval_url'] ?? $payment->payload['authorization_url'] ?? null;
        if ($redirect) {
            return redirect()->away($redirect);
        }

        return view('payments.confirm', compact('booking', 'payment'));

    }
}
