<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<?php
ini_set('display_errors', '1');

require_once("phpMQTT.php");
require_once("Mysql.php");

$mqtt = new phpMQTT("localhost", 1884, "MAT-PHPSERVER"); //Change client name to something unique


if(!$mqtt->connect()){
	exit(1);
}


$topics['esp/topic'] = array("qos"=>0, "function"=>"procmsg");
$mqtt->subscribe($topics,0);


while(1){
	$mqtt->proc();	
}

$mqtt->close();
           

function procmsg($topic,$msg){
		$m = new Mysql();    
    
    //OCESANI O NADBYTECNE ZNAKY     
    for ($i = 0; $i <= 31; ++$i) { 
      $msg = str_replace(chr($i), "", $msg); 
    }
    $msg = str_replace(chr(127), "", $msg);     
    if (0 === strpos(bin2hex($msg), 'efbbbf')) {
      $msg = substr($msg, 3);
    }
    $msg_stripped = $msg;      
    
    echo $msg_stripped;
    
    //DEKODOVANI Z JSON FORMATU
    $msg_decoded = json_decode( $msg_stripped, true, 9);
    var_dump ($msg_decoded);
    
    if($msg_decoded["mysql"] == "identifikace"){
        $sql = "SELECT * FROM `uzivatele` WHERE card LIKE ".$msg_decoded["card"]."";
        $mysql_result = $m->dotaz($sql) or die('Query failed: ' . mysql_error());
        $msg_to_send = array("CHIP_ID" => 0, "card" => 0);
        $msg_to_send["CHIP_ID"] = $msg_decoded["CHIP_ID"];
      
      if ($m->pocetRadku($mysql_result)==1) {
			  $data = $m->podejRadek($mysql_result);      
        $msg_to_send["card"] = $msg_decoded["card"];
        if($msg_decoded["way"] == "in"){
          $user = (string)$data->user;
          $sql = "INSERT INTO `pohyb` (`user`, `action`) VALUES (".$user." , 1)";
          echo ($user);
          echo ($sql);
          $m->dotaz($sql);
        }else if($msg_decoded["way"] == "out"){
          $user = (string)$data->user;
          $sql = "INSERT INTO `pohyb` (`user`, `action`) VALUES (".$user." , 0)"; 
                 
          $m->dotaz($sql);
        }       	  
      }else{
        $msg_to_send["card"] = 0;  
      }
        var_dump($msg_to_send);
        shell_exec("mosquitto_pub -h localhost -q 0 -i MAT- -t set/topic -m \"{\"CHIP_ID\":".$msg_to_send["CHIP_ID"].",\"card\":".$msg_to_send["card"]."}\"");
        $msg_to_send_encoded = json_encode($msg_to_send);
        var_dump($msg_to_send_encoded);
			  $mqtt->publish("card/topic",$msg_to_send_encoded,0);
      
      	
    }
    else if($msg_decoded["mysql"] == "zasuvky_data"){
      $sql = "SELECT `date` FROM `zasuvky_data` ORDER BY `ID` DESC LIMIT 1";      
		  $mysql_result = $m->dotaz($sql) or die('Query failed: ' . mysql_error());
      
      if ($m->pocetRadku($mysql_result)==1) {
			   $data = $m->podejRadek($mysql_result);
			   $datumdb = $data->date;      			
      
        if((date("H",time()) - date("H",strtotime($datumdb))) >= 1 OR (date("i",time()) - date("i",strtotime($datumdb))) >= 1){
		      $ins = "INSERT INTO ".$msg_decoded["mysql"]." (`CHIP_ID`, `current`) VALUES (".$msg_decoded["CHIP_ID"]." ,".$msg_decoded["current"].")";
		      $m->dotaz($ins);
          var_dump($ins);
        }
      }
    }
    
    else if($msg_decoded["value_name"] == "temp"){
        $msg_decoded["value"] = $msg_decoded["value"] / 10000;
        $temp = number_format($msg_decoded["value"], 2, '.', '');
        $ins = "INSERT INTO ".$msg_decoded["mysql"]." (`CHIP_ID`, ".$msg_decoded["value_name"].") VALUES (".$msg_decoded["CHIP_ID"]." ,".$temp.")";
		    $m->dotaz($ins);
      }
    else if($msg_decoded["mysql"] == "spotreba"){
      $sql = "SELECT `kwh` FROM `spotreba` ORDER BY `ID` DESC LIMIT 1";      
		  $mysql_result = $m->dotaz($sql) or die('Query failed: ' . mysql_error());
      if ($m->pocetRadku($mysql_result)==1) {
			$data = $m->podejRadek($mysql_result);
			$kwh = $data->kwh;
      $kwh = $kwh + 250;
			
		  $ins = "INSERT INTO ".$msg_decoded["mysql"]." (`CHIP_ID`, ".$msg_decoded["value_name"].", `napeti_bat`) VALUES (".$msg_decoded["CHIP_ID"]." ,".$kwh.", ".$msg_decoded["napeti_bat"].")";
		  $m->dotaz($ins);
      }
    }  
}


?>