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

session_start();
date_default_timezone_set('Asia/Rangoon');
$database = new Database();
$db = $database->getConnection();
 
$stock_transfer = new StockTransfer($db);
$stock_balance = new StockBalance($db);
$data = json_decode(file_get_contents("php://input"));
    
$stock_transfer->stock_transfer_date = $data->stock_transfer_date;
$stock_transfer->store_from = $data->store_from;
$stock_transfer->store_to = $data->store_to;
$stock_transfer->item_code = $data->item_code;
$stock_transfer->item_name = $data->item_name;
$stock_transfer->quantity = $data->quantity;
$stock_transfer->stock_transfer_by = $data->transfer_by;
$stock_transfer->remark = $data->remark;
$stock_transfer->entry_by = isset($_SESSION['user'])?$_SESSION['user']:"";
$stock_transfer->entry_date_time = date("Y-m-d H:i:s");

$stock_balance->stock_balance_date = $stock_transfer->stock_transfer_date;
$stock_balance->item_code = $stock_transfer->item_code;
$stock_balance->item_name = $stock_transfer->item_name;
$stock_balance->store = $stock_transfer->store_to;
$stock_balance->quantity =0;
// $stock_balance->plus = 1;

// if($stock_balance->checkMaterialForStockOut()){
    // $tf = $stock_balance->updateFromStockTransfer();
// }else{
// 	echo "not enough";
// 	 die();
// }

// if($data->stock_transfer_date < date("Y-m-d")){
//     $stock_balance->plus = 0;
//     $tf = $stock_balance->updateFromStockTransferOut();

//     $stock_balance->store = $stock_transfer->store_to;
//     $stock_balance->quantity = $stock_transfer->quantity;
//     $stock_balance->plus = 1;

//     if($stock_balance->checkMaterial()){
//         $tf = $stock_balance->updateFromStockTransferIN();
//     }else{
//         $tf = $stock_balance->create();
//     }
  
// }

  
// if($tf){
if($stock_transfer->create()){
    if($stock_balance->checkMaterial()){
        // if($stock_balance->updateFromStockIn()){
        // }    
    }else{
        $stock_balance->createSB();  
    }
    echo 'created';

}else{
    echo 'error';
}
// }else{
//     echo 'error';
// }

?>