<?php

namespace App\Http\Controllers;

use App\Models\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use App\Jobs\ClientSyncJobForSingle;
use App\Models\BkashWebhook;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class BkashWebhookController extends Controller
{

    public function handleWebhook(Request $request)
    {
        $payload = json_decode($request->getContent(), true);

        $messageType = $payload['Type'];

            if ($messageType == "SubscriptionConfirmation") {

                $subscribeURL = $payload['SubscribeURL'];
                //subscribe
                $bkashWebhook = new BkashWebhook();
                $bkashWebhook->payload = $request->getContent();
                $bkashWebhook->trxid = Str::random(10);
                $bkashWebhook->save();

                $url = curl_init($subscribeURL);
                curl_exec($url);
            } else if ($messageType == "Notification") {
                $notificationData = $payload['Message'];
                $data = json_decode($notificationData);

                if (!BkashWebhook::where('trxid', $data->trxID)->first()) {
                    $bkashWebhook = new BkashWebhook();
                    $bkashWebhook->payload = $request->getContent();
                    $bkashWebhook->trxid = $data->trxID;
                    $bkashWebhook->save();
                }

                if (checkSettings('prepaid-bill-by-client-code') == 'enable'){

                    $client = Client::where('customer_code', $data->transactionReference)->first();

                } else if (checkSettings('prepaid-bill-by-client-username') == 'enable'){

                    $client = Client::where('userid', $data->transactionReference)->first();
                } else{

                    $client = Client::where('id', $data->transactionReference)->first();
                }

                DB::beginTransaction();
                try {
                    (new PaymentController)->bkashWebhookPaymentProcess(
                        $data->amount,
                        $client->id,
                        $data->trxID,
                        $data->debitMSISDN,
                        $data->trxID,
                        $data->dateTime,
                    );
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    Log::error($e->getMessage());
                }


                if (checkAPI()) {
                    ClientSyncJobForSingle::dispatch($client->id);
                }
            }

    }

    public function bkashWebhookReport()
    {
        $bkashWebhookReport = BkashWebhook::orderBy('id', 'DESC')->get();

        return view('bkashWebhook.bkashWebhookReport',[
            'bkashWebhookReport' => $bkashWebhookReport,
            'page_title' => 'Bkash Webhook Report',
        ]);
    }
}
