<?php

namespace App\Services;

use App\Http\Integrations\Imake\MoorlePay;
use App\Http\Integrations\Imake\Requests\MoorlePay\CheckTransactionStatus;
use App\Http\Integrations\Imake\Requests\MoorlePay\VerifyOTP;
use App\Http\Integrations\Imake\Requests\MoorlePay\MakePayment;
use App\Http\Integrations\Imake\Requests\MoorlePay\InitiatePayment;

class MoorleService
{
    protected $moorleAPI;
    /**
     * Create a new class instance.
     */
    public function __construct(MoorlePay $moorleAPI)
    {
        $this->moorleAPI = $moorleAPI;
    }

    public function initiatePayment($amount, $paymentNumber, $network, $transactionId)
    {
        $request = new InitiatePayment($amount, $paymentNumber, '', $this->getNetwork($network), $transactionId);
        $response = $this->moorleAPI->send($request);

        if ($response->ok() && $response->json()['status'] == 1) {
            return $response->json();
        } else {
            return null;
        }
    }

    public function verifyOTP($amount, $paymentNumber, $otp, $network, $transactionId)
    {
        $request = new VerifyOTP($amount, $paymentNumber, $otp, $this->getNetwork($network), $transactionId);
        $response = $this->moorleAPI->send($request);

        if ($response->ok() && $response->json()['status'] == 1) {
            return $response->json();
        } else {
            return null;
        }
    }

    public function sendPaymentPrompt($amount, $paymentNumber, $otp, $network, $transactionId)
    {
        $request = new MakePayment($amount, $paymentNumber, $otp, $this->getNetwork($network), $transactionId);
        $response = $this->moorleAPI->send($request);

        if ($response->ok() && $response->json()['status'] == 1) {
            return $response->json();
        } else {
            return null;
        }
    }

    public function checkTransactionStatus($transactionId)
    {
        $request = new CheckTransactionStatus($transactionId);
        $response = $this->moorleAPI->send($request);

        if ($response->ok()) {
            $status = $response->json()['data']['txstatus'];
            $isSuccess = $status == 1;
            return $isSuccess;
        } else {
            return null;
        }
    }

    private function getNetwork($network)
    {
        return match ($network) {
            'MTN' => '13',
            'TELECEL' => '6',
            'AIRTELTIGO' => '7',
        };
    }
}