<?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);
    }
		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);
			$conn->beginTransaction();
			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);
				}
				
				if (!$conn->commit()) {
					$conn->rollback();
					$sql="delete from push_key where qkey = '$key' and date = '$dt'";
			        $conn->exec($sql);
					exit();
				}
				
				echo "Sucesfull $key";
			}
			catch(PDOException $e)
			{
				$conn->rollback();
				$sql="delete from push_key where qkey = '$key' and date = '$dt'";
			    $conn->exec($sql);
				echo "NonQueryError  $q " . $e->getMessage();
			}
		}
		else
		{
			echo "Already $key";
		}
	}

?>