<?php
header('Access-Control-Allow-Origin: *');
session_start();

if (!$_SESSION["manu"]) {
    http_response_code(401);
    die();
}

$manu = $_SESSION["manu"];

//var_dump(json_decode(file_get_contents("php://input")));
//$postData = json_decode(file_get_contents("php://input"));

//$mysqli = new mysqli("localhost", "afxtech1_myori", "myori2017", "afxtech1_myori");
include_once("db_connect.php");
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
} 


//Fist, check if we have any file sent to the script:
$file = isset($_FILES['namefile']) ? $_FILES['namefile'] : NULL;
$nfc = isset($_POST['id']) ? $_POST['id'] : NULL;
$photo = isset($_POST['photo']) ? $_POST['photo'] : NULL;
    
//It seems we have a file?
$tmpfile = $file['tmp_name'];
//Find the file extension:
$fileparts = explode('.', $file['name']);

//Apply the extension, usually the last item in the parts array:
$fileExtension = $fileparts[count($fileparts) - 1];


$type = pathinfo($tmpfile, PATHINFO_EXTENSION);
$data = file_get_contents($tmpfile);
$base64 = 'data:image/' . $fileExtension . ';base64,' . base64_encode($data);


//Make a filename:
$filename = md5($file['name']);

//add file extension to the filename:
$filename .= '.' . $fileExtension;

//Save to current directory:
$saveto = __DIR__ . DIRECTORY_SEPARATOR . "uploaded/" . $filename;

//Move file:
move_uploaded_file($tmpfile, $saveto);

///If we ever get here, the file has been uploaded, saved and moved to the permanent location
//print 'File saved to: ' . $base64;
//print $base64;

$query = $photoo;
if ($photo === '1'){
    $query = "UPDATE items SET photo = '". $base64 ."' WHERE manu = '" .$manu. "' AND nfc = '" .$nfc. "' ";    
}
if ($photo === '2'){
    $query = "UPDATE items SET photo2 = '". $base64 ."' WHERE manu = '" .$manu. "' AND nfc = '" .$nfc. "' ";    
}
if ($photo === '3'){
    $query = "UPDATE items SET photo3 = '". $base64 ."' WHERE manu = '" .$manu. "' AND nfc = '" .$nfc. "' ";    
}
if ($photo === '4'){
    $query = "UPDATE items SET photo4 = '". $base64 ."' WHERE manu = '" .$manu. "' AND nfc = '" .$nfc. "' ";    
}

if ($mysqli->query($query) === true) {
//echo "Success: Record updated. [".$query."]";
print $base64;
http_response_code(200);
} else {
echo "Error: Process failed - " . $mysqli->error . "[".$query."]";
http_response_code(401);
}


/*
echo "Success: Record updated. [".$query."]";
http_response_code(200);
*/
$mysqli->close();


?>