<?php
	header('Content-Type: text/html; charset=utf-8');
	include "logger.php";
	include "settings.php";
	
	$db = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
    $db->query("SET CHARSET SET utf8");
    $db->query("SET NAMES 'utf8'");
    if (mysqli_connect_errno()) {
        echo "Error connecting to DB";
		writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> synchroxml <> "Error connecting to DB"');
        exit;
    }
	
	$json = file_get_contents('php://input');
	
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> file_get_contents license <> '.$json );
	
	$data = stripslashes($json);
	$arraydata = (array)json_decode($data);
	
	$licenceKey = trim($arraydata["licenceKey"]);
	$btmac = $arraydata["btmac"];
	$wifimac = $arraydata["wifimac"];
	$deviceID = $arraydata["deviceID"];
	$imei = $arraydata["imei"];
	//{"licenceKey":"865233020144706","btmac":"00000000","wifimac":"14:9f:e8:16:64:57","deviceID":"b1d58a3a204772d2","imei":"863156020912230"}
	
	
	
	$state = false;
	$query = "SELECT `key`,`hash`,`date` FROM `wm_license` WHERE `key` = '".$licenceKey."';";
	writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> license query <> '.$query);
	if($stmt = $db->prepare($query)){
    if($stmt->execute()){
	$stmt->bind_result($key,$hash,$date);
    //$stmt->store_result();
	//if($stmt->num_rows()>0){
	$stmt->fetch();
	
		$hashnew = md5($btmac.$wifimac.$deviceID.$imei.time());
		writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> license hashnew <> '.$hashnew);
		if($key == $licenceKey){ 
			$state = true;
			echo json_encode(array("success" => true, "message" => $hashnew));
			writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> license key==licenceKey ');
		}else{
			echo json_encode(array("success" => false, "message" => 'Лицензионный ключ проверку не прошел'));
			writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> license key!=licenceKey ');
		}

	//}else{ writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> license num_rows empty'); }
	$stmt->close();
    }else{ writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> license error <> '.$db->errno . ' ' . $db->error); }
	}else{ writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> license error <> '.$db->errno . ' ' . $db->error); }
    
	if($state == true){
		$query = "UPDATE `wm_license` SET hash = '".$hashnew."', btmac = '".$btmac."', wifimac = '".$wifimac."', deviceID = '".$deviceID."', imei = '".$imei."'  WHERE `key` = '".$licenceKey."';";
		writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> license query <> '.$query);
		if($stmt = $db->prepare($query)){
		if($stmt->execute()){
			$stmt->close();
		}else{ writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> license error <> '.$db->errno . ' ' . $db->error); }
		}else{ writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> license error <> '.$db->errno . ' ' . $db->error); }
	}
	
	
	
	$db->close();
	exit;
	
	
?>