<?

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

final class Outbound extends DBTable
{

	public $__TABLE = 'Outbound';
	public static $__COLUMNS = array(
						'id' 		=> 0,
						'item_id'						=> 0,
						'item_dvsn_id'			=> 0,
						'customer_id'				=> '',
						'customer_dvsn_id'	=> 0,
						'package_type'			=> 0,
						'package_qty'				=> 0,
						'product_date' 			=> '',
						'qty'								=> 0,
						'location_id'				=> 0,
						'location_dvsn_id'	=> 0,
						'status'  					=> 0,
						'slip_divide'  			=> '',
						'create_dt' 				=> '',
						'create_user_id' 		=> 0,
						'update_dt' 				=> '',
						'update_user_id' 		=> 0,
					);

	/**
	 * Insert record with generated ID
	 *
	 * @return generated ID
	 */
	public function add($ob_cols) {
		try {
			$id = parent::add($ob_cols);

			// Update or Add to Stock table
			$ob_cols['update_user_id'] = $ob_cols['create_user_id'];
			$ob_cols['qty'] *= -1;
			$result = (new Stock())->updateQty($ob_cols);

		} catch (Exception $e) {
			$this::$logger->error("Caught exception: " . print_r(sqlsrv_errors(), true));
			return false;
		}

		return $id;
	}

	public function set_($ob_cols, $where, $diff, $old=null) {
		try {
			$rows_affected = parent::set($ob_cols, $where);

			// check Item and Location with original value
			if ($old == null) {
				// Update or Add to Stock table with old key(Item and Location)
				$ob_cols['qty'] = $diff * -1;
				$result = (new Stock())->updateQty($ob_cols);
			} else {
				$this::$logger->debug("Item or Location changed!");
				// Add the qty number with new key
				$ob_cols['qty'] *= -1;
				$result = (new Stock())->updateQty($ob_cols);

				// Deduct an old stock record with its old number
				$ob_cols['qty'] = $old['oqty'];
				$ob_cols['item_id'] = $old['oitem_id'];
				$ob_cols['item_dvsn_id'] = $old['oitem_dvsn_id'];
				$ob_cols['location_id'] = $old['olocation_id'];
				$ob_cols['location_dvsn_id'] = $old['olocation_dvsn_id'];
				$ob_cols['product_date'] = $old['oproduct_date'];
				$result = (new Stock())->updateQty($ob_cols);

			}

		} catch (Exception $e) {
			$this::$logger->error("Caught exception: " . print_r(sqlsrv_errors(), true));
			return false;
		}
		return $rows_affected;
	}

	public function remove($ob_cols) {
		try {
			$rows_affected = parent::remove("id = " . $ob_cols['id']);

			// Update or Add to Stock table
			//$ob_cols['qty'] = $ob_cols['qty'] * -1;
			$result = (new Stock())->updateQty($ob_cols);

		} catch (Exception $e) {
			$this::$logger->error("Caught exception: " . print_r(sqlsrv_errors(), true));
			return false;
		}
		return $rows_affected;
	}
}
