<?php
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);

// Must have a code and password field
$fp = fopen('.htpassajax', 'r');
$password = trim(fread($fp, filesize('.htpassajax')));
fclose($fp);

if ($_POST["password"] != $password)
    die("Wrong Password");

// open the file and get the stock
$file = '../data/stock-v2.json';
$fp = fopen($file, 'r');
$result = json_decode(fread($fp, filesize($file)));
fclose($fp);

$returnVal = 'N/A';

// Get the price from the given code and remove 1 in quantity. Do not get the price if quantity is at 0
foreach ($result->articles as $articleObject) {
    if ($articleObject->code === $_POST["code"] && intval($articleObject->quantity) > 0) {
        $returnVal = $articleObject->name . "\n". $articleObject->price . "€";
        $articleObject->quantity = strval(intval($articleObject->quantity) - 1);
    }
}

// open the file and write the updated stock
$fp = fopen('../data/stock.json', 'w');
fwrite($fp, json_encode($result));
fclose($fp);

echo $returnVal;

