<?php
   ob_start();
   session_start();
?>

<?
   // error_reporting(E_ALL);
   // ini_set("display_errors", 1);
?>

<html lang = "en">

   <head>
      <title>Internal Use Whatsapp api</title>
      <link href = "css/bootstrap.min.css" rel = "stylesheet">

      <style>
         body {
            padding-top: 40px;
            padding-bottom: 40px;
            background-color: #ADABAB;
         }

         .form-signin {
            max-width: 330px;
            padding: 15px;
            margin: 0 auto;
            color: #017572;
         }

         .form-signin .form-signin-heading,
         .form-signin .checkbox {
            margin-bottom: 10px;
         }

         .form-signin .checkbox {
            font-weight: normal;
         }

         .form-signin .form-control {
            position: relative;
            height: auto;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            padding: 10px;
            font-size: 16px;
         }

         .form-signin .form-control:focus {
            z-index: 2;
         }

         .form-signin input[type="email"] {
            margin-bottom: -1px;
            border-bottom-right-radius: 0;
            border-bottom-left-radius: 0;
            border-color:#017572;
         }

         .form-signin input[type="password"] {
            margin-bottom: 10px;
            border-top-left-radius: 0;
            border-top-right-radius: 0;
            border-color:#017572;
         }

         h2{
            text-align: center;
            color: #017572;
         }
      </style>

   </head>

   <body>

      <h2>Enter Username and Password</h2>
      <div class = "container form-signin">

         <?php
            $msg = '';

            $arraydatabase=array("whatsappapi" => array("password" => "LmG6", "instance" => "https://api.maytapi.com/api/d7683b62-1d55-4f6f-b886-cb929b9b74fd", "token" => "fb09bb72-2bb5-4e91-83d7-18ee58ee87f0", "phoneid" => 23343),
                                 "whatsappapi1" => array("password" => "LmG6", "instance" => "https://api.maytapi.com/api/d7683b62-1d55-4f6f-b886-cb929b9b74fd", "token" => "fb09bb72-2bb5-4e91-83d7-18ee58ee87f0", "phoneid" => 23343));
            //echo $arraydatabase["whatsappapi"]["instance"];
            /*
            $object = (object)[
                'whatsappapi' => (object)['instance' => "https://api.chat-api.com/instance259849/", "token" => "ijmoq2peb8n0toz2"],
                'member1o' => (object)['member1' => "hello, I'm 1o.1"],
                'member2' => "hello, I'm 2",
            ];
            */
            if (array_key_exists($_SESSION['username'],$arraydatabase))
            {
              $APIurl = $arraydatabase[$_SESSION['username']]["instance"];
              $token =  $arraydatabase[$_SESSION['username']]["token"];
              $phoneid = $arraydatabase[$_SESSION['username']]["phoneid"];
            }

            if (isset($_POST['login']) && !empty($_POST['username'])
               && !empty($_POST['password'])) {

               if (array_key_exists($_POST['username'],$arraydatabase)) {

                 if($_POST['password'] != $arraydatabase[$_POST['username']]["password"]) {
                     $msg = 'Wrong username or password';
                     return;
                 }

                  $_SESSION['valid'] = true;
                  $_SESSION['timeout'] = time();
                  $_SESSION['username'] = $_POST['username'];

                  if (array_key_exists($_SESSION['username'],$arraydatabase))
                  {
                    $APIurl = $arraydatabase[$_SESSION['username']]["instance"];
                    $token =  $arraydatabase[$_SESSION['username']]["token"];
                  }

                  $webhookUrl = "https://whandler.royalbet33.com";
                  $payload = array("webhook" => $webhookUrl);
                  $ch = curl_init();
                  $environment_url = $APIurl . "/setWebhook";

                  curl_setopt($ch, CURLOPT_URL,$environment_url);
                  curl_setopt($ch, CURLOPT_POST, 1);
                  curl_setopt($ch, CURLOPT_POSTFIELDS,
                              json_encode($payload,JSON_UNESCAPED_SLASHES));
                  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                  'x-maytapi-key: ' . $token,
                                  'accept: application/json',
                                  'Content-Type: application/json'
                  ));
                  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                  $server_output = curl_exec($ch);
                  curl_close ($ch);

                  echo $server_output;

                  echo 'You have entered valid use name and password';
               } else {
                  $msg = 'Wrong username or password';
               }
            }

            if (isset($_POST['logout'])) {
              $environment_url = $APIurl . '/' . $phoneid . "/logout";
              $tuCurl= curl_init();
              curl_setopt($tuCurl, CURLOPT_URL, $environment_url);
              curl_setopt($tuCurl, CURLOPT_TIMEOUT, 60000 );
              curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
              curl_setopt($tuCurl, CURLOPT_HTTPHEADER, array(
                              'x-maytapi-key: ' . $token,
                              'accept: application/json'
              ));
              curl_setopt($tuCurl, CURLINFO_HEADER_OUT, true);
              $exec = curl_exec($tuCurl);
              curl_close($tuCurl);
              echo 'You have logout whatsapp' . $exec;
              //header('Refresh: 2; URL = login.php');
            }

         ?>
      </div> <!-- /container -->


      <div class = "container">
      <?php if( empty($_SESSION['username']) ) { ?>
         <form class = "form-signin" role = "form"
            action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);
            ?>" method = "post">
            <h4 class = "form-signin-heading"><?php echo $msg; ?></h4>
            <input type = "text" class = "form-control" placeholder="User Name"
               name = "username"
               required autofocus></br>
            <input type = "password" class = "form-control" placeholder="Password"
               name = "password" required>
            <button class = "btn btn-lg btn-primary btn-block" type = "submit"
               name = "login">Login</button>
         </form>
    <?php } else {

      //$APIurl = 'https://api.chat-api.com/instance259849/';
      //$token = 'ijmoq2peb8n0toz2';

      $environment_url = $APIurl . '/' . $phoneid . "/status";
      $tuCurl= curl_init();
      curl_setopt($tuCurl, CURLOPT_URL, $environment_url);
      curl_setopt($tuCurl, CURLOPT_TIMEOUT, 60000 );
      curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($tuCurl, CURLOPT_HTTPHEADER, array(
                      'x-maytapi-key: ' . $token,
                      'accept: application/json'
      ));
      curl_setopt($tuCurl, CURLINFO_HEADER_OUT, true);
      $exec = curl_exec($tuCurl);
      curl_close($tuCurl);
      //$exec ="nothing";
      $arrbody = json_decode($exec);
      //echo $exec;
      if ($arrbody->status->isQr) {

        $environment_url = $APIurl . '/' . $phoneid . "/qrCode";
        $tuCurl= curl_init();
        curl_setopt($tuCurl, CURLOPT_URL, $environment_url);
        curl_setopt($tuCurl, CURLOPT_TIMEOUT, 60000 );
        curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($tuCurl, CURLOPT_HTTPHEADER, array(
                        'x-maytapi-key: ' . $token,
                        'accept: */*'
        ));
        //curl_setopt($tuCurl, CURLINFO_HEADER_OUT, true);
        $exec = curl_exec($tuCurl);
        curl_close($tuCurl);
        $xt = time();
        $save_as = $xt . 'qrcode.jpg';
        $fp = fopen($save_as, 'x');
        fwrite($fp, $exec);
        fclose($fp);
        echo "<div>
                <p>Scan To Login Whatsapp</p>
                <img src=". $xt . "qrcode.jpg" . " />
              </div>";

      } else if ($arrbody->status->loading) {
        /*
        $environment_url = $APIurl . "reboot/?token=" . $token;
        $tuCurl= curl_init();
        curl_setopt($tuCurl, CURLOPT_URL, $environment_url);
        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);
        $arrbody = json_decode($exec);
        echo $exec;
        */
        echo "instance loading... Please wait 5 minute and refresh.";

      } else if ($arrbody->status->loggedIn) {
        $webhookUrl = "https://whandler.royalbet33.com";
        $payload = array("webhook" => $webhookUrl);
        $ch = curl_init();
        $environment_url = $APIurl . "/setWebhook";

        curl_setopt($ch, CURLOPT_URL,$environment_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,
                    json_encode($payload,JSON_UNESCAPED_SLASHES));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                        'x-maytapi-key: ' . $token,
                        'accept: application/json',
                        'Content-Type: application/json'
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec($ch);
        curl_close ($ch);
        //echo $environment_url . " token :" . $token;
        //echo $server_output;

        ?>
        <form class = "form-signout" role = "form"
           action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);
           ?>" method = "post">
           <button class = "btn btn-lg btn-primary btn-block" type = "submit"
              name = "logout">Logout Whatsapp</button>
        </form>
        <?php

        echo "<div>Whatsapp Already Login</div>";
      } else {
        echo $exec;
      }


    } ?>
         Click here to logout <a href = "logout.php" tite = "Logout">Session.

      </div>


   </body>
</html>
