<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
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 Yajra\DataTables\Facades\DataTables;
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 = '';
                if (count($chars) > 6) {
                    $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()
    {
        return view('bkashWebhook.bkashWebhookReport', [
            'page_title' => 'Bkash Webhook Report',
        ]);
    }

    public function bkashWebhookReportDatatable(Request $request)
    {
        $query = BkashWebhook::select('id', 'payload', 'created_at')
            ->orderBy('id', 'desc');

        return DataTables::of($query)

            ->filter(function ($query) use ($request) {
                // Date Range Filter
                if ($request->filled('from_date') && $request->filled('to_date')) {
                    $query->whereBetween('created_at', [
                        $request->from_date . ' 00:00:00',
                        $request->to_date   . ' 23:59:59'
                    ]);
                }

                // Global Search
                if ($search = $request->get('search')['value'] ?? null) {
                    $query->where(function ($q) use ($search) {
                        $q->orWhere('payload', 'like', "%{$search}%")
                            ->orWhere('id', 'like', "%{$search}%");
                    });
                }
            })

            ->addColumn('payment_number', function ($row) {
                $info  = json_decode($row->payload);
                $data  = json_decode($info->Message ?? '{}');
                return $data->debitMSISDN ?? '';
            })

            ->addColumn('amount', function ($row) {
                $info  = json_decode($row->payload);
                $data  = json_decode($info->Message ?? '{}');
                return $data->amount ?? '';
            })

            ->addColumn('trxid', function ($row) {
                $info  = json_decode($row->payload);
                $data  = json_decode($info->Message ?? '{}');
                return $data->trxID ?? '';
            })

            ->addColumn('reference', function ($row) {
                $info  = json_decode($row->payload);
                $data  = json_decode($info->Message ?? '{}');
                return $data->transactionReference ?? '';
            })

            ->addColumn('date_time', function ($row) {
                $info  = json_decode($row->payload);
                $data  = json_decode($info->Message ?? '{}');

                return isset($data->dateTime)
                    ? Carbon::parse($data->dateTime)->format('Y-m-d H:i:s')
                    : '';
            })

            ->setRowClass(function ($row) {
                $info  = json_decode($row->payload);
                $data  = json_decode($info->Message ?? '{}');

                return isset($data->transactionReference) ? '' : 'bg-danger';
            })

            ->make(true);
    }
}
