<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Users\AccountsModel;
use App\Models\Users\BotApiResponse;
use App\Models\Users\Botmessage;
use App\Models\Users\Botmessageoption;
use App\Models\Users\Botvisitor;
use App\Models\Users\Botvisitorhistory;
use App\Models\Users\BotvisitorReasult;
use App\Models\Users\Contacts;
use App\Models\WhatsappBotApi;
use Illuminate\Http\Request;
use App\Models\Users\Botinfo;
use App\Models\Users\BotmsgFormulaValue;
use Illuminate\Support\Facades\DB;
use App\Models\Users\BotExternalAction;
use App\Models\Users\BotmsgFormula;

class ChatbotController extends Controller
{

   public function entry(Request $request)
   {
      //return 1;

      //return response($request->vistor_name);
      // $vistor_name = "Imran";
      // $vistor_phone_no = "923458095076";
      // $wamid = "wamid.HBgMOTIzNDU4MDk1MDc2FQIAEhggNkJENTUzOTJCMUFERjhDNDk3NjE3OUY3NDM5N0Q1QTcA";
      // $timestamp = "1659950072";
      // $text_message = "1";
      // $bot_number = "923013350898";

      $vistor_name =  json_decode($request->vistor_name);
      $vistor_phone_no = ($request->vistor_phone_no);
      $wamid =  json_decode($request->wamid);
      $timestamp = json_decode($request->timestamp);
      $text_message = ($request->text_message);
      $bot_number =  ($request->bot_number);
      $vistor_phone_no = trim($vistor_phone_no);
      //$bot_number = trim("923013350898");
      // print_r($vistor_name);
      // exit();
      $text_message = urldecode($text_message);


      // get the information of the bot number
      $account_data = AccountsModel::where('phone_number', $bot_number)->get()->first();

      // check the bot information what kind of bot triggered

      $bot_info = Botinfo::getBotInfo($account_data->id, $text_message);


      // check either the visitor number is new or old
      $contact_data = Contacts::getContact($vistor_phone_no, $account_data);

      $contact_id = '';
      // if contact already exist just grab the contact id
      if ($contact_data != Null) {
         $contact_id = $contact_data->id;
      } else {
         $contact_id =  Contacts::saveContact($account_data->id, $vistor_phone_no, $vistor_name);
      }

      // check if the user come or not come within selected time hours
      $flage = Botvisitor::checkVisitor($vistor_phone_no, $contact_id, $bot_number);

      // flage false means visitor either come first time or come after the bot expiry time
      // other wise it will retrun the visitor id
      $accountData =  AccountsModel::getAccountsonPoneNumber($bot_number);

      $response = $this->curlCheckUserStatus($vistor_phone_no);


      if (!$flage) {

         // get BOT INFO for the issume it must get one record( one bot number have one flow)
         $BotInfo = Botinfo::where('account_id', $accountData->id)->get()->first();
         //$response = $this->curlCheckUserStatus($vistor_phone_no);

         if ($response->status == 'success' && $response->result->buyer == "true") {
            //buyer case if buyer directly type Credit ******* keyword
            if (strpos($text_message, "Credit") !== false || strpos($text_message, "credit") !== false) {
               $apiArray = $this->buyerDirectCreditMessage($text_message);
               $apiArray['username'] = $response->result->username;

               Botmessage::directMessage($bot_number, $vistor_phone_no, $apiArray['credit'], $apiArray['amount'], $apiArray['txnid'], $apiArray['username'], $apiArray['deposit']);
               exit();
            }
            if (preg_match_all("/[0-9]/", $text_message) >=  4) {

               $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
               $flage = $visitor_id;
               $this->AskOTP($vistor_phone_no, $text_message, $BotInfo, $bot_number, $flage);
               exit();
            }

            if (strpos($text_message, "sheet") !== false || strpos($text_message, "Sheet") !== false) {

               $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
               $flage = $visitor_id;
               $whereValue = "All";
               $this->sendSheet($vistor_phone_no, $text_message, $BotInfo, $bot_number, $flage, $whereValue);
               exit();
            } else {
               $msg_data_i = Botmessage::getMessage($BotInfo->id, 1);
            }
         } else if ($response->status == 'success' && $response->result->admin == "true") {

            //admin case if admin directly type Credit ******* keyword
            if (strpos($text_message, "Credit") !== false || strpos($text_message, "credit") !== false) {

               $apiArray = $this->adminDirectMessage($text_message);
               Botmessage::directMessage($bot_number, $vistor_phone_no, $apiArray['credit'], $apiArray['amount'], $apiArray['txnid'], $apiArray['username'], $apiArray['deposit']);
               exit();
            }

            // admin case when admin wanted to generate a sheet by giving it's username
            if (strpos($text_message, "sheet") !== false || strpos($text_message, "Sheet") !== false) {

               $operations = explode(' ', $text_message);
               if (count($operations) == 2) {
                  $whereValue = $operations[1];
               }
               $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
               $flage = $visitor_id;

               $this->sendSheet($vistor_phone_no, $text_message, $BotInfo, $bot_number, $flage, $whereValue);
               exit();
            }
            if (preg_match_all("/[0-9]/", $text_message) >=  4) {


               $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
               $flage = $visitor_id;
               $this->AskOTP($vistor_phone_no, $text_message, $BotInfo, $bot_number, $flage);
               exit();
            }

            $msg_data_i = Botmessage::getMessagebyID(104);
         } else if ($response->status == 'success' && $response->result->buyer == "false") {

            if (strpos($text_message, "Update delivery code") !== false) {

               $msg_data_i = Botmessage::getMessagebyID(113);
               // when card holder reply with template message 

               $needle = '<orderID>';
               $sentence = substr($text_message, strpos($text_message, $needle) + strlen($needle));
               $payload = explode("--", $sentence);
               $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
               $flage = $visitor_id;
               BotmsgFormula::saveFormulaValue($payload[0], $BotInfo->id, $visitor_id, 24);
               BotmsgFormula::saveFormulaValue($payload[1], $BotInfo->id, $visitor_id, 25);
               $msg_datas = Botmessage::getMessagebyID(113);
               foreach ($msg_datas as $msg_data) {
                  $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $visitor_id, $wamid, $msg_data, $BotInfo);
                  break;
               }
               exit();
            } else if (strpos($text_message, "Update OTP") !== false) {
               // when card holder reply with template message  chatbot_new_otp_request

               $needle = '<orderID>';
               $sentence = substr($text_message, strpos($text_message, $needle) + strlen($needle));
               $payload = explode("--", $sentence);
               $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
               $flage = $visitor_id;
               BotmsgFormula::saveFormulaValue($payload[0], $BotInfo->id, $visitor_id, 26);
               BotmsgFormula::saveFormulaValue($payload[1], $BotInfo->id, $visitor_id, 27);
               $msg_datas = Botmessage::getMessagebyID(110);
               foreach ($msg_datas as $msg_data) {
                  $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
                  break;
               }
               exit();
               //// on resoponse of askforopt template button we catch here payload
            } else if (strpos($text_message, "Ask for otp") !== false) {

               $needle = '<orderID>';
               $sentence = substr($text_message, strpos($text_message, $needle) + strlen($needle));
               $payload = explode("--", $sentence);
               $text_message = $payload[0];
               $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
               $flage = $visitor_id;
               $msg_datas = Botmessage::getMessagebyID(115);
               foreach ($msg_datas as $msg_data) {
                  $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
                  break;
               }
               exit();
            } else {
               $msg_data_i = Botmessage::getMessagebyID(37);
            }
         } else {
            $message = "It seems you are not a registered member of IDZO LLP. Kindly Signup at https://idzo.in or message from your registered mobile number.";
            BotExternalAction::sendcautionMessage($vistor_phone_no, $bot_number, $message);
         }


         $whatsapp_obj = new WhatsappBotApi($bot_number);
         // Send first welcome message
         foreach ($msg_data_i as $msg) {

            if ($msg->type == Botmessage::SIMPLE_MESSAGE) {
               $resp_code = $whatsapp_obj->BotSimpleMessage($vistor_phone_no, $msg->text);
            } else if ($msg->type == Botmessage::BUTTONS) {
               $button_options = Botmessageoption::where('msgs_id', $msg->id)->get();
               $resp_code =  $whatsapp_obj->BotButtonMessage($vistor_phone_no, $msg->text, $button_options);
            } else if ($msg->type == Botmessage::TEMPLATE_SiMPLE) {
               $resp_code = $whatsapp_obj->BotTemplateSimple($vistor_phone_no, $msg);
            } else {

               $data_options_for_sent = Botmessageoption::getMsgoptionbymsgID($msg->id);

               $resp_code =  $whatsapp_obj->BotInteractiveMessage($vistor_phone_no, $msg->text, $data_options_for_sent);
            }
         }
         if ($resp_code == 200) {
            $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
            Botvisitorhistory::saveVisitorHistory($visitor_id, $msg->id, $text_message, $wamid, '',  0);
         }
         exit();
      } else {

         // After session start code




         $BotInfo = Botinfo::where('account_id', $accountData->id)->get()->first();
         // only for buyer direct message
         if ($response->status == 'success' && $response->result->buyer == "true") {
            if (strpos($text_message, "Credit") !== false || strpos($text_message, "credit") !== false) {
               $apiArray = $this->buyerDirectCreditMessage($text_message);
               $apiArray['username'] = $response->result->username;
               Botmessage::directMessage($bot_number, $vistor_phone_no, $apiArray['credit'], $apiArray['amount'], $apiArray['txnid'], $apiArray['username'] = NULL, $apiArray['deposit']);
               exit();
            }
            if (strpos($text_message, "sheet") !== false || strpos($text_message, "Sheet") !== false) {

               $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
               $flage = $visitor_id;
               $whereValue = "All";
               $this->sendSheet($vistor_phone_no, $text_message, $BotInfo, $bot_number, $flage, $whereValue);
               exit();
            }
         }

         if ($response->status == 'success' && $response->result->admin == "true") {

            // only admin direct message to geneare sheet
            if (strpos($text_message, "sheet") !== false || strpos($text_message, "Sheet") !== false) {

               $operations = explode(' ', $text_message);
               // if the message come with sheet<space>username then entertain.
               if (count($operations) == 2) {
                  $whereValue = $operations[1];
                  $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
                  $flage = $visitor_id;

                  $this->sendSheet($vistor_phone_no, $text_message, $BotInfo, $bot_number, $flage, $whereValue);
                  exit();
               }
            }
            //admin case if admin directly type Credit ******* keyword
            if (strpos($text_message, "Credit") !== false || strpos($text_message, "credit") !== false) {
               $apiArray = $this->adminDirectMessage($text_message);
               Botmessage::directMessage($bot_number, $vistor_phone_no, $apiArray['credit'], $apiArray['amount'], $apiArray['txnid'], $apiArray['username'], $apiArray['deposit']);
               exit();
            }
         }

         // when card holder reply with template message of chatbot_otp_request
         if (strpos($text_message, "Update delivery code") !== false) {
            $needle = '<orderID>';
            $sentence = substr($text_message, strpos($text_message, $needle) + strlen($needle));
            $payload = explode("--", $sentence);
            BotmsgFormula::saveFormulaValue($payload[0], $BotInfo->id, $flage, 24);
            BotmsgFormula::saveFormulaValue($payload[1], $BotInfo->id, $flage, 25);
            $msg_datas = Botmessage::getMessagebyID(113);
            foreach ($msg_datas as $msg_data) {
               $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
               break;
            }
            exit();
         }
         // when card holder reply with template message  chatbot_new_otp_request
         if (strpos($text_message, "Update OTP") !== false) {
            $needle = '<orderID>';
            $sentence = substr($text_message, strpos($text_message, $needle) + strlen($needle));
            $payload = explode("--", $sentence);
            BotmsgFormula::saveFormulaValue($payload[0], $BotInfo->id, $flage, 26);
            BotmsgFormula::saveFormulaValue($payload[1], $BotInfo->id, $flage, 27);
            $msg_datas = Botmessage::getMessagebyID(110);


            foreach ($msg_datas as $msg_data) {
               $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
               break;
            }
            exit();
         }


         if (strpos($text_message, "Ask for otp") !== false) {

            $needle = '<orderID>';
            $sentence = substr($text_message, strpos($text_message, $needle) + strlen($needle));
            $payload = explode("--", $sentence);
            $text_message = $payload[0];
            $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
            $flage = $visitor_id;
            $msg_datas = Botmessage::getMessagebyID(115);
            foreach ($msg_datas as $msg_data) {
               $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
               break;
            }
            exit();
            // check if string has morethen 4 digits in any message
         }
         if (strpos($text_message, "Ask for new OTP") !== false) {

            $needle = '<orderID>';
            $sentence = substr($text_message, strpos($text_message, $needle) + strlen($needle));
            $payload = explode("--", $sentence);
            $text_message = $payload[0];
            $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
            $flage = $visitor_id;
            $msg_datas = Botmessage::getMessagebyID(116);
            foreach ($msg_datas as $msg_data) {
               $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
               break;
            }
            exit();
            // check if string has morethen 4 digits in any message
         }





         //check if exact value match, if not match then go to else 

         $msg_datas = $this->query($BotInfo, $text_message);
         if ($msg_datas->count() > 0) {
            foreach ($msg_datas as $msg_jumpt_old) {
               $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_jumpt_old, $BotInfo);
               $break = true;
               break;
            }
            exit();
         }


         //  ************************ now compare it to the coming text**************************////
         // NOW GET ALL THE MULTIPLE ANSWERS MESSAGES
         //$msg_datas = array();
         $allMultipleAnswers = Botmessage::where('fk_bot_info', $BotInfo->id)
            ->where('is_multiple_answer', 1)
            ->get();


         // $text_message_int = intval($text_message);
         // $msg_datas = $this->query($BotInfo, $text_message_int);
         foreach ($allMultipleAnswers as $allMultiple) {
            if (str_contains($allMultiple->coming_answ, ',')) {
               $coming_answer = explode(",", $allMultiple->coming_answ);
               foreach ($coming_answer as $coming) {
                  if ($text_message == $coming) {
                     $msg_datas = Botmessage::where('id', $allMultiple->id)->where('fk_bot_info', $BotInfo->id)->where('status', 1)->get();
                  } // else if ($text_message_int == $coming) {
                  //    $msg_datas = Botmessage::where('id', $allMultiple->id)->where('fk_bot_info', $BotInfo->id)->where('status', 1)->get();
                  // }
               }
            }
         }
         if ($msg_datas->count() > 0) {
            foreach ($msg_datas as $msg_data) {
               $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
            }
            exit();
         }




         //  ************************now check next sequence**************************//

         $max_seq_id =  Contacts::select('bot_visitors_history.msg_id', 'bot_visitors_history.sequence', 'bot_visitors_history.created_at')
            ->join('bot_visitors', 'bot_visitors.contact_id', '=', 'contacts.id')
            ->join('bot_visitors_history', 'bot_visitors_history.visitor_id', '=', 'bot_visitors.id')
            ->where('contacts.phone_number', $vistor_phone_no)
            ->where('bot_visitors_history.status', 1)
            //->max('bot_visitors_history.msg_id');
            ->latest()->first();
         // if notthing found in the next sequence go to else and send finalize text.
         if ($max_seq_id != NULL) {

            $nextId = Botmessage::find($max_seq_id->msg_id);

            // check if we need to extract multiple messages
            if (strpos($nextId->sequence, ',') !== false) {
               $ids = explode(",", $nextId->sequence);
               $msg_datas = Botmessage::where('fk_bot_info', $BotInfo->id)->whereIn('id', $ids)->where('status', 1)->get();
            } else {

               $msg_datas = Botmessage::where('fk_bot_info', $BotInfo->id)->where('id', $nextId->sequence)->where('status', 1)->get();
            }

            $fflage = false;

            foreach ($msg_datas as $msg_data) {

               $fflage = true;
               $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
            }
            if (!$fflage) {
               if (preg_match_all("/[0-9]/", $text_message) >=  4) {

                  $response = $this->curlCheckUserStatus($vistor_phone_no);
                  if ($response->status == 'success' && ($response->result->buyer == "true") || ($response->result->admin == "true")) {
                     $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
                     $flage = $visitor_id;
                     $this->AskOTP($vistor_phone_no, $text_message, $BotInfo, $bot_number, $flage);
                     exit();
                  }
               }

               $message = "Please choose any of the above options.";
               BotExternalAction::sendcautionMessage($vistor_phone_no, $bot_number, $message);
            }
         } else {

            if (preg_match_all("/[0-9]/", $text_message) >=  4) {

               $response = $this->curlCheckUserStatus($vistor_phone_no);
               if ($response->status == 'success' && ($response->result->buyer == "true") || ($response->result->admin == "true")) {
                  $visitor_id =  Botvisitor::saveVisitor($contact_id, $BotInfo->id);
                  $flage = $visitor_id;
                  $this->AskOTP($vistor_phone_no, $text_message, $BotInfo, $bot_number, $flage);
                  exit();
               }
            }
            $message = "Please choose any of the above options";
            BotExternalAction::sendcautionMessage($vistor_phone_no, $bot_number, $message);
         }


         exit();














         // return $msg_datas;

         if ($msg_datas->count() > 0) {

            foreach ($msg_datas as $msg_data) {

               // if bot need to recalculate or jump to in another flow
               $checkifGo =  Botvisitorhistory::checkIfGo($vistor_phone_no, $flage);

               if ($text_message == 68.2 && $checkifGo) {

                  $msg_datas_jumpto_old = $this->querybyId($BotInfo, 71);
                  foreach ($msg_datas_jumpto_old as $msg_jumpt_old) {
                     $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_jumpt_old, $BotInfo);
                     break;
                  }
               } else if ($msg_data->jump_to) {

                  $msg_datas_jumpto = $this->querybyId($BotInfo, $msg_data->jump_to);

                  foreach ($msg_datas_jumpto as $msg_jumpt) {
                     $checkifGo =  Botvisitorhistory::checkIfGo($vistor_phone_no, $flage);
                     // manull work alert // 

                     if (!$checkifGo) {
                        $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_jumpt, $BotInfo);
                     } else {
                        $msg_datas_jumpto_old = $this->querybyId($BotInfo, 71);
                        foreach ($msg_datas_jumpto_old as $msg_jumpt_old) {
                           $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_jumpt_old, $BotInfo);
                           $break = true;
                           break;
                        }
                        if ($break) {
                           break;
                        }
                     }
                     //// finish manul work it's stop multiple calculation only one time Monthly and one time yearly calulatin allow
                  }
                  // this will work when nothing have i.e not in jumpt to etc.
               } else {
                  $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
               }
            }
         } else {

            //check if Integer value match in upcoming answer column of msg-tables
            $text_message_int = intval($text_message);
            $msg_datas = $this->query($BotInfo, $text_message_int);

            if ($msg_datas->count() > 0) {
               foreach ($msg_datas as $msg_data) {

                  $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
               }
               // now check if there is match in upcoming answer column
            } else if (!$msg_datas->count()) {

               //if (is_numeric($text_message)) {

               $text_message_int = intval($text_message);
               // get all the multipel answer of that bot
               $allMultipleAnswers = Botmessage::where('fk_bot_info', $BotInfo->id)
                  ->where('is_multiple_answer', 1)
                  ->get();

               // now compare it to the coming text
               foreach ($allMultipleAnswers as $allMultiple) {
                  if (str_contains($allMultiple->coming_answ, ',')) {
                     $coming_answer = explode(",", $allMultiple->coming_answ);
                     foreach ($coming_answer as $coming) {
                        // manull work alert // 

                        if ($text_message == $coming) {
                        } else if ($text_message_int == $coming) {

                           $msg_datas = Botmessage::where('id', $allMultiple->id)->where('fk_bot_info', $BotInfo->id)->where('status', 1)->get();
                        }
                     }
                  }
               }




               if ($msg_datas->count() > 0) {

                  foreach ($msg_datas as $msg_data) {
                     // float value must be filtered as floating values must be check in very first step
                     // if (!str_contains($msg_data->coming_answ, '.')) {
                     $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
                     // }
                  }
               } else {

                  // if still no data found in msg datas which means that's might be the last step ( probably the external function or asking the question)
                  //  else {
                  // get the lastest from the chat hostory table and get the upcoming message by looking them
                  $max_seq_id =  Contacts::select('bot_visitors_history.msg_id', 'bot_visitors_history.sequence', 'bot_visitors_history.created_at')
                     ->join('bot_visitors', 'bot_visitors.contact_id', '=', 'contacts.id')
                     ->join('bot_visitors_history', 'bot_visitors_history.visitor_id', '=', 'bot_visitors.id')
                     ->where('contacts.phone_number', $vistor_phone_no)
                     ->where('bot_visitors_history.status', 1)
                     //->max('bot_visitors_history.msg_id');
                     ->latest()->first();

                  $nextId = Botmessage::find($max_seq_id->msg_id);

                  // check if we need to extract multiple messages
                  if (strpos($nextId->sequence, ',') !== false) {
                     $ids = explode(",", $nextId->sequence);
                     $msg_datas = Botmessage::where('fk_bot_info', $BotInfo->id)->whereIn('id', $ids)->where('status', 1)->get();
                  } else {

                     $msg_datas = Botmessage::where('fk_bot_info', $BotInfo->id)->where('id', $nextId->sequence)->where('status', 1)->get();
                  }

                  $fflage = false;

                  foreach ($msg_datas as $msg_data) {

                     $fflage = true;
                     //check if upcoming message has formula values
                     //$check_dynamicValue = BotmsgFormula::dynamicComingValue($msg_data->coming_answ, $text_message, $flage, $BotInfo->id);
                     // if dyanmic value not match in above function set the flage false and send caution message
                     $re =  Botvisitor::process($bot_number, $vistor_phone_no, $text_message, $flage, $wamid, $msg_data, $BotInfo);
                  }
                  if (!$fflage) {

                     $message = "Please enter correct details!";
                     BotExternalAction::sendcautionMessage($vistor_phone_no, $bot_number, $message);
                  }
               }
            }
         }
      }
   }
   public function buyerDirectCreditMessage($text_message)
   {
      $operations = explode(' ', $text_message);
      $count = count($operations);
      $apiArray = array();

      for ($i = 0; $i < $count; $i++) {
         if ($i == 0)
            $apiArray['credit'] = $operations[$i] == NULL ? '' : $operations[$i];
         if ($i == 1)
            $apiArray['amount'] =  $operations[$i] == NULL ? '' : $operations[$i];
         if ($i == 2)
            $apiArray['txnid'] = $operations[$i] == NULL ? '' : $operations[$i];
         // if ($i == 3)
         //    $apiArray['username'] = $operations[$i] == NULL ? '' : $operations[$i];
         if ($i == 3) {
            if ($operations[$i] == 'Deposit' || $operations[$i] == 'deposit') {
               $apiArray['deposit'] = $operations[$i] == NULL ? '' : $operations[$i];
            } else {
               $apiArray['deposit'] = $operations[$i] == NULL ? '' : 'UPI';
            }
         }
      }
      if (!array_key_exists('txnid', $apiArray)) {
         $apiArray['txnid'] = '';
      }
      // if (!array_key_exists('username', $apiArray)) {
      //    $apiArray['username'] = 'unidentified';
      // }
      if (!array_key_exists('amount', $apiArray)) {
         $apiArray['amount'] = '';
      }
      if (!array_key_exists('deposit', $apiArray)) {
         $apiArray['deposit'] = 'UPI';
      }
      return $apiArray;
   }
   public function adminDirectMessage($text_message)
   {
      $operations = explode(' ', $text_message);
      $count = count($operations);
      $apiArray = array();

      for ($i = 0; $i < $count; $i++) {
         if ($i == 0)
            $apiArray['credit'] = $operations[$i] == NULL ? '' : $operations[$i];
         if ($i == 1)
            $apiArray['amount'] =  $operations[$i] == NULL ? '' : $operations[$i];
         if ($i == 2)
            $apiArray['txnid'] = $operations[$i] == NULL ? '' : $operations[$i];
         if ($i == 3)
            $apiArray['username'] = $operations[$i] == NULL ? '' : $operations[$i];
         if ($i == 4) {
            if ($operations[$i] == 'Deposit' || $operations[$i] == 'deposit') {
               $apiArray['deposit'] = $operations[$i] == NULL ? '' : $operations[$i];
            } else {
               $apiArray['deposit'] = $operations[$i] == NULL ? '' : 'UPI';
            }
         }
      }
      if (!array_key_exists('txnid', $apiArray)) {
         $apiArray['txnid'] = '';
      }
      if (!array_key_exists('username', $apiArray)) {
         $apiArray['username'] = 'unidentified';
      }
      if (!array_key_exists('amount', $apiArray)) {
         $apiArray['amount'] = '';
      }
      if (!array_key_exists('deposit', $apiArray)) {
         $apiArray['deposit'] = 'UPI';
      }
      return $apiArray;
   }

   public function adminSheetmessage($text_message)
   {
      $operations = explode(' ', $text_message);
      $count = count($operations);
      $apiArray = array();

      for ($i = 0; $i < $count; $i++) {
         if ($i == 0)
            $apiArray['sheet'] = $operations[$i] == NULL ? '' : $operations[$i];
         if ($i == 1)
            $apiArray['username'] =  $operations[$i] == NULL ? '' : $operations[$i];
      }

      return $apiArray;
   }
   public function del()
   {

      BotmsgFormulaValue::truncate();
      Botvisitorhistory::truncate();
      BotApiResponse::truncate();
      Botvisitor::query()->delete();
      echo "done";
   }

   public function updateOTP()
   {
      // phone number who's order belongs
      $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => '923458095076', 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => 'IZ2312091132');
      $response = BotExternalAction::idzoAPI($arr);
      //print_r($response);
      $values = [
         "OTP" => 'NULL',
         "status" => $response->result->status
      ];
      // set phone number of 
      $encodedValues = base64_encode(json_encode($values));
      $arrr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $response->result->phone, 'command' => 'update', 'type' => 'document', 'location' => 'Orders', 'id' => 'IZ2312091132', 'values' => $encodedValues);
      $response = BotExternalAction::idzoAPI($arrr);
      print_r($response);
   }




   public function query($BotInfo, $text_message)
   {
      $msg_datas = Botmessage::where('coming_answ', "$text_message")
         ->where('fk_bot_info', $BotInfo->id)
         ->where('status', 1)
         ->get();
      return $msg_datas;
   }
   public function querybyId($BotInfo, $text_message)
   {
      $ids = explode(",",  $text_message);
      $msg_datas = Botmessage::wherein('id', $ids)
         ->where('fk_bot_info', $BotInfo->id)
         ->where('status', 1)
         ->get();
      return $msg_datas;
   }

   public function sendSheet($vistor_phone_no, $text_message, $BotInfo, $bot_number, $visitor_id, $whereValue)
   {

      $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Sheets', 'where' => 'buyer_orders', 'whereValue' => $whereValue);
      $response = BotExternalAction::idzoAPI($arr);
      // BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
      if ($response->status == 'success') {
         $mediaResponse = BotExternalAction::sendMedia($vistor_phone_no, $response->id, $BotInfo->account_id);
         exit();
      } else if ($response->status != 'success') {
      }
   }

   public function AskOTP($vistor_phone_no, $text_message, $BotInfo, $bot_number, $visitor_id)
   {

      $arr = array('username' => BotApiResponse::$API_USERNAME, 'authId' => BotApiResponse::$API_PASSWORD, 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Orders', 'id' => $text_message);
      $response = BotExternalAction::idzoAPI($arr);

      // BotApiResponse::saveApiResponse($BotInfo->id, $visitor_id, $query[0]->fk_msg_id, $response->status, $response->message, json_encode($response));
      if ($response->status != 'success') {
         //print_r('here');
         $message = $response->message;
         $button_options = Botmessageoption::where('msgs_id', 95)->get();
         BotExternalAction::sendcautionButtonMessage($vistor_phone_no, $bot_number, $message, $button_options, 1);
      } else if ($response->status == 'success') {


         //$message = 'abc';
         // $message . "Product :" . $productName . '\n';
         $message = "Product :" . $response->result->name == NULL ? 0 : $response->result->name . '\n';
         $addressName = $response->result->addressName == NULL ? 0 : $response->result->addressName;
         $OTP = $response->result->OTP == NULL ? 0 : $response->result->OTP;
         $trackingID = $response->result->trackingId == NULL ? 0 : $response->result->trackingId;
         $storename =  $response->result->service == NULL ? 0 : $response->result->service;
         $courierName = $response->result->courier == NULL ? 0 : $response->result->courier;
         $pinCode = $response->result->pincode == NULL ? 0 : $response->result->pincode;
         $sellingPrice = $response->result->sellingPrice == NULL ? 0 : $response->result->sellingPrice;
         $orderStatus = $response->result->status == NULL ? 0 : $response->result->status;



         $message = $message . "Address name :-" . $addressName . '\n';
         $message = $message . 'Otp :-' . $OTP . '\n';
         $message = $message . 'Order Id :-' .  $response->result->orderId . '\n';
         $message = $message . 'Tracking Id :-' . $trackingID . '\n';;
         $message = $message . 'Store name :-' . $storename . '\n'; // not found
         $message = $message . 'Courier name:-' . $courierName  . '\n';
         $message = $message . 'IDZO Id :-' . $response->result->id . '\n';
         $message = $message . 'Pincode :-' . $pinCode . '\n';
         $message = $message . 'Selling price:-' . $sellingPrice . '\n';
         $message = $message . "Order status :-" . $orderStatus . '\n';
         $message = $message . 'Last 4 digits :-' . substr($response->result->delBToPhone, -4) . '\n';
         if ($response->result->OTP == null || $response->result->OTP == "NULL" || $response->result->OTP == "") {
            $title = 'Ask for otp';
         } else {
            $title = 'Ask for new OTP';
         }

         $button_options = Botmessageoption::where('msgs_id', 95)->get();
         BotExternalAction::sendcustomcautionButtonMessage($title, $vistor_phone_no, $bot_number, $message, $button_options, 1, $response->result->id, $response->result->buyerPhone);


         $request = array();
         //$request = (object) array('Account_Id' => '12', 'components' => 12, 'row' => $row, 'to_number' => $vistor_phone_no, 'template_name' => 'askforotp', 'lang' => 'en', 'orderID' => $response->result->id, 'buyerNo' =>  $response->result->buyerPhone);
         //$response =  BotExternalAction::sendTemplate($request);

      }
   }
   public function curlCheckUserStatus($vistor_phone_no)
   {
      $curl = curl_init();

      curl_setopt_array($curl, array(
         CURLOPT_URL => 'https://idzo.in/app/?ver=3',
         CURLOPT_RETURNTRANSFER => true,
         CURLOPT_ENCODING => '',
         CURLOPT_MAXREDIRS => 10,
         CURLOPT_TIMEOUT => 0,
         CURLOPT_FOLLOWLOCATION => true,
         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
         CURLOPT_CUSTOMREQUEST => 'POST',
         CURLOPT_POSTFIELDS => array('username' => 'wa.api', 'authId' => 'A7b!iw_ert24@^#^4f*r4(', 'phone' => $vistor_phone_no, 'command' => 'get', 'type' => 'document', 'location' => 'Users', 'id' => 'userId'),
      ));

      $response = curl_exec($curl);
      curl_close($curl);
      $response = (json_decode($response));
      return $response;
   }
}
