<?php

namespace App\Http\Controllers;

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

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();

                //payment process start
                $ref = $data->transactionReference;
                $chars = str_split($ref);
                $tReference = $chars[0] . $chars[1] . $chars[2] . $chars[3] . $chars[4] . $chars[5] . $chars[6];

                if ($tReference == 'manager') {
                    $manager = Reseller::where('manager_unique_code', $data->transactionReference)->first();
                    $user_id = User::onlinePaymentUser('Bkash-Webhook')->id;

                    DB::beginTransaction();
                    try {
                        (new ResellerRechargeController)->resellerBkashWebhookRecharge(
                            $manager->id,
                            $data->amount,
                            'Recharge from Bkash-Webhook',
                            $user_id,
                            $data->trxID
                        );
                        DB::commit();
                    } catch (\Exception $e) {
                        DB::rollBack();
                        Log::error($e->getMessage());
                    }
                } else {
                    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',
        ]);
    }
}
