<?

require_once ('DBTable.php');
require_once ('BasicEnum.php');
require_once ('DBFactory.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;
	}

	/**
	 * cancel
	 *
	 * @return true if update successfully, otherwise return false
	 */
	public function cancel($ib_cols, $where){
		try {
			
			$upd_inb = "UPDATE " . $this->__TABLE .
						" SET status = 3 ".
						" , update_user_id = '" . $ib_cols['update_user_id'] . "'" .
						" WHERE id='" . $ib_cols['id'] ."'";
			
			$rows_affected = (new DBFactory())->query($upd_inb);

			//$ib_cols['package_qty'] *= -1;
			//$ib_cols['qty'] *= -1;

			$upd_stock = "UPDATE Stock " .
							" SET qty = qty - " . $ib_cols['qty'] .
							" , update_user_id = '" . $ib_cols['update_user_id'] . "'" .
							" WHERE item_id='" . $ib_cols['item_id'] . "'" .
							"   AND item_dvsn_id=" . $ib_cols['item_dvsn_id'] .
							"   AND customer_id='" . $ib_cols['customer_id'] . "'".
							"   AND customer_dvsn_id='" . $ib_cols['customer_dvsn_id']. "'";

			$rows_affected = (new DBFactory())->query($upd_stock);

			$qty_cancel = $ib_cols['qty'];
			$ib_cols['package_qty'] *= -1;
			$ib_cols['qty'] *= -1;

			$create_dt =  $ib_cols['create_dt']->format('Y-m-d H:i:s');
			unset($ib_cols['create_dt']);

			$ib_cols['create_dt'] = $create_dt;
			$result_stockcard = (new StockCardRecord())->addStockCard_ib($ib_cols)?1:0;


				$year_20yy = substr($create_dt,0,4);
				$month_mm = substr($create_dt,5,2);
				$month_cur = date('m');
				if( $month_mm==$month_cur){
					// is current month not cal it will cal on last day of month
				}else{
					$sql_forecast = "SELECT * FROM StockCardForecast WHERE itemforecast_id='".$ib_cols['item_id']."' AND month_mm='".$month_mm."' AND year_20yy='".$year_20yy."'";
					$StockCardForecasts = (new DBFactory())->query($sql_forecast);
					if( isset($StockCardForecasts[0]) ){
						$row_StockCardForecast = $StockCardForecasts[0];
						$after_upd_current_stock = $row_StockCardForecast['current_stock']-$qty_cancel;
						$status_of_deli_1to15 = $after_upd_current_stock / $row_StockCardForecast['forecast_per_day'];

						if($status_of_deli_1to15<1){
							$status_of_deli_1to15 = 1;
						}

						if($status_of_deli_1to15>15){
							$status_of_deli_1to15 = 15;
						}

						$upd_forecast = "UPDATE StockCardForecast " .
										" SET current_stock=".$after_upd_current_stock. " , " .
										"     status_of_deli_1to15=".$status_of_deli_1to15. " ". 
										" WHERE id=".$row_StockCardForecast['id']." ";
						$rows_affected = (new DBFactory())->query($upd_forecast);
					}
				}
			

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