<?php 
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Unit Mapping
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
*****************************************/

$page_security = 'SA_UOM';

if (@$_GET['page_level'] == 1)
	$path_to_root = "../..";
else	
	$path_to_root = "..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/sales/includes/sales_db.inc");
include_once($path_to_root . "/sales/includes/db/sales_types_db.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/inventory/includes/inventory_db.inc");

$js = "";
if ($SysPrefs->use_popup_windows && $SysPrefs->use_popup_search)
	$js .= get_js_open_window(900, 500);
page(_($help_context = "Inventory Item Unit mapping"), false, false, "", $js);

//---------------------------------------------------------------------------------------------------
check_db_has_stock_items(_("There are no items defined in the system."));

check_db_has_sales_types(_("There are no sales types in the system. Please set up sales types befor entering pricing."));

simple_page_mode(true);
//---------------------------------------------------------------------------------------------------
$input_error = 0;

if (isset($_GET['stock_id'])){
	$_POST['stock_id'] = $_GET['stock_id'];
}
if (isset($_GET['Item'])){
	$_POST['stock_id'] = $_GET['Item'];
}

if (!isset($_POST['curr_abrev'])){
	$_POST['curr_abrev'] = get_company_currency();
}

//---------------------------------------------------------------------------------------------------
$action = $_SERVER['PHP_SELF'];
if ($page_nested)
	$action .= "?stock_id=".get_post('stock_id');
start_form(false, false, $action);

if (!isset($_POST['stock_id']))
	$_POST['stock_id'] = get_global_stock_item();

if (!$page_nested){
	echo "<center>" . _("Item:"). "&nbsp;";
	echo sales_items_list('stock_id', $_POST['stock_id'], false, true, '', array('editable' => false));
	echo "<hr></center>";
}
else
	br(2);
set_global_stock_item($_POST['stock_id']);

//----------------------------------------------------------------------------------------------------
if ($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') {

	if (!check_num('qty', 0))	{
		$input_error = 1;
		display_error( _("The Quantity entered must be numeric."));
		set_focus('price');
	}   	

	if ($input_error != 1)	{
    	if ($selected_id != -1) 	{//editing an existing price
			update_item_unit_mapp($selected_id, $_POST['unit'], input_num('qty'));
			$msg = _("This Unit has been updated.");
		}	else		{
			add_item_unit_mapp($_POST['stock_id'],  $_POST['unit'], input_num('qty'));
			$msg = _("The new Unit has been added.");
		}
		display_notification($msg);
		$Mode = 'RESET';
	}
}

//------------------------------------------------------------------------------------------------------
if ($Mode == 'Delete'){
	//the link to delete a selected record was clicked
	delete_item_unit_mapp($selected_id);
	display_notification(_("The selected price has been deleted."));
	$Mode = 'RESET';
}

if ($Mode == 'RESET'){
	$selected_id = -1;
}

if (list_updated('stock_id')) {
	$Ajax->activate('unit_table');
	$Ajax->activate('unit_details');
}
if (list_updated('stock_id') || isset($_POST['_curr_abrev_update']) || isset($_POST['_sales_type_id_update'])) {
	// after change of stock, currency or salestype selector
	// display default calculated price for new settings. 
	// If we have this price already in db it is overwritten later.
	unset($_POST['price']);
	$Ajax->activate('unit_details');
}

//---------------------------------------------------------------------------------------------------
$prices_list = get_units_mapped($_POST['stock_id']);

div_start('unit_table');
start_table(TABLESTYLE, "width='30%'");

$th = array(_("StockID"), _("Quantity"), _("Unit"), "", "");
table_header($th);
$k = 0; //row colour counter
$calculated = false;
if(is_array($prices_list) && !empty($prices_list)){
    foreach($prices_list as $myrow){
        alt_table_row_color($k);
        label_cell($myrow["stock_id"]);
        amount_cell($myrow["qty"]);
        label_cell($myrow["unit"]);
        edit_button_cell("Edit".$myrow['id'], _("Edit"));
        delete_button_cell("Delete".$myrow['id'], _("Delete"));
        end_row();
    }
}

end_table();
div_end();
//------------------------------------------------------------------------------------------------
echo "<br>";
if ($Mode == 'Edit'){
	$myrow = get_item_mapped_unit($selected_id);
	$_POST['qty'] = $myrow["qty"];
	$_POST['unit'] = $myrow["unit"];
}

hidden('selected_id', $selected_id);
div_start('unit_details');
start_table(TABLESTYLE2);

$kit = get_item_code_dflts($_POST['stock_id']);
$units = $kit ? $kit["units"] : '';
stock_units_list_row(_("Unit:"), 'unit', null, true, $units);
small_amount_row(_("Quantity:"), 'qty', null, '', _('per') .' '.$units);

end_table(1);

submit_add_or_update_center($selected_id == -1, '', 'both');
div_end();

end_form();
end_page();

function add_item_unit_mapp($stock_id, $unit, $qty) {
    $sql = "INSERT INTO " .TB_PREF."item_units_map (stock_id, unit, qty) VALUES (".db_escape($stock_id).", ".db_escape($unit).",".db_escape($qty).");";
    db_query($sql, "Can't insert new unit for item");
    return db_insert_id();
}

function update_item_unit_mapp($selected_id, $unit, $qty) {
    $sql = "UPDATE ".TB_PREF."item_units_map SET unit=".db_escape($unit).", qty=".db_escape($qty)." WHERE id =".db_escape($selected_id);
    db_query($sql, "Unable to update the second unit");
}

function get_item_mapped_unit($selected_id){ 
    $sql = "SELECT * FROM ".TB_PREF."item_units_map WHERE id =".db_escape($selected_id);
    $res = db_query($sql, "Cant get the selected unit");
    if(db_num_rows($res) > 0 ){
        return  db_fetch($res);
    } else 
        return 0;
}
function delete_item_unit_mapp($selected_id){
    $sql = "DELETE FROM ".TB_PREF."item_units_map WHERE id =".db_escape($selected_id);
    $res = db_query($sql, "Cant get the selected unit");
}

function get_units_mapped($stock_id){
    $sql = "SELECT * FROM ".TB_PREF."item_units_map WHERE stock_id =".db_escape($stock_id);
    $res = db_query($sql, "Cant get the selected unit");
    if(db_num_rows($res) > 0 ){
        $result = [];
        while($row = db_fetch($res)){
            $result[] = $row;
        }
        return $result;
    } else 
        return 0;
}