<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Services\PaymentService;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Http\Request;

class GatewayController extends Controller
{
    /**
     * @throws BindingResolutionException
     */
    public function getToken($gateway)
    {
        $token = PaymentService::setGateway($gateway)->getToken();
        return response()->json(['token' => $token]);
    }

    public function safeRedirect(Request $request)
    {
        $url = $request->query('url');

        if (!$url || !filter_var($url, FILTER_VALIDATE_URL)) {
            abort(400, 'Invalid URL.');
        }

        $parsed = parse_url($url);
        if (!$parsed || !isset($parsed['host'])) {
            abort(400, 'Invalid redirect URL.');
        }

        $allowedHosts = [
            'www.paypal.com',
            'sandbox.paypal.com',
            'www.sandbox.paypal.com',
            'example.com',
        ];

        if (!in_array($parsed['host'], $allowedHosts)) {
            abort(403, 'This domain is not allowed.');
        }

        return redirect()->away($url);
    }

    /**
     * @throws BindingResolutionException
     */
    public function ipn($gateway): void
    {
        PaymentService::setGateway(strtolower($gateway))->processIPN();
    }

}
