<?php


namespace NioModules\Paypal\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Transaction;
use Illuminate\Http\Request;
use NioModules\Paypal\Exceptions\PaypalFailedException;
use NioModules\Paypal\Services\TransactionConfirmationService;

class TransactionConfirmationController extends Controller
{
    private $transactionConfirmationService;

    public function __construct(TransactionConfirmationService $transactionConfirmationService)
    {
        $this->transactionConfirmationService = $transactionConfirmationService;
    }

    public function cancelPaypal()
    {
        $request = request();
        $transaction = $this->transactionConfirmationService->cancelPaypal($request->token);

        return redirect()->route('deposit.complete.online', [
            'status' => 'cancel',
            'tnx' => $transaction->tnx,
        ]);
    }

    public function returnPaypal()
    {
        $request = request();
        try {
            $transaction = $this->transactionConfirmationService->returnPaypal($request);

            if ($transaction instanceof Transaction) {
                return redirect()->route('deposit.complete.online', [
                    'status' => 'success',
                    'tnx' => $transaction->tnx,
                ]);
            }
        } catch (PaypalFailedException $e) {
            $transaction = $e->getData();
            return redirect()->route('deposit.complete.online', [
                'status' => 'failed',
                'tnx' => $transaction->tnx,
            ]);
        }

        return redirect()->route('dashboard');
    }

    public function makePayment()
    {
        $request = request();
        return $this->transactionConfirmationService->makePayment($request->get("id"));
    }
}
