<?php
// required headers
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/purchase.php';
include_once '../objects/purchase_detail.php';
include_once '../objects/item.php';

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

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

$purchase = new Purchase($db);
$purchase_detail = new Purchase_Detail($db);
$item = new Item($db);

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

$purchase->date = $data->date;
$purchase->voucher_no = $data->voucher_no;
$purchase->supplier = $data->supplier;
$purchase->entry_by = $_SESSION['user'];

if(!$purchase->exist()){
	if($purchase->create()){
		  	foreach($data->purchase_details as $items){
		  		$purchase_detail->purchase_id = $purchase->id;
		  		$purchase_detail->item_code = $items->item_code;
		  		$purchase_detail->item_name = $items->item_name;
				$purchase_detail->quantity = $items->quantity;
				$purchase_detail->price = $items->price;
				if(!$purchase_detail->create()){
					$arr = array(
						"message" => "error1"
					);
					echo json_encode($arr);
					die();
				}

				$item->item_code = $items->item_code;
				$item->capital_price = $items->price;

				$item->updateCapital();
				$arr = array(
					"message" => "created",
				);
			}
	}else{
	  	$arr = array(
			"message" => "error",
		);
	}
}else{
	$arr = array(
		"message" => "duplicate",
	);
}
echo json_encode($arr);
?>