<?

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

final class Inbound extends DBTable
{

	public $__TABLE = 'Inbound';
	public static $__COLUMNS = array(
						'id' 				=> 0,
						'item_id'			=> 0,
						'item_dvsn_id'		=> 0,
						'customer_id'		=> 0,
						'customer_dvsn_id'	=> 0,
						'supplier_id'		=> '',
						'supplier_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,
						'act_type' 			=> '',
					);

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

			// Update or Add to Stock table
			$ib_cols['update_user_id'] = $ib_cols['create_user_id'];
			$result_stockcard = (new StockCardRecord())->addStockCard_ib($ib_cols);
			
			$result = (new Stock())->updateQty($ib_cols);

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

		return $id;
	}

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

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

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

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

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

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

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