<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once '../config/database.php';
include_once '../objects/item.php'; 

session_start();
date_default_timezone_set('Asia/Rangoon');

$database = new Database();
$db = $database->getConnection();

$item = new Item($db);

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

$item->id = $data->id;
$item->category_code = $data->category_code;
$item->category = $data->category; 
$item->type_code = $data->type_code;
$item->type = $data->type;
$item->item_code = $data->item_code;
$item->item_name = $data->item_name;
$item->barcode = $data->barcode;
$item->capital_price = isset($data->capital_price) ? $data->capital_price : 0;
$item->sales_price = isset($data->sales_price) ? $data->sales_price : 0;
$item->supplier = $data->supplier;
$item->entry_by = isset($_SESSION['userid']) ? $_SESSION['userid'] : "";
$item->update_by = isset($_SESSION['userid']) ? $_SESSION['userid'] : "";

if ($data->id) {
    if ($item->update()) {
        echo json_encode(array("message" => "updated"));
    } else {
        echo json_encode(array("message" => "error"));
    }
} else {
    if ($item->exist()) {
        echo json_encode(array("message" => "duplicate"));
    } elseif ($item->create()) {
        echo json_encode(array("message" => "created"));
    } else {
        echo json_encode(array("message" => "error"));
    }
}
?>
