<?php

declare(strict_types=1);

namespace App\Http\Controllers\Payment;

use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Models\User;
use App\Support\ApiResponse;
use App\Services\PaymentService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PaymentVerifyController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request, Payment $payment)
    {
        $query = '';
        try {
            DB::beginTransaction();
            $query = http_build_query($request->all());

            $paymentService = new PaymentService;
            $user = User::find($payment->user_id);

            if (! $user) {
                return ApiResponse::response(message: 'شما وارد سایت نشده اید!', status: 420);
            }

            $paymentService->verify($payment, $request->gateway, $payment->transaction_id, $user);
            DB::commit();

            return redirect('https://vianasystem.com/payment/' . $payment->id . '?' . $query);
        } catch (Exception $exception) {
            return redirect('https://vianasystem.com/payment/' . $payment->id . '?' . $query);
        }
    }
}
