<?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"));
$nfc = $postData->id;

date_default_timezone_set("Asia/Kuala_Lumpur");

$appno = "LM".strtotime("now");
$status = "0";


$tarikh = date("D M d, Y G:i");
//$tarikh = date("d/m/Y G:i");


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

$query = "INSERT INTO coas (appno, status, nfc, manu, tarikh_mohon) 
            SELECT * FROM (SELECT '" .$appno. "' as appno, '" .$status. "' as status, '" .$nfc. "' as nfc, '" .$manu. "' as manu, '" .$tarikh. "' as tarikh_mohon) AS tmp
            WHERE NOT EXISTS (
                SELECT id FROM coas WHERE nfc = '" .$nfc. "' AND manu = '" .$manu. "' and status = '" .$status. "' 
            ) LIMIT 1; ";

            
if ($mysqli->query($query) === true) {

    $count = $mysqli->affected_rows;
    //echo "Success: Record saved. [".$query."] ".$count;
    $data[] = array('appno' => $appno, 'status' => $status, 'tarikh' => $tarikh);
    $result = json_encode($data);

    http_response_code(200);
} else {
    $data[] = array('error' => "Error: Process failed - " .$mysqli->error);
    http_response_code(500);
    $result = json_encode($data);
}


$mysqli->close();
//var_dump(json_decode(file_get_contents("php://input")));

echo $result;

?>