<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Exception;

class BkashService
{
    protected string $baseUrl;

    public function __construct()
    {
        $this->baseUrl = rtrim(
            config('bkash.base_url'),
            '/'
        );
    }

    /**
     * Grant Token
     */
    public function grantToken(): array
    {
        $response = Http::timeout(30)
            ->withHeaders([
                'username' => config('bkash.username'),
                'password' => config('bkash.password'),
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ])
            ->post(
                $this->baseUrl . '/tokenized/checkout/token/grant',
                [
                    'app_key' => config('bkash.app_key'),
                    'app_secret' => config('bkash.app_secret'),
                ]
            );

        $data = $response->json();

        if (!$response->successful() || !isset($data['id_token'])) {
            throw new Exception(
                'bKash Token Error: ' . $response->body()
            );
        }

        return $data;
    }


    /**
     * Create Payment
     */
    public function createPayment(
        float $amount,
        string $invoice
    ): array {

        $token = $this->grantToken();

        $response = Http::timeout(30)
            ->withHeaders([
                'Authorization' => $token['id_token'],
                'X-APP-Key' => config('bkash.app_key'),
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ])
            ->post(
                $this->baseUrl . '/tokenized/checkout/create',
                [
                    'mode' => '0011',

                    'payerReference' => '',

                    'callbackURL' => route(
                        'bkash.callback'
                    ),

                    'amount' => number_format(
                        $amount,
                        2,
                        '.',
                        ''
                    ),

                    'currency' => 'BDT',

                    'intent' => 'sale',

                    'merchantInvoiceNumber' => $invoice,
                ]
            );

        $data = $response->json();

        if (
            !$response->successful()
            || !isset($data['paymentID'])
        ) {
            throw new Exception(
                'bKash Create Payment Error: '
                . $response->body()
            );
        }

        return $data;
    }


    /**
     * Execute Payment
     */
    public function executePayment(
        string $paymentId
    ): array {

        $token = $this->grantToken();

        $response = Http::timeout(30)
            ->withHeaders([
                'Authorization' => $token['id_token'],
                'X-APP-Key' => config('bkash.app_key'),
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ])
            ->post(
                $this->baseUrl . '/tokenized/checkout/execute',
                [
                    'paymentID' => $paymentId,
                ]
            );

        return $response->json();
    }
}