<?php

class whatsAppBot
{
    //specify instance URL and token
    var $APIurl = '';
    var $token = '';

    public function __construct()
    {
        //get the JSON body from the instance
        $json = file_get_contents('php://input');
        $decoded = json_decode($json, true);

        if (isset($decoded['phone_id'])) {
          if ($decoded['phone_id'] == '23343') {
            $this->APIurl = 'https://api.maytapi.com/api/d7683b62-1d55-4f6f-b886-cb929b9b74fd';
            $this->token = 'fb09bb72-2bb5-4e91-83d7-18ee58ee87f0';
          } else if ($decoded['phone_id'] == '23343') {
            $this->APIurl = 'https://api.maytapi.com/api/d7683b62-1d55-4f6f-b886-cb929b9b74fd';
            $this->token = 'fb09bb72-2bb5-4e91-83d7-18ee58ee87f0';
          }
        }

        //write parsed JSON-body to the file for debugging

        //ob_start();
        //var_dump($decoded);
        //$input = ob_get_contents();
        //ob_end_clean();
        file_put_contents('input_requests.log', $json . PHP_EOL, FILE_APPEND);


        if (isset($decoded['message'])) {
            //check every new message
                //delete excess spaces and split the message on spaces. The first word in the message is a command, other words are parameters
                //current message shouldn't be send from your bot, because it calls recursion
                if ( !$decoded['message']['fromMe']) {
                  if ($decoded['phone_id'] == '23343') {
                    $this->royalbet33_register($decoded['user']['id']);
                  } else if ($decoded['phone_id'] == '23343') {
                    $this->royalbet33_register($decoded['user']['id']);
                  }
                    //check what command contains the first word and call the function
                }
        }
    }

    public function invalidkey($chatId) {
      $this->sendMessage($chatId, "Invalid Keyword. Please Try Again.");
    }


    public function sendcurl($chatId, $requrl) {
      $tim = (int) (microtime(true) * 1000);
      $tts = "$tim";
      $splitphone = explode('@', $chatId);
      $phone = $splitphone[0];
      $token = md5($tts);
      $sign = hash('ripemd160', $phone . $token);

      $header   = array();
      $header[] = "Accept:text/html,application/xhtml+xml,application/xml;q=0.8";
      $header[] = "Cache-Control: max-age=0";
      $header[] = "Connection: keep-alive";
      $header[] = "Keep-Alive:timeout=5, max=100";
      $header[] = "Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3";
      $header[] = "Accept-Language:es-ES,es;q=0.8";

      $environment_url = $requrl . "?phone=" . $phone . "&token=" . $token . "&sign=" . $sign;
      $tuCurl= curl_init();
      curl_setopt($tuCurl, CURLOPT_URL, $environment_url);
      curl_setopt($tuCurl, CURLOPT_VERBOSE, 0);
      curl_setopt($tuCurl, CURLOPT_HTTPHEADER, $header);
      curl_setopt($tuCurl, CURLOPT_TIMEOUT, 60000 );
      curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($tuCurl, CURLINFO_HEADER_OUT, true);
      $exec = curl_exec($tuCurl);
      curl_close($tuCurl);
      return $exec;
    }

    public function royalbet33_register($chatId)
    {
      $splitphone = explode('@', $chatId);
      $phone = $splitphone[0];
      //$this->sendMessage($chatId, "Keyword Receive. Registering User. Please Wait...");
      $exec = $this->sendcurl($chatId ,"https://m.royalbet33.com/royalbet33_register/");
      //echo $exec;
      $arrbody = json_decode($exec);
      if ($arrbody->Success) {
        $responsestring = $arrbody->Message . "\n";
        $responsestring .= "Mobile Number: " . substr($phone,1) . "\n";
        $responsestring .= "Password: " . $arrbody->password . "\n";
        $responsestring .= "Link: royalbet33.net/?login=true \n";
        //$this->sendMessage($chatId, $responsestring);
      } else {
        $responsestring = $arrbody->Message . "\n";
        $responsestring .= "To Reset Password, Please Send" . "\n" . "royalbet33_reset" . "\n";
        $responsestring .= "Link: royalbet33.net/?login=true \n";
        //$this->sendMessage($chatId, $responsestring);
      }

    }


    public function royalbet33_reset($chatId)
    {
      $splitphone = explode('@', $chatId);
      $phone = $splitphone[0];
      $exec = $this->sendcurl($chatId ,"https://m.royalbet33.com/royalbet33_reset/");
      $arrbody = json_decode($exec);
      if ($arrbody->Success) {
        $responsestring = $arrbody->Message . "\n";
        $responsestring .= "Mobile Number: " . substr($phone,1) . "\n";
        $responsestring .= "Password: " . $arrbody->password . "\n";
        $responsestring .= "Link: royalbet33.net/?login=true \n";
        //$this->sendMessage($chatId, $responsestring);
      } else {
        $responsestring = $arrbody->Message . "\n";
        $responsestring .= "To Register, Please Send" . "\n" . "royalbet33_register" . "\n";
        //$responsestring .= "Click Link Below To Login\n https://royalbet33.net/?login=true \n";
        //$this->sendMessage($chatId, $responsestring);
      }
    }


    public function tmc86_register($chatId)
    {
      $splitphone = explode('@', $chatId);
      $phone = $splitphone[0];
      //$this->sendMessage($chatId, "Keyword Receive. Registering User. Please Wait...");
      $exec = $this->sendcurl($chatId ,"https://tmc86.com/tmc86_register/");
      //echo $exec;
      $arrbody = json_decode($exec);
      if ($arrbody->Success) {
        $responsestring = $arrbody->Message . "\n";
        $responsestring .= "Mobile Number: " . substr($phone,1) . "\n";
        $responsestring .= "Password: " . $arrbody->password . "\n";
        $responsestring .= "Link: tmc86.com/?login=true \n";
        //$this->sendMessage($chatId, $responsestring);
      } else {
        $responsestring = $arrbody->Message . "\n";
        $responsestring .= "To Reset Password, Please Send" . "\n" . "tmc86_reset" . "\n";
        $responsestring .= "Link: tmc86.com/?login=true \n";
        //$this->sendMessage($chatId, $responsestring);
      }
    }



    public function tmc86_reset($chatId)
    {
      $splitphone = explode('@', $chatId);
      $phone = $splitphone[0];
      $exec = $this->sendcurl($chatId ,"https://tmc86.com/tmc86_reset/");
      $arrbody = json_decode($exec);
      if ($arrbody->Success) {
        $responsestring = $arrbody->Message . "\n";
        $responsestring .= "Mobile Number: " . substr($phone,1) . "\n";
        $responsestring .= "Password: " . $arrbody->password . "\n";
        $responsestring .= "Link: tmc86.com/?login=true \n";
        //$this->sendMessage($chatId, $responsestring);
      } else {
        $responsestring = $arrbody->Message . "\n";
        $responsestring .= "To Register, Please Send" . "\n" . "tmc86_register" . "\n";
        //$responsestring .= "Click Link Below To Login\n https://royalbet33.net/?login=true \n";
        //$this->sendMessage($chatId, $responsestring);
      }
    }
    //this function calls function sendRequest to send a simple message
    //@param $chatId [string] [required] - the ID of chat where we send a message
    //@param $text [string] [required] - text of the message
    public function welcome($chatId, $noWelcome = false)
    {
        $welcomeString = ($noWelcome) ? "Incorrect command\n" : "WhatsApp Demo Bot PHP\n";
        $this->sendMessage($chatId,
            $welcomeString .
            "Commands:\n" .
            "1. chatId - show ID of the current chat\n" .
            "2. time - show server time\n" .
            "3. me - show your nickname\n" .
            "4. file [format] - get a file. Available formats: doc/gif/jpg/png/pdf/mp3/mp4\n" .
            "5. ptt - get a voice message\n" .
            "6. geo - get a location\n" .
            "7. group - create a group with the bot"
        );
    }

    //sends Id of the current chat. it is called when the bot gets the command "chatId"
    //@param $chatId [string] [required] - the ID of chat where we send a message
    public function showchatId($chatId)
    {
        $this->sendMessage($chatId, 'chatId: ' . $chatId);
    }
    //sends current server time. it is called when the bot gets the command "time"
    //@param $chatId [string] [required] - the ID of chat where we send a message
    public function time($chatId)
    {
        $this->sendMessage($chatId, date('d.m.Y H:i:s'));
    }
    //sends your nickname. it is called when the bot gets the command "me"
    //@param $chatId [string] [required] - the ID of chat where we send a message
    //@param $name [string] [required] - the "senderName" property of the message
    public function me($chatId, $name)
    {
        $this->sendMessage($chatId, $name);
    }
    //sends a file. it is called when the bot gets the command "file"
    //@param $chatId [string] [required] - the ID of chat where we send a message
    //@param $format [string] [required] - file format, from the params in the message body (text[1], etc)
    public function file($chatId, $format)
    {
        $availableFiles = array(
            'doc' => 'document.doc',
            'gif' => 'gifka.gif',
            'jpg' => 'jpgfile.jpg',
            'png' => 'pngfile.png',
            'pdf' => 'presentation.pdf',
            'mp4' => 'video.mp4',
            'mp3' => 'mp3file.mp3',
        );

        if (isset($availableFiles[$format])) {
            $data = array(
                'chatId' => $chatId,
                'body' => 'https://domain.com/PHP/' . $availableFiles[$format],
                'filename' => $availableFiles[$format],
                'caption' => 'Get your file ' . $availableFiles[$format],
            );
            $this->sendRequest('sendFile', $data);
        }
    }

    //sends a voice message. it is called when the bot gets the command "ptt"
    //@param $chatId [string] [required] - the ID of chat where we send a message
    public function ptt($chatId)
    {
        $data = array(
            'audio' => 'https://domain.com/PHP/ptt.ogg',
            'chatId' => $chatId,
        );
        $this->sendRequest('sendAudio', $data);
    }

    //sends a location. it is called when the bot gets the command "geo"
    //@param $chatId [string] [required] - the ID of chat where we send a message
    public function geo($chatId)
    {
        $data = array(
            'lat' => 51.51916,
            'lng' => -0.139214,
            'address' => 'Ваш адрес',
            'chatId' => $chatId,
        );
        $this->sendRequest('sendLocation', $data);
    }

    //creates a group. it is called when the bot gets the command "group"
    //@param chatId [string] [required] - the ID of chat where we send a message
    //@param author [string] [required] - "author" property of the message
    public function group($author)
    {
        $phone = str_replace('@c.us', '', $author);
        $data = array(
            'groupName' => 'Group with the bot PHP',
            'phones' => array($phone),
            'messageText' => 'It is your group. Enjoy',
        );
        $this->sendRequest('group', $data);
    }

    public function sendMessage($chatId, $text)
    {
        $data = array('chatId' => $chatId, 'body' => $text);
        $this->sendRequest('sendMessage', $data);
    }

    public function sendRequest($method, $data)
    {
        $url = $this->APIurl . $method . '/?token=' . $this->token;
        if (is_array($data)) {
            $data = json_encode($data);
        }
        /*
        $options = stream_context_create(['http' => [
            'method' => 'POST',
            'header' => 'Content-type: application/json',
            'content' => $data]]);
        $response = file_get_contents($url, false, $options);
        file_put_contents('requests.log', $response . PHP_EOL, FILE_APPEND);
        */
        //$environment_url = $APIurl . 'webhook/?token=' . $token;
        //$webhookUrl = "https://whandler.royalbet33.com";
        $header   = array();
        $header[] = "Content-type: application/json";
        $ch= curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POSTFIELDS,
                     $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        $server_output = curl_exec($ch);
        curl_close ($ch);
        //file_put_contents('requests.log', $server_output . $url . $data . PHP_EOL, FILE_APPEND);
    }
}

//execute the class when this file is requested by the instance
new whatsAppBot();
