<?

require_once ('DBTable.php');
require_once ('BasicEnum.php');
require_once ('Util.php');

final class Stock extends DBTable
{

	public $__TABLE = 'Stock';
	public static $__COLUMNS = array(
						'item_id'						=> '',
						'item_dvsn_id'			=> 0,
						'location_id'  			=> '',
						'location_dvsn_id'  => 0,
						'product_date' 			=> '',
						'carry_over'				=> 0,
						//'stocktaking'				=> 0,
						//'stocktaking_status'	=> 0,
						'qty'								=> 0,
						'create_dt' 				=> '',
						'create_user_id' 		=> 0,
						'update_dt' 				=> '',
						'update_user_id' 		=> 0,
						'customer_id'						=> '',
						'customer_dvsn_id'			=> 0,
					);


	/**
	 * Update stock quantity
	 *
	 * @return true if update successfully, otherwise return false
	 */
	public function updateQty($data)
	{
		$sql = "UPDATE " . $this->__TABLE .
			" SET qty = qty " . ($data['qty']>0?"+":"-") . abs($data['qty']) .
			" , update_user_id = '" . $data['update_user_id'] . "'" .
			" WHERE item_id='" . $data['item_id'] . "'" .
			"   AND item_dvsn_id=" . $data['item_dvsn_id'] .
			"   AND location_id='" . $data['location_id']. "'" .
			"   AND location_dvsn_id=" . $data['location_dvsn_id'] .
			"   AND product_date='" . $data['product_date']. "'".
			"   AND customer_id='" . $data['customer_id'] . "'".
			"   AND customer_dvsn_id='" . $data['customer_dvsn_id']. "'"
			;

		$this::$logger->debug("SQL: " . $sql);
		$stmt = sqlsrv_query( $this::$db->getInstance(), $sql );
		$rows_affected = sqlsrv_rows_affected( $stmt);
		if( $rows_affected === false) {
     	$this::$logger->error("Caught exception: " . print_r(sqlsrv_errors(), true));
		} elseif( $rows_affected == -1) {
      $rows_affected = 0;
		} else {
      $this::$logger->debug($rows_affected." rows were updated.");
		}

		// if update failed try to insert new record
		if (!$rows_affected) {
			$stock_cols = $this::$__COLUMNS;
			// remove unwant data
			$unsets = ['create_dt', 'update_dt', 'update_user_id', 'carry_over', 'stocktaking', 'stocktaking_status'];
			foreach ($unsets as $u) unset($stock_cols[$u]);

			$stock_cols = Util::parseArrayData($stock_cols, $data);
			if (array_key_exists('update_user_id', $data))
				$stock_cols['create_user_id'] = $data['update_user_id'];
			//$this::$logger->debug(print_r($stock_cols, true));
			$rows_affected = $this->add($stock_cols) ? 1 : 0;
		}


		return $rows_affected;
	}
}


abstract class StocktakingStatus extends BasicEnum {
  const REGISTRATION = 0;
  const CONFIRMED  = 1;
}
