<?php
include "../config/connect.php";
$db = mysqli_query($con,"SELECT url_whatsapp_gateway,apikey_whatsapp FROM data_server WHERE id = '$_GET[id]' ");
$data = mysqli_fetch_assoc($db);

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => $data['url_whatsapp_gateway'].'getState',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_POSTFIELDS => 'apiKey='.$data['apikey_whatsapp'],
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/x-www-form-urlencoded'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
$dataArray = json_decode($response, true);
$stat = $dataArray['results']['state'];
echo "<center>";

if ($stat == "CONNECTED") {
	echo '<img src="img/qrimg/connect.png" width="400px"/><br>';
}
elseif ($stat == "SERVICE_OFF") {
	echo '<img src="img/qrimg/disconnect.png" width="400px"/><br>';

	$curl = curl_init();
	curl_setopt_array($curl, array(
	  CURLOPT_URL => $data['url_whatsapp_gateway'].'serviceStart',
	  CURLOPT_RETURNTRANSFER => true,
	  CURLOPT_ENCODING => '',
	  CURLOPT_MAXREDIRS => 10,
	  CURLOPT_TIMEOUT => 0,
	  CURLOPT_FOLLOWLOCATION => true,
	  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	  CURLOPT_CUSTOMREQUEST => 'GET',
	  CURLOPT_POSTFIELDS => 'apiKey='.$data['apikey_whatsapp'],
	));
	$response = curl_exec($curl);
	curl_close($curl);
}
elseif ($stat == "SERVICE_SCAN" ) {
	$curl = curl_init();

	curl_setopt_array($curl, array(
	  CURLOPT_URL => $data['url_whatsapp_gateway'].'getQR',
	  CURLOPT_RETURNTRANSFER => true,
	  CURLOPT_ENCODING => '',
	  CURLOPT_MAXREDIRS => 10,
	  CURLOPT_TIMEOUT => 0,
	  CURLOPT_FOLLOWLOCATION => true,
	  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	  CURLOPT_CUSTOMREQUEST => 'GET',
	  CURLOPT_POSTFIELDS => 'apiKey='.$data['apikey_whatsapp'],
	  CURLOPT_HTTPHEADER => array(
	    'Content-Type: application/x-www-form-urlencoded'
	  ),
	));

	$response = curl_exec($curl);

	curl_close($curl);
	$dataArray = json_decode($response, true);
	$dataqr = $dataArray['results']['qrString'];
	echo '<img src="'.$dataqr.'" width="400px"/><br>';
}
else{
	echo '<img src="img/qrimg/map_loader.gif" width="400px"/><br>';
}
echo "</center>";
// echo "<pre>";
// print_r($dataArray);
?>
<script>
    document.getElementById('time').innerText = new Date().toLocaleTimeString();
</script>