<?php

	include 'cnxdata';

	$data = file_get_contents("php://input");
	$data = json_decode($data);
	$data = (array) $data; 
	$size=$data['size'];
	$key=$data['key'];
	$deviceid=$data['deviceid'];
	$motive=$data['motive'];
	$error=0;
	$dt = new DateTime();	
	$dt = $dt->format('Y-m-d H:i:s');
		
	try {
		$conn = new PDO("mysql:host=$servername;dbname=$DB", $username, $password);
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$conn->setAttribute(PDO::ATTR_TIMEOUT, 500);
    }
		catch(PDOException $e)
    {
		echo "ConnectionError " . $e->getMessage();
		$error=1;
	}
	
	if ($error == 0)
	{	
		$sql = "SELECT count(qkey) as c FROM push_key where qkey='$key'";
		
		foreach ($conn->query($sql) as $row) {
			$count = $row["c"];
		}

			
		if ($count == 0){		
			
			$sql="insert into push_key (qkey,date,device,motive) values('$key','$dt','$deviceid','$motive')";
			$conn->exec($sql);

			try {
				for ($i = 0; $i <= $size - 1; $i++) {
					$q=$data['Data' . $i];
					$q = mb_convert_encoding($q, "ISO-8859-1", "UTF-8");
					$conn->exec($q);
				}
				echo "Sucesfull $key";
			}
			catch(PDOException $e)
			{
				echo "NonQueryError  $q " . $e->getMessage();
			}
		}
		else
		{
			echo "Already $key";
		}
	}
?>