<?php
require_once ("varables.php");

$myJSON = 0;
if(isset($_POST["nekot"]) && isset($_POST["json"]))
{

	$postdata = $_POST["json"];
	$products = json_decode($postdata,true);
	$toke = $_POST["nekot"];
if($toke == "sldiskdjgsoewmvmdpekdjghsncusi"){
    $connect = @mysqli_connect($hostname,$username,$password,$database);
    if($connect)
    {
        @mysqli_query($connect,"SET CHARACTER SET utf8;");

					for($i=0;$i<sizeof($products);$i++){
						$select_query = "SELECT id FROM ".$tbl_products." WHERE P_id ='".$products[$i]["P_id"]."'";
							$res =@mysqli_query($connect,$select_query);
							if(!$res){
								$myJSON = 401;
									echo $myJSON;
								return;
							}
							else {
								$count=0;
								while($row = @mysqli_fetch_assoc($res)){
									$count++;
								}
								if($count == 0){
										$insert_query= "INSERT INTO ".$tbl_products." (P_name,Price,Price_1,Price_s1,Stack,P_id,P_Code,P_comment0,maxo,date,vahed,up)
											VALUES ('".$products[$i]["P_name"]."','".$products[$i]["P_price"]."','".$products[$i]["Price_1"]."','".$products[$i]["P_price1"]."','".$products[$i]["P_stack"]."','".$products[$i]["P_id"]."','".$products[$i]["P_Code"]."','".$products[$i]["P_Comment"]."','0','".$products[$i]["date"]."','".$products[$i]["unit"]."','".$products[$i]["up"]."')";
								
											$insres =@mysqli_query($connect,$insert_query);
											if(!$insres){
											$myJSON = @mysqli_error($connect);
											  echo $myJSON;
											return;
										}
								}
								else{
							//		$update_query= "UPDATE ".$tbl_products." SET P_name = '".$products[$i]["P_name"]."', Price = '".$products[$i]["P_price"]."', up = '".$products[$i]["up"]."', vahed = '".$products[$i]["unit"]."', Stack = '".$products[$i]["P_stack"]."', P_comment0 = '".$products[$i]["P_Comment"]."',P_Code= '".$products[$i]["P_Code"]."',date = '".$products[$i]["date"]."',Price_1= '".$products[$i]["Price_1"]."',Price_s1= '".$products[$i]["P_price1"]."' WHERE P_id ='".$products[$i]["P_id"]."'";
									$update_query= "UPDATE ".$tbl_products." SET P_name = '".$products[$i]["P_name"]."', Price = '".$products[$i]["P_price"]."', vahed = '".$products[$i]["unit"]."', Stack = '".$products[$i]["P_stack"]."', P_comment0 = '".$products[$i]["P_Comment"]."',P_Code= '".$products[$i]["P_Code"]."',date = '".$products[$i]["date"]."',Price_1= '".$products[$i]["Price_1"]."',Price_s1= '".$products[$i]["P_price1"]."' WHERE P_id ='".$products[$i]["P_id"]."'";
										$upres =@mysqli_query($connect,$update_query);
										if(!$upres){
										$myJSON = @mysqli_error($connect);
											echo $myJSON ;// @mysqli_error($connect);// json_encode($myJSON);
										return;
								}
							}
				}
			}
				$myJSON = 200;
		}
	}
	 else
		 $myJSON = 405;
}
    echo $myJSON;

?>
