<?php

use App\Http\Controllers\ConfigurationController;
use App\Models\Transaction;
use App\Models\SMSActivity;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;


if (!function_exists('numberFromInput')) {
    function numberFromInput($inputName = 'total_number')
    {
        $phoneNumbersInput = str_replace(' ', '', request()->input($inputName));
        $phoneNumbersArray = explode(',', $phoneNumbersInput);

        return $phoneNumbersArray;

        //        $numbers = collect(request()->input($inputName))->pluck('text')->toArray();
        //        return $numbers;
    }
}

if (!function_exists('getSender')) {
    function getSender($senderList, $type, $operatorId = null)
    {
        if ($type == 1) {
            $senders = $senderList->where('sender_id_type', 1)->keyBy('operator_id');
            if (isset($senders[$operatorId])) {
                return $senders[$operatorId];
            }
            return null;
        }

        if ($type == 2) {
            $sender = $senderList->where('sender_id_type', 2)->first();
            if ($sender) {
                return $sender;
            }
            return null;
        }

        return null;
    }
}

if (!function_exists('sederToRequestArr')) {
    function sederToRequestArr($senderApi, $messageData)
    {
        $arrData = [
            "username" => $senderApi->username,
            "password" => $senderApi->password,
            "billMsisdn" => $senderApi->billMsisdn,
            "apiKey" => $senderApi->apiKey,
            "cli" => $senderApi->cli,
            "transactionType" => $messageData->transactionType,
            "messageType" => $messageData->messageType,
            "campaignId" => $senderApi->campaignId,
            "isLongSMS" => false,
        ];

        if ($messageData->transactionType == 'P') {
            $arrData['isLongSMS'] = true;
        }

        return $arrData;
    }
}

if (!function_exists('sentSms')) {
    function sentSms($messageData, $senderApi)
    {
        try {

            $helper = new \App\Helpers\TraitSupport();
            $defaultError = $helper->defaultSmsError;

            if (!is_array($messageData->number) || count($messageData->number) == 0) {
                insertFailLog($messageData->number_id, 'Number not passed, Empty Array');

                $defaultError['serverResponseCode'] = '5001';
                $defaultError['serverTxnId'] = '5000-receiver-error';
                $defaultError['serverResponseMessage'] = 'Number Must be Array and at least one number';
                return (object)$defaultError;
            }

            $url = config('sms.apiUrl');

            $arrayData = sederToRequestArr($senderApi, $messageData);
            $arrayData["message"] = $messageData->body;
            $arrayData["msisdnList"] = $messageData->number;

            $dataUpdated = json_encode($arrayData);

            $response = Http::withOptions(['verify' => false])
                ->withHeaders(['Content-Type' => 'application/json',])
                ->withBody($dataUpdated, 'application/json')
                ->post($url);

            $data = json_decode($response->getBody()->getContents());

            DB::table('req_res_log')->insert([
                'url' => $url,
                'req_body' => $dataUpdated,
                'res_body' => json_encode($data),
            ]);

            return $data;
        } catch (Exception $exception) {
            insertFailLog($messageData->number_id, $exception->getMessage());

            DB::table('req_res_log')->insert([
                'url' => json_encode($messageData),
                'req_body' => $exception->getCode(),
                'res_body' => $exception->getMessage(),
            ]);
            return (object)$defaultError;
        }
    }
}

if (!function_exists('sederToDeleveryArr')) {
    function sederToDeleveryArr($senderApi, $messageData)
    {
        $number = @$messageData->numbers->phone;
        $arrData = [
            "username" => $senderApi->username,
            "password" => $senderApi->password,
            "billMsisdn" => $senderApi->billMsisdn,
            "apiKey" => $senderApi->apiKey,
            "cli" => $senderApi->cli,
            "msisdnList" => [$number],
            "serverReference" => $messageData->serverTxnId,
        ];

        return $arrData;
    }
}

if (!function_exists('checkDelivery')) {
    function checkDelivery($messageData, $senderApi)
    {
        try {

            $helper = new \App\Helpers\TraitSupport();
            $defaultError = $helper->defaultSmsError;


            $url = config('sms.apiDelivery');

            $arrayData = sederToDeleveryArr($senderApi, $messageData);
            $dataUpdated = json_encode($arrayData);


            $response = Http::withOptions(['verify' => false])
                ->withHeaders(['Content-Type' => 'application/json',])
                ->withBody($dataUpdated, 'application/json')
                ->post($url);

            $data = json_decode($response->getBody()->getContents());

            return $data;
        } catch (Exception $exception) {
            return (object)$defaultError;
        }
    }
}

if (!function_exists('insertFailLog')) {
    function insertFailLog($id, $message, $data = null, $header = null)
    {
        DB::table('fail_logs')->insert([
            'failed_id' => $id,
            'time' => date('Y-m-d H:m:s'),
            'message' => $message,
            'data' => $data,
            'header' => $header,
        ]);
    }
}

if (!function_exists('balanceCheck')) {
    function balanceCheck($smsCount = 1, $rate = 0, $totalNumber = 1, $user_id = 0, $balanceObject = null)
    {
        $balanceObj = $balanceObject ? $balanceObject :  showBalance($user_id);
        $balance = $balanceObj->balance;
        $cost = ($rate * $smsCount) * $totalNumber;
        $currAmount = $balance - $cost;

        return (object)[
            'balance' => $balance,
            'crrAmount' => $currAmount,
            'allowNegative' => $balanceObj->allowNegative,
            'negativeLimit' => $balanceObj->negativeLimit
        ];
    }
}

if (!function_exists('smsPart')) {
    function smsPart($characterCount, $content_type)
    {
        $config = new ConfigurationController();
        $data = $config->getGeneralData(['characters'])['characters'];

        $siCount = $content_type == 3 ? $data['unicode']['count'] : $data['english']['count'];
        $siLimit = $content_type == 3 ? $data['unicode']['limit'] : $data['english']['limit'];
        $smsPart = ceil($characterCount / $siCount);

        if ($characterCount > $siLimit) {
            return (object)['status' => false, 'part' => $smsPart, 'message' => "Maximum $siLimit Character Acceptable"];
        }

        return (object)['status' => true, 'part' => $smsPart, 'message' => "Valid Message"];
    }
}
