<?php
/**********************************************************************
    Copyright (C) FrontAccounting, LLC.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************/

function add_stock_adjustment($items, $location, $date_, $reference, $memo_, $file_system='')
{
	global $SysPrefs, $path_to_root, $Refs;

	begin_transaction();
	$args = func_get_args();
	$args = (object)array_combine(array('items', 'location', 'date_', 'reference', 'memo_', 'file_system'), $args);
	$args->trans_no = 0;
	hook_db_prewrite($args, ST_INVADJUST);

	$adj_id = get_next_trans_no(ST_INVADJUST);

	if ($SysPrefs->loc_notification() == 1)
	{
		include_once($path_to_root . "/inventory/includes/inventory_db.inc");
		$st_ids = array();
		$st_names = array();
		$st_num = array();
		$st_reorder = array();
	}
	foreach ($items as $line_item)
	{

		if ($SysPrefs->loc_notification() == 1 && $line_item->quantity < 0)
		{
			$chg = $line_item; $chg->quantity= -$chg->quantity;	// calculate_reorder_level expect positive qty
			$loc = calculate_reorder_level($location, $chg, $st_ids, $st_names, $st_num, $st_reorder); 
		}

		add_stock_adjustment_item($adj_id, $line_item->stock_id, $location, $date_, $reference,
			$line_item->quantity, $line_item->standard_cost, $memo_, $line_item->batch_no, $line_item->exp_date, $file_system, $line_item->pack_size, $line_item->pack_unit, 
			$line_item->no_of_pack);
	}

	add_comments(ST_INVADJUST, $adj_id, $date_, $memo_);

	$Refs->save(ST_INVADJUST, $adj_id, $reference);
	add_audit_trail(ST_INVADJUST, $adj_id, $date_);

	$args->trans_no = $adj_id;
	hook_db_postwrite($args, ST_INVADJUST);
	commit_transaction();
	if ($SysPrefs->loc_notification() == 1 && count($st_ids) > 0)
		send_reorder_email($loc, $st_ids, $st_names, $st_num, $st_reorder);

	return $adj_id;
}

//-------------------------------------------------------------------------------------------------------------

function void_stock_adjustment($type_no)
{
	hook_db_prevoid(ST_INVADJUST, $type_no);
	void_gl_trans(ST_INVADJUST, $type_no);
	void_stock_move(ST_INVADJUST, $type_no);
	void_adjustment_bag_items($type_no);
}

//-------------------------------------------------------------------------------------------------------------

function get_stock_adjustment_items($trans_no)
{
	$result = get_stock_moves(ST_INVADJUST, $trans_no);

	if (db_num_rows($result) == 0)
	{
		return null;
	}

	return $result;
}


function void_adjustment_bag_items($trans_no)
{
	$sql="DELETE FROM ".TB_PREF."adjustment_bag WHERE trans_no=".db_escape($trans_no);
	db_query($sql,"could not delete adjustment bag");
}

//--------------------------------------------------------------------------------------------------

function add_stock_adjustment_item($adj_id, $stock_id, $location, $date_, $reference, $quantity, $standard_cost, $memo_, $batch_no=null, $exp_date=null, $file_system='', $pack_size=0,
	$pack_unit=null, $no_of_pack=0){

	if($pack_size > 0){
		$sql = "INSERT INTO ".TB_PREF."adjustment_bag (trans_no, stock_id, batch_no, pack_size, pack_unit,
		no_of_pack) VALUES (".db_escape($adj_id) . ", ".db_escape($stock_id) . ", ".db_escape($batch_no) . ",".db_escape($pack_size) . ", ".db_escape($pack_unit) . ", ".db_escape($no_of_pack) . ")";
   		db_query($sql,"The adjustment bag could not be added");
	}

	$mb_flag = get_mb_flag($stock_id);

    if (is_service($mb_flag))
    {
    	display_db_error("Cannot do inventory adjustment for Service item : $stock_id", "");
    }

	update_average_material_cost(null, $stock_id, $standard_cost, $quantity, $date_);

	if (is_fixed_asset($mb_flag)) {
		$sql = "UPDATE ".TB_PREF."stock_master SET inactive=1
			WHERE stock_id=".db_escape($stock_id);
		db_query($sql,"The inactive flag for the fixed asset could not be updated");
	}

	add_stock_move(ST_INVADJUST, $stock_id, $adj_id, $location,   $date_, $reference, $quantity, $standard_cost, $standard_cost, $batch_no, $exp_date, $file_system);

	$inv_value = $standard_cost * $quantity;
	$adj_value = $standard_cost * -($quantity);

	if (is_fixed_asset($mb_flag)) {
		// get the initial value of the fixed assset.
		$row = get_fixed_asset_move($stock_id, ST_SUPPRECEIVE);
		$inv_value = $row['price'] * $quantity;
		$adj_value = (-($row['price']) + $standard_cost) * $quantity;
	}

	if ($standard_cost > 0 || is_fixed_asset($mb_flag))
	{

		$stock_gl_codes = get_stock_gl_code($stock_id);
          $company_record = get_company_prefs();
		add_gl_trans_std_cost(ST_INVADJUST, $adj_id, $date_,
			$company_record['default_adj_act'], $stock_gl_codes['dimension_id'], $stock_gl_codes['dimension2_id'], $memo_, $adj_value  );

		add_gl_trans_std_cost(ST_INVADJUST, $adj_id, $date_, $stock_gl_codes['inventory_account'], 0, 0, $memo_, $inv_value);
	}

	if (is_fixed_asset($mb_flag)) {
		// Additional gl entry for fixed asset.
		$grn_act = get_company_pref('default_loss_on_asset_disposal_act');
		add_gl_trans_std_cost(ST_INVADJUST, $adj_id, $date_, $grn_act, 0, 0, $memo_, ($standard_cost * -($quantity)));
	}
}

function get_adjustment_bag($trans_no)
{
	$sql = "SELECT * FROM ".TB_PREF."adjustment_bag WHERE trans_no=".db_escape($trans_no);
	return db_query($sql,"could not get group");
}

function add_fa_stock_adjustment($items, $location, $date_, $reference, $memo_)
{
	global $SysPrefs, $path_to_root, $Refs;

	begin_transaction();
	$args = func_get_args();
	$args = (object)array_combine(array('items', 'location', 'date_', 'reference', 'memo_'), $args);
	$args->trans_no = 0;
	hook_db_prewrite($args, ST_INVADJUST);

	$adj_id = get_next_trans_no(ST_INVADJUST);

	if ($SysPrefs->loc_notification() == 1)
	{
		include_once($path_to_root . "/inventory/includes/inventory_db.inc");
		$st_ids = array();
		$st_names = array();
		$st_num = array();
		$st_reorder = array();
	}
	foreach ($items as $line_item)
	{

		if ($SysPrefs->loc_notification() == 1 && $line_item->quantity < 0)
		{
			$chg = $line_item; $chg->quantity= -$chg->quantity;	// calculate_reorder_level expect positive qty
			$loc = calculate_reorder_level($location, $chg, $st_ids, $st_names, $st_num, $st_reorder); 
		}

		add_fa_stock_adjustment_item($adj_id, $line_item->stock_id, $location, $date_, $reference,
			$line_item->quantity, $line_item->standard_cost, $memo_, $line_item->batch_no, $line_item->exp_date);
	}

	add_comments(ST_INVADJUST, $adj_id, $date_, $memo_);

	$Refs->save(ST_INVADJUST, $adj_id, $reference);
	add_audit_trail(ST_INVADJUST, $adj_id, $date_);

	$args->trans_no = $adj_id;
	hook_db_postwrite($args, ST_INVADJUST);
	commit_transaction();
	if ($SysPrefs->loc_notification() == 1 && count($st_ids) > 0)
		send_reorder_email($loc, $st_ids, $st_names, $st_num, $st_reorder);

	return $adj_id;
}


function add_fa_stock_adjustment_item($adj_id, $stock_id, $location, $date_, $reference, $quantity, $standard_cost, $memo_, $batch_no=null, $exp_date=null, $pack_size=0, $pack_unit=null, $no_of_pack=0){

	if($pack_size > 0){
		$sql = "INSERT INTO ".TB_PREF."adjustment_bag (trans_no, stock_id, batch_no, pack_size, pack_unit,
		no_of_pack) VALUES (".db_escape($adj_id) . ", ".db_escape($stock_id) . ", ".db_escape($batch_no) . ",".db_escape($pack_size) . ", ".db_escape($pack_unit) . ", ".db_escape($no_of_pack) . ")";
   		db_query($sql,"The adjustment bag could not be added");
	}

	$mb_flag = get_mb_flag($stock_id);

    if (is_service($mb_flag))
    {
    	display_db_error("Cannot do inventory adjustment for Service item : $stock_id", "");
    }

	update_average_material_cost(null, $stock_id, $standard_cost, $quantity, $date_);
	update_purchase_value($stock_id, $standard_cost);
	// if (is_fixed_asset($mb_flag)) {
	// 	$sql = "UPDATE ".TB_PREF."stock_master SET inactive=1
	// 		WHERE stock_id=".db_escape($stock_id);
	// 	db_query($sql,"The inactive flag for the fixed asset could not be updated");
	// }

	add_stock_move(ST_INVADJUST, $stock_id, $adj_id, $location,   $date_, $reference, $quantity, $standard_cost, $standard_cost, $batch_no, $exp_date);

	$inv_value = $standard_cost * $quantity;
	$adj_value = $standard_cost * -($quantity);

	if (is_fixed_asset($mb_flag)) {
		// get the initial value of the fixed assset.
		$row = get_fixed_asset_move($stock_id, ST_SUPPRECEIVE);
		$inv_value = $row['price'] * $quantity;
		$adj_value = (-($row['price']) + $standard_cost) * $quantity;
	}

	if ($standard_cost > 0 || is_fixed_asset($mb_flag))
	{

		$stock_gl_codes = get_stock_gl_code($stock_id);

		add_gl_trans_std_cost(ST_INVADJUST, $adj_id, $date_,
			$stock_gl_codes['inventory_account'], $stock_gl_codes['dimension_id'], $stock_gl_codes['dimension2_id'], $memo_, $adj_value  );

		// add_gl_trans_std_cost(ST_INVADJUST, $adj_id, $date_, $stock_gl_codes['inventory_account'], 0, 0, $memo_, $inv_value);
	}

	if (is_fixed_asset($mb_flag)) {
		// Additional gl entry for fixed asset.
		$grn_act = get_company_pref('default_adj_act');
		add_gl_trans_std_cost(ST_INVADJUST, $adj_id, $date_, $grn_act, 0, 0, $memo_, ($standard_cost * -($quantity)));
	}
}

//=================================================================================================================================

function add_stock_cunsumption($items, $location, $date_, $reference, $memo_,$gl_code_id,$dimension_id=0 ,$dimension2_id=0,$person_id=null, $file_system='')
{
	global $SysPrefs, $path_to_root, $Refs;

	begin_transaction();
	$args = func_get_args();
	$args = (object)array_combine(array('items', 'location', 'date_', 'reference', 'memo_', 'file_system'), $args);
	$args->trans_no = 0;
	hook_db_prewrite($args, ST_CUNSUMPTION);

	$adj_id = get_next_trans_no(ST_CUNSUMPTION);

	if ($SysPrefs->loc_notification() == 1)
	{
		include_once($path_to_root . "/inventory/includes/inventory_db.inc");
		$st_ids = array();
		$st_names = array();
		$st_num = array();
		$st_reorder = array();
	}
	$itm_amt=0;
	foreach ($items as $line_item)
	{
			$item_row=get_item($line_item->stock_id);
			// if(!$item_row['is_cunsumption']) continue;

		if ($SysPrefs->loc_notification() == 1 && $line_item->quantity < 0)
		{
			$chg = $line_item; $chg->quantity= -$chg->quantity;	// calculate_reorder_level expect positive qty
			$loc = calculate_reorder_level($location, $chg, $st_ids, $st_names, $st_num, $st_reorder); 
		}

		$itm_amt+=add_stock_cunsumption_item($adj_id, $line_item->stock_id, $location, $date_, $reference,
			$line_item->quantity, $line_item->standard_cost, $memo_, $line_item->batch_no, $line_item->exp_date,$gl_code_id,$dimension_id,$dimension2_id,$person_id,$file_system);
	}
         
       if($person_id)
       {
       	// display_error($itm_amt);
       	write_supp_journal(ST_CUNSUMPTION, $adj_id, $person_id, $date_,
						$reference, -$itm_amt, 1, $adj_id);
       }  
	add_comments(ST_CUNSUMPTION, $adj_id, $date_, $memo_);

	$Refs->save(ST_CUNSUMPTION, $adj_id, $reference);
	add_audit_trail(ST_CUNSUMPTION, $adj_id, $date_);

	$args->trans_no = $adj_id;
	hook_db_postwrite($args, ST_CUNSUMPTION);
	commit_transaction();
	if ($SysPrefs->loc_notification() == 1 && count($st_ids) > 0)
		send_reorder_email($loc, $st_ids, $st_names, $st_num, $st_reorder);

	return $adj_id;
}

//-------------------------------------------------------------------------------------------------------------

function void_stock_cunsumption($type_no)
{
	hook_db_prevoid(ST_CUNSUMPTION, $type_no);
	void_gl_trans(ST_CUNSUMPTION, $type_no);
	void_stock_move(ST_CUNSUMPTION, $type_no);
}

//-------------------------------------------------------------------------------------------------------------

function get_stock_cunsumption_items($trans_no)
{
	$result = get_stock_moves(ST_CUNSUMPTION, $trans_no);

	if (db_num_rows($result) == 0)
	{
		return null;
	}

	return $result;
}

//--------------------------------------------------------------------------------------------------

function add_stock_cunsumption_item($adj_id, $stock_id, $location, $date_, $reference, $quantity, $standard_cost, $memo_, $batch_no=null, $exp_date=null,$gl_code_id=null,$dimension_id=0, $dimension2_id=0,$person_id=null,$file_system=''){
	$mb_flag = get_mb_flag($stock_id);

    if (is_service($mb_flag))
    {
    	display_db_error("Cannot do inventory adjustment for Service item : $stock_id", "");
    }

	update_average_material_cost(null, $stock_id, $standard_cost, $quantity, $date_);

	if (is_fixed_asset($mb_flag)) {
		$sql = "UPDATE ".TB_PREF."stock_master SET inactive=1
			WHERE stock_id=".db_escape($stock_id);
		db_query($sql,"The inactive flag for the fixed asset could not be updated");
	}

	add_stock_move(ST_CUNSUMPTION, $stock_id, $adj_id, $location,   $date_, $reference, -$quantity, $standard_cost, 0, $batch_no, $exp_date, $file_system);

	$inv_value = $standard_cost * $quantity;
	$adj_value = $standard_cost * -($quantity);

	if (is_fixed_asset($mb_flag)) {
		// get the initial value of the fixed assset.
		$row = get_fixed_asset_move($stock_id, ST_SUPPRECEIVE);
		$inv_value = $row['price'] * $quantity;
		$adj_value = (-($row['price']) + $standard_cost) * $quantity;
	}

	if ($standard_cost > 0 || is_fixed_asset($mb_flag))
	{

		$stock_gl_codes = get_stock_gl_code($stock_id);
    // $stock_gl_codes['adjustment_account'];
	  add_gl_trans_std_cost(ST_CUNSUMPTION, $adj_id, $date_,
			 $stock_gl_codes['inventory_account'] , $dimension_id, $dimension2_id, $memo_, $adj_value  );

        $gl_type = is_subledger_account($gl_code_id, $person_id);
		$person_type_id = $gl_type > 0 ? PT_CUSTOMER : PT_SUPPLIER;
	   $amount +=add_gl_trans_std_cost(ST_CUNSUMPTION, $adj_id, $date_,$gl_code_id, $dimension_id, $dimension2_id, $memo_, $inv_value,$person_type_id,$person_id);
	}

	if (is_fixed_asset($mb_flag)) {
		// Additional gl entry for fixed asset.
		$grn_act = get_company_pref('default_loss_on_asset_disposal_act');
		$amount += add_gl_trans_std_cost(ST_CUNSUMPTION, $adj_id, $date_, $grn_act, $dimension_id, $dimension2_id, $memo_, ($standard_cost * -($quantity)));
	}

	return $amount;
}
