<?php

require_once 'chat-api/src/whatsprot.class.php';
//Change the time zone if you are in a different country
date_default_timezone_set('America/Sao_Paulo');
#5511941681671
#Hu2sYKmZT7xxeFU6BbQGgk4Q9l0=

$username = '55119416716681;
$password = 'Hu2sYKmZT7xxeFU6BbQGgk4Q9l0=';
$nickname = 'Xymon';
$debug = false;

function logger($message) {
	$data= date("d-m-y");
	$hora = date("H:i:s");
	$ip = $_SERVER['REMOTE_ADDR'];
	 
	//Nome do arquivo:
	$arquivo = "/var/www/sites/whatsapp/whatsapp.log";
	 
	//Texto a ser impresso no log:
	$texto = "[$hora][$ip]> $message \n";
	 
	$manipular = fopen("$arquivo", "a");
	fwrite($manipular, $texto);
	fclose($manipular);
 
}

if (php_sapi_name() == "cli") {
	// Linha usada para funcionar pelo cli do PHP
	parse_str(implode('&', array_slice($argv, 1)), $_POST); // Linha usada para funcionar pelo cli do PHP
} 

$dst = $_POST['phone'];
$msg = str_replace("|","&",$_POST['msg']);
#$msg = $_POST['msg'];
$color = $_POST['color'];
$recovered = $_POST['recovered'];

$CMR=$msg;

logger($CMR);

switch ($recovered) {
        case "1":
                $color="green";
                break;
        case "0":
                $color=$_POST['color'];
}

switch ($color) {
        case "red":
                $CMR = "\xF0\x9F\x86\x98 \n" . $msg;               // RED (emoji SOS)
                break;
        case "green":
                $CMR = "\xF0\x9F\x86\x97 \n" . $msg;               // GREEN (emoji OK)
                break;
        case "yellow":
                $CMR = "\xE2\x9A\xA0 \n" . $msg;           // YELLOW (emoji PLACA ALERTA)
                break;
}

$w = new WhatsProt($username, $nickname, $debug);
$w->connect();
$w->loginWithPassword($password);
$w->sendGetServerProperties(); 
$w->sendClientConfig();
$sync = [$dst];
$w->sendSync($sync); // Sincronizamos el contacto
$w->pollMessage(); // Volvemos a poner en cola mensajes
$w->sendPresenceSubscription($dst); // Nos suscribimos a la presencia del usuario

#$pn = new ProcessNode($w, $dst);
#$w->setNewMessageBind($pn);

$w->pollMessage();
$w->sendMessage($dst, $CMR);

#logger($dst . " - " .$CMR);

class ProcessNode
{
    protected $wp = false;
    protected $target = false;

    public function __construct($wp, $target)
    {
        $this->wp = $wp;
        $this->target = $target;
    }

    public function process($node)
    {
        $text = $node->getChild('body');
        $text = $text->getData();
        $notify = $node->getAttribute('notify');

        echo "\n- ".$notify.': '.$text.'    '.date('H:i')."\n";
    }
}


if (php_sapi_name() == "cli") {
	// Linha usada para funcionar pelo cli do PHP
	echo "\nMensagem enviada!!\n";  
} else {
	echo "<BR> <p> Mensagem enviada </p>";
}
?>
