<?php

namespace App\Models\Users;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Botmessage extends Model
{
    protected $table = 'bot_msgs';
    use HasFactory;

    const SIMPLE_MESSAGE = 1;
    const BUTTONS = 3;
    const INTERACTIVE_MESSAGE = 2;
    const PRODUCT_MESSAGE = 4;
    const TEMPLATE_SiMPLE = 5;

    public static function getMessage($bot_info_id, $is_firstmsg)
    {
        $data = Botmessage::Select('bot_msgs.id', 'bot_msgs.sequence', 'bot_msgs.language', 'bot_msgs.text', 'bot_msgs.type', 'bot_msgs.template_name', 'bot_msgs.is_template', 'bot_msgs.status')
            ->where('bot_msgs.is_firstmsg', '=', $is_firstmsg)
            ->where('bot_msgs.fk_bot_info', $bot_info_id)
            ->where('bot_msgs.status', 1)
            ->get();
        return $data;
    }
    public static function getMessagebyID($id)
    {
        $data = Botmessage::Select('bot_msgs.id', 'bot_msgs.sequence', 'bot_msgs.language', 'bot_msgs.text', 'bot_msgs.is_externalaction_before', 'bot_msgs.type')
            ->where('bot_msgs.status', 1)
            ->where('bot_msgs.id', $id)
            ->get();

        return $data;
    }
    public static function getsequence($id)
    {
        $data = Botmessage::Select('bot_msgs.id', 'bot_msgs.sequence')
            ->where('bot_msgs.status', 1)
            ->where('bot_msgs.id', $id)
            ->first();

        return $data->sequence;
    }
    public static function getis_last_sequence($id)
    {
        $data = Botmessage::Select('bot_msgs.id', 'bot_msgs.is_last_sequence')
            ->where('bot_msgs.status', 1)
            ->where('bot_msgs.id', $id)
            ->first();

        return $data->is_last_sequence;
    }

    public static function findVariable($text, $visitorID)
    {
        $text_to_be_sent = '';
        $matches = array();
        $t = preg_match_all('/@@@(.*?)\@@@/s', $text, $matches);
        if ($t) {

            foreach ($matches[1] as $match) {

                $exactValue = explode("|", $match);

                foreach ($exactValue as $exact) {
                    $botAnswer =  Botvisitorhistory::where('text', $exact)->where('visitor_id', $visitorID)->get()->first();

                    if (isset($botAnswer)) {

                        $text_to_be_sent = preg_replace('/@@@(.*?)\@@@/s', $botAnswer->value, $text);
                        return $text_to_be_sent;
                    } else {
                        //return $text_to_be_sent;
                    }
                }
            }
        } else {
            return $text;
        }
    }
    public static function findFormula($text, $visitorID, $currentValue, $botInfo)
    {
        $text_to_be_sent = '';
        $matches = array();
        $t = preg_match_all('/{{(.*?)\}}/s', $text, $matches);


        if ($t) {

            $text_to_be_sent = $text;
            foreach ($matches[1] as $match) {

                $exactValue = explode("|", $match);
                // print_r($matches[1]);
                // print_r($exactValue);
                // exit();
                // put the formula in botmsg_formula table first
                foreach ($exactValue as $exact) {

                    $botFormula =  BotmsgFormula::where('name', $exact)->where('fk_bot_info_id', $botInfo->id)->get()->first();
                    if (isset($botFormula)) {
                        // calculate formula here
                        $FormulatedValue =  BotmsgFormula::putFormula($text_to_be_sent, $botFormula, $visitorID, $currentValue, $botInfo);
                        $text_to_be_sent = preg_replace('{{{' . $match . '}}}', $FormulatedValue, $text_to_be_sent);
                    }
                }
            }
            //exit();


            return $text_to_be_sent;
        } else {
            return $text;
        }
    }

    public static function findAPIResponse($text, $visitorID)
    {
        $text_to_be_sent = '';
        $matches = array();
        $t = preg_match_all('/##@(.*?)\@##/s', $text, $matches);


        //exit();
        if ($t) {

            foreach ($matches[1] as $match) {

                $exactValue = explode("|", $match);

                foreach ($exactValue as $exact) {

                    $botAPIResponses =  BotApiResponse::where('fk_visitor_id', $visitorID)->where('bot_msg_id', $exact)->latest()->first();

                    if (isset($botAPIResponses)) {

                        $text_to_be_sent = preg_replace('/##@(.*?)\@##/s', $botAPIResponses->api_message, $text);
                        return $text_to_be_sent;
                    } else {
                        //return $text_to_be_sent;
                    }
                }
            }
        } else {
            return $text;
        }
    }
    public static function directMessage($bot_number, $visitor_phone_no,  $credit, $amount, $txnid, $username, $deposit)
    {
        $transactionCharge = $deposit == 'UPI' ? 0 : 0.5;

        $values = [
            "type" => 'credit',
            "amount" => $amount,
            "person" => $username,
            "refrenceNo" => $txnid,
            "remarks" => '',
            "transactionType" => $deposit,
            "transactionCharge" => $transactionCharge,
            "personReceive" => NULL
        ];
        $encodedValues = base64_encode(json_encode($values));
        $arrr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $visitor_phone_no, 'command' => 'add', 'type' => 'document', 'location' => 'Credits', 'values' => $encodedValues);
        $response = BotExternalAction::idzoAPI($arrr);
        print_r($response);
        if ($response->status == 'success') {
            $message = "Rs " . $response->result->amount . " added " . $response->result->person . "  with reference no. " . $response->result->refrenceNo . " as " . $response->result->transactionType . "";
            BotExternalAction::sendcautionMessage($visitor_phone_no, $bot_number, $message, 1);
            //$message = "Update Successful!";
            //BotApiResponse::saveApiResponse(11111, 1111111, 11111, $response->status, $message, json_encode($response));
        } else {
            $message = $response->message;
            BotExternalAction::sendcautionMessage($visitor_phone_no, $bot_number, $message, 1);
            // BotApiResponse::saveApiResponse(11111, 1111111, 11111, $response->status, $message, json_encode($response));
        }
    }
}
