<?php

namespace App\Http\Controllers;

use App\Services\Payments\PayPalPaymentService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PayPalController extends Controller
{
    public function __construct(
        private PayPalPaymentService $paypal,
    ) {}

    public function webhook(Request $request): Response
    {
        $gateway = $this->paypal->gatewayConfig();
        if (! $gateway || ! $gateway->status) {
            return response('Gateway disabled', 400);
        }

        $payload = $request->all();
        try {
            $this->paypal->handleWebhook($payload, $gateway);
        } catch (\Throwable $e) {
            report($e);

            return response('Error', 500);
        }

        return response('OK', 200);
    }

    public function return(Request $request): RedirectResponse
    {
        $orderId = $request->query('token');
        $gateway = $this->paypal->gatewayConfig();
        if (! $orderId || ! $gateway) {
            return redirect()->route('payments.checkout')->with('error', 'Invalid PayPal return.');
        }

        try {
            $this->paypal->syncCaptureToTransaction($orderId, $gateway);
        } catch (\Throwable $e) {
            report($e);

            return redirect()->route('payments.checkout')->with('error', 'PayPal capture failed.');
        }

        return redirect()->route('payments.checkout')->with('success', 'Payment completed with PayPal.');
    }

    public function cancel(): RedirectResponse
    {
        return redirect()->route('payments.checkout')->with('error', 'PayPal payment cancelled.');
    }
}
