<?php

namespace App\Repositories\Shop;

use App\Models\Shop\InvoicePayment;
use Bnb\PayboxGateway\Requests\Paybox\AuthorizationWithCapture;
use Bnb\PayboxGateway\Requests\PayboxDirect\Capture;
use Bnb\PayboxGateway\Responses\Exceptions\InvalidSignature;
use Bnb\PayboxGateway\Responses\Paybox\Verify;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;

class Paybox
{
    public static function makeAuthorizationRequest($order, $customer_email = 'test@example.com')
    {
        $authorizationRequest = App::make(AuthorizationWithCapture::class);
        $invoiceId = $order->invoice->id;

        return $authorizationRequest->setAmount($order->total_shipped)->setCustomerEmail($customer_email)
            ->setPaymentNumber($invoiceId)->send('paybox.send');
    }

    public static function verifyPayment($invoiceId)
    {
        $invoice = Invoices::get($invoiceId);
        $payboxVerify = App::make(Verify::class);
        try {
            $success = $payboxVerify->isSuccess($invoice->total_shipped);
            if ($success) {
                // process order here after making sure it was real payment
            }
            echo 'OK';
        } catch (InvalidSignature $e) {
            Log::alert('Invalid payment signature detected');
        }
    }

    public static function getPreviousAuthorizedRequest($request)
    {
        $payment = InvoicePayment::where('number', $request->input('order_number'))->firstOrFail();
        $captureRequest = App::make(Capture::class);
        $response = $captureRequest->setAmount($payment->amount)
            ->setPayboxCallNumber($payment->call_number)
            ->setPayboxTransactionNumber($payment->transaction_number)
            ->setDayRequestNumber(2)
            ->send();

        if ($response->isSuccess()) {
            // process order here
        }
    }
}
