//header('Content-Type: text/html; charset=utf-8');
date_default_timezone_set('Asia/Bangkok');
$date = date('Y-m-d H:i:s');
ini_set('max_execution_time', 300);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$barcode = $_POST['barcode'];
$store = $_POST['store'];
}
else
{
$barcode = $_GET['barcode'];
$store = $_GET['store'];
}
if(!is_numeric($barcode))
exit;
include("connect.php");
mysqli_query($mysqli,"SET character_set_results=utf8");
mysqli_query($mysqli,"SET character_set_client=utf8");
mysqli_query($mysqli,"SET character_set_connection=utf8");
$barcode11 = substr($barcode,0,11);
if(strlen($store)>0)
{
$result = $mysqli->query("SELECT * FROM us_temp WHERE barcode LIKE '$barcode11' AND store = '$store'");
$num_rows = mysqli_num_rows($result);
if($num_rows==0)
$result = $mysqli->query("SELECT * FROM us_temp WHERE barcode LIKE '$barcode11' ORDER BY ctime DESC");
}
else
{
$result = $mysqli->query("SELECT * FROM us_temp WHERE barcode LIKE '$barcode11' ORDER BY ctime DESC");
}
$num_rows = mysqli_num_rows($result);
if($num_rows>0)
{
$row=mysqli_fetch_row($result);
$productname = $row[1];
$price = $row[2];
$amount = $row[4];
$store = $row[6];
$imageurl = $row[11];
echo $productname."|1|".strval($price)."|2|".$store."|3|".$imageurl;
$amount = $amount+1;
$sql = "UPDATE us_temp SET amount='$amount',ctime = '$date' WHERE barcode LIKE '$barcode11' AND store = '$store'";
if (!mysqli_query($mysqli, $sql))
echo "";
exit;
}
else
{
$url = "https://api.barcodelookup.com/v2/products?barcode=".$barcode."&formatted=y&key=gddlxplez4ml6jwv0r4gdm0ph5xtye";
$data = file_get_contents($url, false, stream_context_create(['http' => ['ignore_errors' => true]]));
if(strlen($data)<2)
exit;
else
{
$response = json_decode($data);
$productname = $response->products[0]->title;
$price = $response->products[0]->stores[0]->store_price;
$store = $response->products[0]->stores[0]->store_name;
$imageurl = $response->products[0]->images[0];
if($price==null)
$price="0";
echo $productname."|1|".strval($price)."|2|".$store."|3|".$imageurl;
$barcode11 = substr($barcode,0,11);
$productname = str_replace("'","`",$productname);
$sql = "INSERT IGNORE INTO us_temp (barcode,productname,price,amount,ctime,store) VALUES ('$barcode11','$productname','$price',1,'$date','$store')";
if (!mysqli_query($mysqli, $sql))
echo "";
}
}
?>