<?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/item_sales.php';
include_once '../objects/item_sales_detail.php';

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

$database = new Database();
$db = $database->getConnection();
 
$item_sales = new ItemSales($db);
$item_sales_detail = new ItemSalesDetail($db);
$data = json_decode(file_get_contents("php://input"));

$item_sales->sales_date = $data->sales_date;
$item_sales->voucher_no= $item_sales->getGenerateVoucherNo(date("ym-"));
$item_sales->store = $data->store;
// $item_sales->voucher_no = $data->voucher_no;
$item_sales->invoice_no = $data->invoice_no;
$item_sales->name = $data->name;
$item_sales->total_amount = $data->total_amount;
$item_sales->discount = $data->discount;
$item_sales->payment = $data->payment;
$item_sales->entry_by = isset($_SESSION['user'])?$_SESSION['user']:"";
$item_sales->entry_date_time = date("Y-m-d H:i:s");

$item_sales_detail->sales_date = $data->sales_date;
$item_sales_detail->voucher_no= $item_sales->voucher_no;

if($data->vno){
	$item_sales->voucher_no = $data->vno;
	$item_sales_detail->voucher_no = $data->vno;
	if(!$item_sales->update()){
		$msg_arr = array(
			"message" => "error",
			"table" => "update"
			);
		echo json_encode($msg_arr);
	}else{
		$item_sales_detail->delete();
	}
}else{
	if(!$item_sales->create()){
			$msg_arr = array(
			"message" => "error",
			"table" => "create",
			"sales_id" => $item_sales->id
			);
		echo json_encode($msg_arr);
		die();
	}
}

foreach($data->sales_details as $p_detail){
	
    $item_sales_detail->item_code = $p_detail->item_code;
    $item_sales_detail->item_name = $p_detail->item_name;
	$item_sales_detail->store = $data->store;
	$item_sales_detail->quantity = $p_detail->quantity;
	$item_sales_detail->price = $p_detail->price;

	if(!$item_sales_detail->create()){
		$msg_arr = array(
			"message" => "error",
			"table" => "sales_detail"
		);
		echo json_encode($msg_arr);
		die();
	}
}

if($data->vno){
	$v=$data->vno;
}else{
	$v=$item_sales->voucher_no;
}

$msg_arr = array(
	"message" => "created",
	"vno" => $v
);
echo json_encode($msg_arr);

?>