
<link rel="stylesheet" href="css/new_mxerp.css">
<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"></script>
<script type="text/javascript">
	shade_name_val = '';
	product_sheet_val = '';
	serial_no_val = '';
	brand_code_val = '';
	material_type_val = '';
	material_item_desc_val = '';
	itemname = '';

	function setItemName() {
		if (document.getElementById("item_name1").value == '') {
			document.getElementById("item_name1").value = 1;
			if (document.getElementById("item_name").value != '') {
				itemname = document.getElementById("item_name").value;
			}
		}
		var shade_name_val = document.getElementById("shade_name").value;
		var product_sheet_val = document.getElementById("product_sheet").value;
		var serial_no_val = document.getElementById("serial_no").value;
		var brand_code_val = document.getElementById("brand_code").value;
		var material_type_val = document.getElementById("material_type").value;
		var material_item_desc_val = document.getElementById("material_item_desc").value;
		//	document.getElementById("item_name").value =itemname+" "+ shade_name_val+" "+product_sheet_val+" "+serial_no_val+" "+brand_code_val+" "+material_type_val+" "+material_item_desc_val;

	}

	function get_item(val) {

		if (window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();
		} else {
			xmlhttp = new ActiveXobject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				document.getElementById("harwaregroupid").innerHTML = xmlhttp.responseText;

			}

		}
		//alert(val);
		xmlhttp.open("GET", "Gethardwaregroup.php?groupid=" + val, true);
		xmlhttp.send();

	}

	function loadLasaOptions() {
		var categoryId = $("#CategoryID").val();
		var subGroupId = $("#sub_group").val();
		var currentItemId = $("#current_item_id").val() || "";

		if (!categoryId || categoryId === "000" || !subGroupId || subGroupId === "000") {
			$("#look_alike_item_id, #sound_alike_item_id").html('<option value="">Select</option>');
			return;
		}

		$.ajax({
			url: "item_subcategory.php",
			type: "GET",
			data: {
				lasa_options: 1,
				category_id: categoryId,
				sub_group_id: subGroupId,
				current_item_id: currentItemId
			},
			success: function(result) {
				var optionsHtml = result || '<option value="">Select</option>';
				$("#look_alike_item_id, #sound_alike_item_id").html(optionsHtml);
			}
		});
	}

	function chkdulicateItem(itemVal, itemId) {
		if ($("#CategoryID").val() == "000") {
			alert("Please select Main Group first");
			document.getElementById(itemId).value = "";
			$("#CategoryID").get(0).focus();
			return false;
		}
		if ($("#sub_group").val() == "000") {
			alert("Please select Sub Group first");
			document.getElementById(itemId).value = "";
			$("#sub_group").get(0).focus();
			return false;
		}
		if ($("#orig_local").val() == "000") {
			alert("Please select Store Location first");
			document.getElementById(itemId).value = "";
			$("#orig_local").get(0).focus();
			return false;
		}
		var catID = $("#CategoryID").val();
		var subID = $("#sub_group").val();
		var storeID = $("#orig_local").val();
		$.ajax({
			url: "ajax_chk_dupli_items.php",
			type: "POST",
			data: {
				catID: catID,
				subID: subID,
				storeID: storeID,
				itemVal: itemVal,
				itemId: itemId
			},
			success: function(result) {
				if (result == 1) {
					alert("This is Duplicate Item Detail");
					document.getElementById(itemId).value = "";
					document.getElementById(itemId).focus();
				}
			}
		});

	}

	function blankItem() {
		document.getElementById("StockID").value = "";
		document.getElementById("item_name").value = "";
	}

	function validatefun() {
		if (document.getElementById("CategoryID").value == "000") {
			alert("Please Select Main Group");
			document.getElementById("CategoryID").focus();
			return false;
		}
		if (document.getElementById("sub_group").value == "000") {
			alert("Please Select Sub Group");
			document.getElementById("sub_group").focus();
			return false;
		}
		/* if(document.getElementById("orig_local").value=="000"){
		   alert("Please Select Store Location");
		   document.getElementById("orig_local").focus();
		   return false;
		 }  */
		if (document.getElementById("StockID").value == "") {
			alert("Please Enter Item Code");
			document.getElementById("StockID").focus();
			return false;
		}
		if (document.getElementById("item_name").value == "") {
			alert("Please Enter Item Name");
			document.getElementById("item_name").focus();
			return false;
		}
		if (document.getElementById("hsn").checked != true && document.getElementById("hsn1").checked != true) {
			alert("Please check at least one radio button");
			return false;
		}


		if (document.getElementById("hsn").checked == true) {
			if (document.getElementById("hsn_code").value == "") {
				alert("Please Enter HSN Code");
				document.getElementById("hsn_code").focus();
				return false;
			}
		}

		if (document.getElementById("check_exempted").checked != true) {
			if (document.getElementById("gst_percentage").value == "") {
				alert("Please Enter GST Percentage");
				document.getElementById("gst_percentage").focus();
				return false;
			}

		}



		return true;
	}

	function syncGstPercentageFromTax() {
		var gstSelect = document.getElementById("pur_vat");
		var gstInput = document.getElementById("gst_percentage");
		if (!gstSelect || !gstInput) {
			return;
		}

		var selectedOption = gstSelect.options[gstSelect.selectedIndex];
		var taxRate = selectedOption ? selectedOption.getAttribute("data-taxrate") : "";
		gstInput.value = taxRate && gstSelect.value !== "0" ? taxRate : "";
	}

	function initializeGstSelection() {
		var gstSelect = document.getElementById("pur_vat");
		var gstInput = document.getElementById("gst_percentage");
		var exemptedCheckbox = document.getElementById("check_exempted");
		if (!gstSelect || !gstInput) {
			return;
		}

		var currentPercentage = String(gstInput.value || "").trim();
		if ((gstSelect.value === "" || gstSelect.value === "0") && currentPercentage !== "") {
			for (var i = 0; i < gstSelect.options.length; i++) {
				var option = gstSelect.options[i];
				if (String(option.getAttribute("data-taxrate") || "").trim() === currentPercentage) {
					gstSelect.selectedIndex = i;
					break;
				}
			}
		}

		syncGstPercentageFromTax();
		if (exemptedCheckbox && exemptedCheckbox.checked) {
			gstInput.value = "";
		}
	}
</script>
<?php
session_name('CAKEPHP'); session_start();
include('includes/Class_UnitMeasure.php');
include('CRM/ClassRole.php');

function normalizeCommaSeparatedValues($value)
{
	$items = array_filter(array_map('trim', explode(',', (string) $value)), 'strlen');
	return implode(', ', $items);
}

function parseSelectedItemIds($value)
{
	$ids = is_array($value) ? $value : explode(',', (string) $value);
	$ids = array_values(array_unique(array_filter(array_map('trim', $ids), 'strlen')));
	return $ids;
}

function mergeReciprocalItemIds($existingValue, $itemId, $shouldInclude = true)
{
	$itemIds = parseSelectedItemIds($existingValue);
	$itemId = trim((string) $itemId);

	if ($itemId === '') {
		return implode(',', $itemIds);
	}

	if ($shouldInclude) {
		if (!in_array($itemId, $itemIds)) {
			$itemIds[] = $itemId;
		}
	} else {
		$itemIds = array_values(array_filter($itemIds, function ($value) use ($itemId) {
			return $value !== $itemId;
		}));
	}

	return implode(',', $itemIds);
}

function syncReciprocalLasaMappings($currentItemId, $selectedIds, $fieldName, $companyId, $db)
{
	$currentItemId = trim((string) $currentItemId);
	if ($currentItemId === '') {
		return;
	}

	$selectedIds = parseSelectedItemIds($selectedIds);
	$existingLinkedIds = array();
	$getExistingSql = "select id," . $fieldName . " from item_master where CompanyId='" . $companyId . "' and find_in_set('" . $currentItemId . "'," . $fieldName . ")";
	$getExistingResult = DB_query($getExistingSql, $db);
	while ($existingRow = DB_fetch_array($getExistingResult)) {
		$existingLinkedIds[] = trim((string) $existingRow['id']);
	}

	$idsToRemove = array_diff($existingLinkedIds, $selectedIds);
	foreach ($idsToRemove as $linkedId) {
		$getRowSql = "select " . $fieldName . " from item_master where id='" . $linkedId . "' and CompanyId='" . $companyId . "'";
		$getRowResult = DB_query($getRowSql, $db);
		$getRow = DB_fetch_array($getRowResult);
		if ($getRow) {
			$updatedValue = mergeReciprocalItemIds($getRow[$fieldName], $currentItemId, false);
			DB_query("update item_master set " . $fieldName . "='" . $updatedValue . "' where id='" . $linkedId . "' and CompanyId='" . $companyId . "'", $db);
		}
	}

	foreach ($selectedIds as $linkedId) {
		if ($linkedId === $currentItemId) {
			continue;
		}
		$getRowSql = "select " . $fieldName . " from item_master where id='" . $linkedId . "' and CompanyId='" . $companyId . "'";
		$getRowResult = DB_query($getRowSql, $db);
		$getRow = DB_fetch_array($getRowResult);
		if ($getRow) {
			$updatedValue = mergeReciprocalItemIds($getRow[$fieldName], $currentItemId, true);
			DB_query("update item_master set " . $fieldName . "='" . $updatedValue . "' where id='" . $linkedId . "' and CompanyId='" . $companyId . "'", $db);
		}
	}
}

$CompanyId = $_SESSION['ACGCompanyId'];
$sql_query = "SELECT * FROM tbl_itemname_auto where CompanyId=" . $CompanyId;
$sqlQuery = DB_query($sql_query, $db);
$row = DB_fetch_array($sqlQuery);


$item_name_auto = $row['item_name_auto'];
if ($_REQUEST['SaveItem']) {
	if ($_FILES['back_image']['name'] != "")
		move_uploaded_file($_FILES['back_image']['tmp_name'], "images/login/" . $_FILES['back_image']['name']);
	if ($_FILES['front_image']['name'] != "")
		move_uploaded_file($_FILES['front_image']['tmp_name'], "images/login/" . $_FILES['front_image']['name']);


	if ($_REQUEST['mst_unitid'] != '0' && $_REQUEST['conv_unit'] != '0' && $_REQUEST['conv_factor'] != '') {
		$confac = $_REQUEST['conv_factor'];
		$secondary_unit = $_REQUEST['conv_unit'];
	} else if ($_REQUEST['mst_unitid'] != '0' && $_REQUEST['conv_unit'] != '0' && $_REQUEST['conv_factor'] == '') {
		$confac = '(NULL)';
		$secondary_unit = $_REQUEST['conv_unit'];
	} else if ($_REQUEST['mst_unitid'] != '0' && $_REQUEST['conv_unit'] == '0' && $_REQUEST['conv_factor'] == '') {
		$confac = '1';
		$secondary_unit = $_REQUEST['mst_unitid'];
	}
	$strBothFinal                    = $_REQUEST['StockID'];

	/* $data['orig_local']              =$_REQUEST['orig_local'];
		$data['StockID']                 =$strBothFinal;
		$data['item_name']               =htmlspecialchars($_REQUEST['item_name'],ENT_QUOTES);
		$data['mst_unitid']              =$_REQUEST['mst_unitid'];
		$data['conv_unit']               =$secondary_unit;
		$data['conv_factor']             =$confac;
		$data['min_level']               =$_REQUEST['min_level'];
		$data['max_level']               =$_REQUEST['max_level'];
		$data['reorder_level']           =$_REQUEST['reorder_level'];
		$data['mrp_rate']                =$_REQUEST['mrp_rate'];
		$data['net_rate']                =$_REQUEST['net_rate'];
		$data['shade_name']              =$_REQUEST['shade_name'];
		$data['item_mst_form_rate']      =$_REQUEST['item_mst_form_rate'];
		$data['product_sheet']           =$_REQUEST['product_sheet'];
		$data['serial_no']               =$_REQUEST['serial_no'];
		$data['net_wt']                  =$_REQUEST['net_wt'];
		$data['gross_wt']                =$_REQUEST['gross_wt'];
		$data['make']                    =$_REQUEST['modalgroup'];
		$data['abc_class']               =$_REQUEST['abc_class'];
		$data['excise_trafficno']        =$_REQUEST['excise_trafficno'];
		$data['warr_period']             =$_REQUEST['warr_period'];
		$data['item_mst_form']           =$_REQUEST['item_mst_form'];
		$data['brand_code']              =$_REQUEST['brand_code'];
		$data['material_type']           =$_REQUEST['material_type'];
		$data['material_item_desc']      =$_REQUEST['material_item_desc'];
		$data['cust_drwgno']             =$_REQUEST['cust_drwgno'];
		$data['Mfg_drwgno']              =$_REQUEST['Mfg_drwgno'];
		$data['Mfg_drwgcode']            =$_REQUEST['Mfg_drwgcode'];
		if(count($_REQUEST['groupid'])>0)
		$data['groupid']                 =implode(',',$_REQUEST['groupid']); 
		if(count($_REQUEST['leaduserid'])>0)
		$data['users']                  =implode(',',$_REQUEST['leaduserid']);
		$data['CompanyId']              =$_SESSION['ACGCompanyId'];
		$data['mst_ledgerid']           =$_REQUEST['mst_ledgerid'];
		$data['type_of_material']       =$_REQUEST['type_of_material'];
		$data['quality_of_material']    =$_REQUEST['quality_of_material'];
		$data['mst_ledger_code']        =$_REQUEST['mst_ledger_code'];
		$data['last_po_price']          =$_REQUEST['last_po_price'];
		$data['item_desc']              =htmlspecialchars($_REQUEST['item_desc'],ENT_QUOTES);
		$data['CategoryID']             =$_REQUEST['CategoryID'];
		$data['SubCategoryID']          =$_REQUEST['sub_group']; 
		$data['item_exciable']          =$_REQUEST['item_exciable'];
		$data['back_image']             =$_FILES['back_image']['name'];
		$data['front_image']            =$_FILES['front_image']['name'];
		$data['abtment']            	=$_REQUEST['abtment'];
		$data['inventory_item']         =$_REQUEST['inventory_item'];
		$data['batch_item']            	=$_REQUEST['batch_item'];
		$data['medicine_item']          =$_REQUEST['medicine_item'];
		$data['vat_purchase']           =$_REQUEST['pur_vat'];
		$data['cst_purchase']           =$_REQUEST['pur_cst'];
		$data['vat_sales']              =$_REQUEST['sale_vat'];
		$data['cst_sales']              =$_REQUEST['sale_cst']; */
	if ($_REQUEST['action'] != 'edit') {
		$data['orig_local']              = $_REQUEST['orig_local'];
		$data['StockID']                 = $strBothFinal;
		$data['item_name']               = htmlspecialchars($_REQUEST['item_name'], ENT_QUOTES);
		$data['mst_unitid']              = $_REQUEST['mst_unitid'];
		$data['conv_unit']               = $secondary_unit;
		$data['conv_factor']             = $confac;
		$data['min_level']               = $_REQUEST['min_level'];
		$data['max_level']               = $_REQUEST['max_level'];
		$data['reorder_level']           = $_REQUEST['reorder_level'];
		$data['mrp_rate']                = $_REQUEST['mrp_rate'];
		$data['net_rate']                = $_REQUEST['net_rate'];
		$data['shade_name']              = $_REQUEST['shade_name'];
		$data['item_mst_form_rate']      = $_REQUEST['item_mst_form_rate'];
		$data['product_sheet']           = $_REQUEST['product_sheet'];
		$data['serial_no']               = $_REQUEST['serial_no'];
		$data['net_wt']                  = $_REQUEST['net_wt'];
		$data['gross_wt']                = $_REQUEST['gross_wt'];
		$data['make']                    = $_REQUEST['modalgroup'];
		$data['abc_class']               = $_REQUEST['abc_class'];
		$data['excise_trafficno']        = $_REQUEST['excise_trafficno'];
		$data['warr_period']             = $_REQUEST['warr_period'];
		$data['item_mst_form']           = $_REQUEST['item_mst_form'];
		$data['brand_code']              = normalizeCommaSeparatedValues($_REQUEST['brand_code']);
		$data['material_type']           = $_REQUEST['material_type'];
		$data['material_item_desc']      = $_REQUEST['material_item_desc'];
		$data['cust_drwgno']             = $_REQUEST['cust_drwgno'];
		$data['Mfg_drwgno']              = $_REQUEST['Mfg_drwgno'];
		$data['Mfg_drwgcode']            = $_REQUEST['Mfg_drwgcode'];
		if (count($_REQUEST['groupid']) > 0)
			$data['groupid']                 = implode(',', $_REQUEST['groupid']);
		if (count($_REQUEST['leaduserid']) > 0)
			$data['users']                  = implode(',', $_REQUEST['leaduserid']);
		$data['CompanyId']              = $_SESSION['ACGCompanyId'];
		$data['mst_ledgerid']           = $_REQUEST['mst_ledgerid'];
		$data['type_of_material']       = $_REQUEST['type_of_material'];
		$data['quality_of_material']    = $_REQUEST['quality_of_material'];
		$data['mst_ledger_code']        = $_REQUEST['mst_ledger_code'];
		$data['last_po_price']          = $_REQUEST['last_po_price'];
		$data['item_desc']              = htmlspecialchars($_REQUEST['item_desc'], ENT_QUOTES);
		$data['CategoryID']             = $_REQUEST['CategoryID'];
		$data['SubCategoryID']          = $_REQUEST['sub_group'];
		$data['barcode']				= $_REQUEST['barcode'];
		$data['item_exciable']          = $_REQUEST['item_exciable'];
		$data['back_image']             = $_FILES['back_image']['name'];
		$data['front_image']            = $_FILES['front_image']['name'];
		$data['abtment']            	= $_REQUEST['abtment'];
		$data['inventory_item']         = $_REQUEST['inventory_item'];
		$data['batch_item']            	= $_REQUEST['batch_item'];
		$data['medicine_item']          = $_REQUEST['medicine_item'];
        $data['generic_name']        = normalizeCommaSeparatedValues($_REQUEST['generic_name']);
        $data['ved_type']            = $_REQUEST['ved_type'];
        $data['item_strength']       = $_REQUEST['item_strength'];
        $data['snomed_ct']           = $_REQUEST['snomed_ct'];
        $data['schedule_name']       = $_REQUEST['schedule_name'];

        $data['narcotic']            = isset($_REQUEST['narcotic']) ? 'Y' : 'N';
        $data['is_high_risk']        = isset($_REQUEST['is_high_risk']) ? 'Y' : 'N';
        $data['is_emergency']        = isset($_REQUEST['is_emergency']) ? 'Y' : 'N';
		$data['item_in_use'] = isset($_REQUEST['item_in_use']) ? $_REQUEST['item_in_use'] : 'Y';
        $data['item_not_in_use_reason'] = !empty($_REQUEST['item_not_in_use_reason'])? $_REQUEST['item_not_in_use_reason']: '';

       $selectedLookAlikeIds = parseSelectedItemIds(isset($_REQUEST['look_alike_item_id']) ? $_REQUEST['look_alike_item_id'] : array());
       $selectedSoundAlikeIds = parseSelectedItemIds(isset($_REQUEST['sound_alike_item_id']) ? $_REQUEST['sound_alike_item_id'] : array());
       $data['look_alike_item_id'] = implode(',', $selectedLookAlikeIds);
       $data['sound_alike_item_id'] = implode(',', $selectedSoundAlikeIds);

         $data['expiry_cutoff_days']  = $_REQUEST['expiry_cutoff_days'];
		$data['vat_purchase']           = $_REQUEST['pur_vat'];
		$data['cst_purchase']           = $_REQUEST['pur_cst'];
		$data['vat_sales']              = $_REQUEST['sale_vat'];
		$data['cst_sales']              = $_REQUEST['sale_cst'];
		$data['hsn_applicable']         = $_REQUEST['hsn'];
		$data['hsn_code']               = $_REQUEST['hsn_code'];
		//$data['gst_sales']              =$_REQUEST['sale_gst'];
		//$data['gst_purchase']           =$_REQUEST['purchase_gst'];
		$data['exempted']               = $_REQUEST['check_exempted'];
		$data['gst_percentage']         = $_REQUEST['gst_percentage'];
		$data['gst_applicable']         = $_REQUEST['hsn'];

		$s->RecordInsert('item_master', $data);
		$lastid = DB_Last_Insert_ID($db, 'item_master', 'id');
		syncReciprocalLasaMappings($lastid, $selectedLookAlikeIds, 'look_alike_item_id', $_SESSION['ACGCompanyId'], $db);
		syncReciprocalLasaMappings($lastid, $selectedSoundAlikeIds, 'sound_alike_item_id', $_SESSION['ACGCompanyId'], $db);
		if ($_REQUEST['modalgroup'] == '0') {
			$data1['model_group_name'] = htmlspecialchars($_REQUEST['item_name'], ENT_QUOTES);
			$data1['model_group_code'] = $_REQUEST['StockID'];
			$data1['mst_itemid'] = $lastid;
			$data1['created_by'] = $_SESSION['UserID'];
			$data1['CompanyId'] = $_SESSION['ACGCompanyId'];
			$data1['created_date'] = date('Y-m-d');
			$s->RecordInsert('prd_model_group', $data1);
		}
		prnMsg(_('Record Inserted Successfully!'), 'success');
	} else {
		$data['orig_local']              = $_REQUEST['orig_local'];
		$data['StockID']                 = $strBothFinal;
		//$data['item_name']               =htmlspecialchars($_REQUEST['item_name'],ENT_QUOTES);
		$data['mst_unitid']              = $_REQUEST['mst_unitid'];
		$data['conv_unit']               = $secondary_unit;
		$data['conv_factor']             = $confac;
		$data['min_level']               = $_REQUEST['min_level'];
		$data['max_level']               = $_REQUEST['max_level'];
		$data['reorder_level']           = $_REQUEST['reorder_level'];
		$data['mrp_rate']                = $_REQUEST['mrp_rate'];
		$data['net_rate']                = $_REQUEST['net_rate'];
		$data['shade_name']              = $_REQUEST['shade_name'];
		$data['item_mst_form_rate']      = $_REQUEST['item_mst_form_rate'];
		$data['product_sheet']           = $_REQUEST['product_sheet'];
		$data['serial_no']               = $_REQUEST['serial_no'];
		$data['net_wt']                  = $_REQUEST['net_wt'];
		$data['gross_wt']                = $_REQUEST['gross_wt'];
		$data['make']                    = $_REQUEST['modalgroup'];
		$data['abc_class']               = $_REQUEST['abc_class'];
		$data['excise_trafficno']        = $_REQUEST['excise_trafficno'];
		$data['warr_period']             = $_REQUEST['warr_period'];
		$data['item_mst_form']           = $_REQUEST['item_mst_form'];
		$data['brand_code']              = normalizeCommaSeparatedValues($_REQUEST['brand_code']);
		$data['material_type']           = $_REQUEST['material_type'];
		$data['material_item_desc']      = $_REQUEST['material_item_desc'];
		$data['cust_drwgno']             = $_REQUEST['cust_drwgno'];
		$data['Mfg_drwgno']              = $_REQUEST['Mfg_drwgno'];
		$data['Mfg_drwgcode']            = $_REQUEST['Mfg_drwgcode'];
		if (count($_REQUEST['groupid']) > 0)
			$data['groupid']                 = implode(',', $_REQUEST['groupid']);
		if (count($_REQUEST['leaduserid']) > 0)
			$data['users']                  = implode(',', $_REQUEST['leaduserid']);
		$data['CompanyId']              = $_SESSION['ACGCompanyId'];
		$data['mst_ledgerid']           = $_REQUEST['mst_ledgerid'];
		$data['type_of_material']       = $_REQUEST['type_of_material'];
		$data['quality_of_material']    = $_REQUEST['quality_of_material'];
		$data['mst_ledger_code']        = $_REQUEST['mst_ledger_code'];
		$data['last_po_price']          = $_REQUEST['last_po_price'];
		$data['item_desc']              = htmlspecialchars($_REQUEST['item_desc'], ENT_QUOTES);
		$data['CategoryID']             = $_REQUEST['CategoryID'];
		$data['SubCategoryID']          = $_REQUEST['sub_group'];
		$data['barcode']				= $_REQUEST['barcode'];
		$data['item_exciable']          = $_REQUEST['item_exciable'];
		$data['back_image']             = $_FILES['back_image']['name'];
		$data['front_image']            = $_FILES['front_image']['name'];
		$data['abtment']            	= $_REQUEST['abtment'];
		$data['inventory_item']         = $_REQUEST['inventory_item'];
		$data['batch_item']            	= $_REQUEST['batch_item'];
		$data['medicine_item']          = $_REQUEST['medicine_item'];
		 $data['generic_name']        = normalizeCommaSeparatedValues($_REQUEST['generic_name']);
        $data['ved_type']            = $_REQUEST['ved_type'];
        $data['item_strength']       = $_REQUEST['item_strength'];
        $data['snomed_ct']           = $_REQUEST['snomed_ct'];
        $data['schedule_name']       = $_REQUEST['schedule_name'];

        $data['narcotic']            = isset($_REQUEST['narcotic']) ? 'Y' : 'N';
        $data['is_high_risk']        = isset($_REQUEST['is_high_risk']) ? 'Y' : 'N';
        $data['is_emergency']        = isset($_REQUEST['is_emergency']) ? 'Y' : 'N';
		$data['item_in_use'] = isset($_REQUEST['item_in_use']) ? $_REQUEST['item_in_use'] : 'Y';
        $data['item_not_in_use_reason'] = !empty($_REQUEST['item_not_in_use_reason'])? $_REQUEST['item_not_in_use_reason']: '';

        $selectedLookAlikeIds = parseSelectedItemIds(isset($_REQUEST['look_alike_item_id']) ? $_REQUEST['look_alike_item_id'] : array());
        $selectedSoundAlikeIds = parseSelectedItemIds(isset($_REQUEST['sound_alike_item_id']) ? $_REQUEST['sound_alike_item_id'] : array());
        $data['look_alike_item_id'] = implode(',', $selectedLookAlikeIds);
        $data['sound_alike_item_id'] = implode(',', $selectedSoundAlikeIds);

         $data['expiry_cutoff_days']  = $_REQUEST['expiry_cutoff_days'];
		$data['vat_purchase']           = $_REQUEST['pur_vat'];
		$data['cst_purchase']           = $_REQUEST['pur_cst'];
		$data['vat_sales']              = $_REQUEST['sale_vat'];
		$data['cst_sales']              = $_REQUEST['sale_cst'];
		$data['hsn_code']               = $_REQUEST['hsn_code'];
		$data['hsn_applicable']         = $_REQUEST['hsn'];
		//$data['gst_sales']              =$_REQUEST['sale_gst'];
		//$data['gst_purchase']           =$_REQUEST['purchase_gst'];
		$data['exempted']               = $_REQUEST['check_exempted'];
		$data['gst_percentage']         = $_REQUEST['gst_percentage'];
		$data['gst_applicable']         = $_REQUEST['hsn'];

		$cond = "id='" . $_REQUEST['id'] . "'";
		$s->RecordEdit('item_master', $data, $cond);
		syncReciprocalLasaMappings($_REQUEST['id'], $selectedLookAlikeIds, 'look_alike_item_id', $_SESSION['ACGCompanyId'], $db);
		syncReciprocalLasaMappings($_REQUEST['id'], $selectedSoundAlikeIds, 'sound_alike_item_id', $_SESSION['ACGCompanyId'], $db);
		if ($_REQUEST['modalgroup'] == '0') {
			$data1['model_group_name'] = htmlspecialchars($_REQUEST['item_name'], ENT_QUOTES);
			$data1['model_group_code'] = $_REQUEST['StockID'];
			$data1['mst_itemid'] = $_REQUEST['id'];
			$data1['created_by'] = $_SESSION['UserID'];
			$data1['CompanyId'] = $_SESSION['ACGCompanyId'];
			$data1['created_date'] = date('Y-m-d');
			$s->RecordInsert('prd_model_group', $data1);
		} else {
			$cond1 = "id='" . $_REQUEST['id'] . "'";
			$data1['model_group_name'] = htmlspecialchars($_REQUEST['item_name'], ENT_QUOTES);
			$data1['model_group_code'] = $_REQUEST['StockID'];
			$data1['mst_itemid'] = $_REQUEST['id'];
			$data1['created_by'] = $_SESSION['UserID'];
			$data1['CompanyId'] = $_SESSION['ACGCompanyId'];
			$data1['created_date'] = date('Y-m-d');
			$s->RecordEdit('prd_model_group', $data1, $cond1);
		}
		prnMsg(_('Record Updated Successfully!'), 'success');
	}
	echo "<script>location.href='index.php?route=item_list&modid=" . $_REQUEST['modid'] . "&frmid=" . $_REQUEST['frmid'] . "'</script>";
}
if ($_REQUEST['action'] == 'edit' || $_REQUEST['action'] == 'view') {
	$sql = "select * from item_master where id='" . $_REQUEST['id'] . "' ";
	$result = DB_query($sql, $db);
	$myrow = DB_fetch_array($result);
	//echo "<pre>";
	//print_r($myrow);
	$CategoryID = $myrow['CategoryID'];
	$SubCategoryID = $myrow['SubCategoryID'];
	$barcode = $myrow['barcode'];
	$orig_local = $myrow['orig_local'];
	$StockID = $myrow['StockID'];
	$item_name = $myrow['item_name'];
	$item_desc = $myrow['item_desc'];
	$mst_unitid = $myrow['mst_unitid'];
	$conv_unit = $myrow['conv_unit'];
	$conv_factor = $myrow['conv_factor'];
	$min_level = $myrow['min_level'];
	$max_level = $myrow['max_level'];
	$reorder_level = $myrow['reorder_level'];
	$mrp_rate = $myrow['mrp_rate'];
	$net_rate = $myrow['net_rate'];
	$shade_name = $myrow['shade_name'];
	$product_sheet = $myrow['product_sheet'];
	$serial_no = $myrow['serial_no'];
	$net_wt = $myrow['net_wt'];
	$gross_wt = $myrow['gross_wt'];
	$abc_class = $myrow['abc_class'];
	$excise_trafficno = $myrow['excise_trafficno'];
	$warr_period = $myrow['warr_period'];
	$item_mst_form = $myrow['item_mst_form'];
	$brand_code = $myrow['brand_code'];
	$material_type = $myrow['material_type'];
	$material_item_desc = $myrow['material_item_desc'];
	$cust_drwgno = $myrow['cust_drwgno'];
	$Mfg_drwgno = $myrow['Mfg_drwgno'];
	$Mfg_drwgcode = $myrow['Mfg_drwgcode'];
	$groupid = $myrow['groupid'];
	$users  = $myrow['users'];
	$make = $myrow['make'];
	$type_of_material =  $myrow['type_of_material'];
	$quality_of_material =  $myrow['quality_of_material'];
	$item_mst_form_rate =  $myrow['item_mst_form_rate'];
	$last_po_price =  $myrow['last_po_price'];
	$item_exciable  = $myrow['item_exciable'];
	$abtment       = $myrow['abtment'];

	$front_image  = $myrow['front_image'];
	$back_image       = $myrow['back_image'];

	$inventory_item = $myrow['inventory_item'];
	$batch_item = $myrow['batch_item'];
	$medicine_item = $myrow['medicine_item'];
    $generic_name        = $myrow['generic_name'];
   $ved_type            = $myrow['ved_type'];
   $item_strength       = $myrow['item_strength'];
    $snomed_ct           = $myrow['snomed_ct'];
    $schedule_name       = $myrow['schedule_name'];

    $narcotic            = $myrow['narcotic'];
    $is_high_risk        = $myrow['is_high_risk'];
    $is_emergency        = $myrow['is_emergency'];
	$item_in_use = !empty($myrow['item_in_use']) ? $myrow['item_in_use'] : 'Y';
    $item_not_in_use_reason = $myrow['item_not_in_use_reason'];

    $look_alike_item_id = parseSelectedItemIds($myrow['look_alike_item_id']);
    $sound_alike_item_id = parseSelectedItemIds($myrow['sound_alike_item_id']);

    $expiry_cutoff_days  = $myrow['expiry_cutoff_days'];
	$vatpurchase = $myrow['vat_purchase'];
	$cstpurchase = $myrow['cst_purchase'];
	$vatsales = $myrow['vat_sales'];
	$cstsales = $myrow['cst_sales'];
	$hsn_code = $myrow['hsn_code'];
	$hsn_applicable = $myrow['hsn_applicable'];
	$exempted = $myrow['exempted'];
	//$gst_sales=$myrow['gst_sales'];
	//$gst_purchase=$myrow['gst_purchase'];
	$gst_percentage = $myrow['gst_percentage'];
	$gst_applicable = $myrow['gst_applicable'];
}

?>

<div class="body_contain">
	<div class="tab_div">
		<form action="" method="post" enctype="multipart/form-data" onsubmit="return validatefun()">
			<input type="hidden" name="current_item_id" id="current_item_id" value="<?php echo htmlspecialchars($currentItemId, ENT_QUOTES); ?>" />
			<h1>Item Definition</h1>
			<h3>Product Information</h3>
			<table width="100%" border="0" cellpadding="3" cellspacing="0">
				<tr class="row1">
					<td align="right">Main Group</td>
					<td><select name="CategoryID" id="CategoryID" onchange="ShowDiv(this.value,'sub_id','item_subcategory.php'); loadLasaOptions();">
							<option value="000">---Select---</option>
							<?php

							$query1 = DB_query("select * from stockmaincategory where CompanyId='" . $_SESSION['ACGCompanyId'] . "'", $db);
							while ($result1 = DB_fetch_array($query1)) {
							?>
								<option value="<?php echo $result1['id']; ?>" <?php echo ($CategoryID == $result1['id'] ? 'selected' : '') ?>><?php echo $result1['stockmaincategoryname']; ?></option>
							<?php } ?>
						</select>
					</td>
					<td align="right">Sub Group</td>
					<td>
						<div id='sub_id'>
							<?php echo $unit;
							//echo	$catid= $s->GetFieldValue('stockmaincategory',"id='".$CategoryID."'",'stockmaincategoryid');
							?>
							<select name="sub_group" id="sub_group" onchange="get_item(this.value); loadLasaOptions();">
								<option value="000">Select</option>
								<?php
								if ($CategoryID != "") {
									echo "select * from stockcategory where stockmaincategory ='" . $CategoryID . "'";
									$sql = "select * from stockcategory where stockmaincategory ='" . $CategoryID . "' ";
								?>
									<?php
									$result = DB_query($sql, $db);
									while ($row = DB_fetch_array($result)) {
									?>
										<option value="<?php echo $row['id']; ?>" <?php echo ($SubCategoryID == $row['id'] ? 'selected' : '') ?>><?php echo $row['categorydescription']; ?></option>
								<?php }
								} ?>
							</select>
						</div>
					</td>
					
					<td colspan="2" rowspan="2" align="center"><svg id="barcode_view" style="height: 38px;"></svg></td>

					<!-- <td align="right">Barcode</td>
					<td><input type="text" name="barcode" id="barcode_input" value="<?php echo $barcode; ?>" /></td> -->


					<!-- <td width="13%" align="right">Store Location</td>
    <td>
	<?php //echo $orig_local;
	$sql_store = "SELECT * FROM storetype where CompanyId='" . $_SESSION['ACGCompanyId'] . "'";
	$result_store = DB_query($sql_store, $db); ?>
	    <select name="orig_local" id="orig_local" style="width:100%;" onchange="blankItem();">
		<option value="000">Select</option>
		<?php while ($rx = DB_fetch_array($result_store)) { ?>
		
		<option value="<?php echo $rx['id']; ?>"  <?php echo ($rx['id'] == $orig_local ? 'selected' : '') ?>><?php echo $rx['StoreName'] ?></option>
 		<?php } ?>
		</select></td> -->
					<td colspan="2">&nbsp;</td>
				</tr>
				<tr class="row1">
					<td align="right">Item Code</td>
					<td><input type="text" id="StockID" name="StockID" value="<?php if ($StockID != '') {
																					echo $StockID;
																				} ?>" autocomplete="off" /></td>
					<td align="right">Item Name</td>
					<td><input name="item_name" id="item_name" type="text" value="<?php echo $item_name; ?>" autocomplete="off" />
						<input type="hidden" name="item_name1" id="item_name1" value="" />
					</td>
					<!-- <td align="right">Abatement %</td>
    <td>
    	<input type="text" name="abtment" value="<?php echo $abtment; ?>" id="abtment" placeholder="%"  onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)'>
    </td> -->
					<!-- <td colspan="2">&nbsp;</td> -->



					
					
				</tr>

				<tr class="row1">
					<!--<td align="right">Model Group</td>
    <td  style="vertical-align: top;">
	<?php $Sqlprodmanu = DB_query("SELECT * FROM prd_model_group where CompanyId='" . $_SESSION['ACGCompanyId'] . "'", $db); ?>
		<select name="modalgroup" id="modalgroup" style="width:98%;vertical-align: top;wi">
		<option value="0" >-Root-</option>
				<?php
				if (DB_Num_rows($Sqlprodmanu) > 0) {
					while ($GetProdData = DB_fetch_array($Sqlprodmanu)) { ?>
						<option value="<?php echo $GetProdData['id'];  ?>"<?php if ($make == $GetProdData['id']) {
																				echo "Selected";
																			} ?>><?php echo $GetProdData['model_group_name'];  ?></option>
				<?php }
				} ?>				
			</select>
			</td>  -->
					<td align="right">Item Description</td>
					<td colspan="5"><textarea name="item_desc" id="item_desc" style="width:99%;vertical-align: top;"><?php echo $item_desc; ?></textarea></td>
				
				
				
				
				
				
				</tr>

				<tr class="row1">
					<td width="13%" align="right">Unit</td>
					<td width="20%"><?php echo $ClassUnitMeasure->UnitMeasure($mst_unitid, 'mst_unitid'); ?></td>
					<td width="13%" align="right">Alt. Unit</td>
					<td width="20%"><?php echo $ClassUnitMeasure->UnitMeasure($conv_unit, 'conv_unit'); ?></td>
					<td width="13%" align="right">Conv. Factor</td>
					<td><input type="text" name="conv_factor" id="conv_factor" value="<?php echo $conv_factor; ?>" onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' /></td>
				</tr>
				<!-- <tr class="row1">
    <td align="right">Min Level</td>
    <td><input type="text"  value="<?php echo $min_level; ?>"  name="min_level" /></td>
    <td align="right">Max Level</td>
    <td><input type="text"   value="<?php echo $max_level; ?>" name="max_level" /></td>
    <td align="right">Reorder Level</td>
    <td><input type="text"   value="<?php echo $reorder_level; ?>" name="reorder_level" /></td>
  </tr> -->
				<tr class="row1">
					<td align="right">Last Purchase Price</td>
					<td><input type="text" value="<?php echo $last_po_price; ?>" name="last_po_price" id="last_po_price" onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' /></td>
					<td align="right">Mrp Rate</td>
					<td><input type="text" value="<?php echo $mrp_rate; ?>" name="mrp_rate" id="mrp_rate" onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' /></td>
					<td align="right">Net Rate</td>
					<td><input type="text" value="<?php echo $net_rate; ?>" name="net_rate" id="net_rate" onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' /></td>
				</tr>

				<tr class="row1">
					<td align="right">Net Wt.</td>
					<td><input type="text" value="<?php echo $net_wt; ?>" name="net_wt" id="net_wt" onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' /></td>
					<td align="right">Gross Wt.</td>
					<td><input type="text" name="gross_wt" id="gross_wt" value="<?php echo $gross_wt; ?>" onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' /></td>
					<td align="right">Classification</td>
					<td><select name="abc_class">
							<option id="A" <?php echo $abcclass == 'A' ? 'selected' : ''; ?>>A</option>
							<option id="B" <?php echo $abcclass == 'B' ? 'selected' : ''; ?>>B</option>
							<option id="C" <?php echo $abcclass == 'C' ? 'selected' : ''; ?>>C</option>
						</select></td>
				</tr>

				<tr class="row1">
					<td align="right">Tariff No.</td>
					<td><input type="text" name="excise_trafficno" value="<?php echo $excise_trafficno; ?>" /></td>
					<td align="right">Warranty</td>
					<td>
						<select name="warr_period">
							<option value="">----Select----</option>
							<option value="6" <?php echo $warr_period == '6' ? 'selected' : ''; ?>> 6 Months</option>
							<option value="12" <?php echo $warr_period == '12' ? 'selected' : ''; ?>>12 Months</option>
							<option value="18" <?php echo $warr_period == '18' ? 'selected' : ''; ?>>18 Months</option>
							<option value="24" <?php echo $warr_period == '24' ? 'selected' : ''; ?>>24 Months</option>
							<option value="30" <?php echo $warr_period == '30' ? 'selected' : ''; ?>>30 Months</option>
							<option value="36" <?php echo $warr_period == '36' ? 'selected' : ''; ?>>36 Months</option>
							<option value="42" <?php echo $warr_period == '42' ? 'selected' : ''; ?>>42 Months</option>
							<option value="48" <?php echo $warr_period == '48' ? 'selected' : ''; ?>>48 Months</option>
							<option value="54" <?php echo $warr_period == '54' ? 'selected' : ''; ?>>54 Months</option>
							<option value="60" <?php echo $warr_period == '60' ? 'selected' : ''; ?>>60 Months</option>
						</select>
					</td>
					<td colspan="2"></td>
				</tr>
			</table>
			<br>
			<h3>Price Information</h3>
			<table width="100%" border="0" cellpadding="3" cellspacing="0">
				<tr class="row1">
					<td width="13%" align="right">MRP <input name="item_mst_form" type="radio" value="MRrate" <?php echo $item_mst_form == 'MRrate' ? 'checked' : '' ?> /></td>
					<td colspan="2">Price List <input name="item_mst_form" type="radio" value="pricelist" <?php echo $item_mst_form == 'pricelist' ? 'checked' : '' ?> />
						Tolerance(%) <input style="width:50%;" name="item_mst_form_rate" id="item_mst_form_rate" value="<?php echo $item_mst_form_rate; ?>" onkeypress='javascript:return isNumberKey(this,event)' maxlength='11' onblur='javascript:validate_floating(this.value,this.id)' /></td>
					<td width="20%">&nbsp;</td>
					<td width="13%" align="right">Inventory Item <input name="inventory_item" type="radio" value="Inventory Item" <?php echo $inventory_item == 'Inventory Item' ? 'checked' : '' ?> /></td>
					<td width="20%">Service Item <input name="inventory_item" type="radio" value="Service Item" <?php echo $inventory_item == 'Service Item' ? 'checked' : '' ?> /></td>
				</tr>
			</table>
			<br>
			<h3>Tax description</h3>
			<?php
			if ($exempted == '1') {
				$dis_exempted = 'disabled';
			} else {
				$dis_exempted = '';
			}

			?>
			<table width="100%" border="0" cellpadding="3" cellspacing="0">
				<tr class="row1">
					<td width="13%" align="right">GST</td>
					<td width="35%"><select name="pur_vat" id="pur_vat" <?php echo $dis_exempted; ?> onchange="syncGstPercentageFromTax();">
							<option value="0">Select</option>
							<?php
							$purvat = DB_query("select * from sales_tax_master where sales_for='GI'", $db);
							while ($purrow = DB_fetch_array($purvat)) {
								$isSelected = false;
								if ($vatpurchase == $purrow['salestax_id']) {
									$isSelected = true;
								} elseif (($vatpurchase == '' || $vatpurchase == '0') && trim((string)$gst_percentage) !== '' && trim((string)$gst_percentage) == trim((string)$purrow['taxrate'])) {
									$isSelected = true;
								}
							?>
								<option value="<?php echo $purrow['salestax_id']; ?>" data-taxrate="<?php echo $purrow['taxrate']; ?>" <?php if ($isSelected) { ?> selected <?php } ?>><?php echo $purrow['tax_code']; ?></option>
							<?php } ?>
						</select></td>
					<!-- <td width="13%" align="right">Cst</td>
					<td><select name="pur_cst" id="pur_cst" <?php echo $dis_exempted; ?>>
							<option value="0">Select</option>
							<?php
							$purvat1 = DB_query("select * from sales_tax_master where sales_for='CI'", $db);
							while ($purrow1 = DB_fetch_array($purvat1)) {
							?>
								<option value="<?php echo $purrow1['salestax_id']; ?>" <?php if ($cstpurchase == $purrow1['salestax_id']) { ?> selected <?php } ?>><?php echo $purrow1['tax_code']; ?></option>
							<?php } ?>
						</select></td>
				</tr>
				<tr class="row1">
					<td align="right">Vat</td>
					<td><select name="sale_vat" id="sale_vat" <?php echo $dis_exempted; ?>>
							<option value="0">Select</option>
							<?php
							$purvat2 = DB_query("select * from sales_tax_master where sales_for='VO'", $db);
							while ($purrow2 = DB_fetch_array($purvat2)) {
							?>
								<option value="<?php echo $purrow2['salestax_id']; ?>" <?php if ($vatsales == $purrow2['salestax_id']) { ?> selected <?php } ?>><?php echo $purrow2['tax_code']; ?></option>
							<?php } ?>
						</select></td>
					<td align="right">Cst</td>
					<td><select name="sale_cst" id="sale_cst" <?php echo $dis_exempted; ?>>
							<option value="0">Select</option>
							<?php
							$purvat3 = DB_query("select * from sales_tax_master where sales_for='CO'", $db);
							while ($purrow3 = DB_fetch_array($purvat3)) {
							?>
								<option value="<?php echo $purrow3['salestax_id']; ?>" <?php if ($cstsales == $purrow3['salestax_id']) { ?> selected <?php } ?>><?php echo $purrow3['tax_code']; ?></option>
							<?php } ?>
						</select></td> -->
				</tr>
				<!-- <tr class="row1">
<td align="right">GST</td>
<td><select name="sale_gst" id="sale_gst" <?php //echo $dis_exempted; 
											?>>
	<option value="0">Select</option>
	<?php
	//$purvat4=DB_query("select * from sales_tax_master where sales_for='GO'",$db);
	//while($purrow4=DB_fetch_array($purvat4))
	//{	
	?>
	 <option value="<?php //echo $purrow4['salestax_id'];
					?>" <?php //if($gstsales==$purrow4['salestax_id']) { 
						?> selected <?php //} 
									?> ><?php //echo $purrow4['tax_code'];
										?></option>
	 <?php //} 
		?>
</select></td>
<td align="right">GST</td>
<td><select name="purchase_gst" id="purchase_gst" <?php //echo $dis_exempted; 
													?>>
	<option value="0">Select</option>
	<?php
	//$purvat5=DB_query("select * from sales_tax_master where sales_for='GI'",$db);
	//while($purrow5=DB_fetch_array($purvat5))
	//{	
	?>
	 <option value="<?php //echo $purrow5['salestax_id'];
					?>" <?php //if($cstsales==$purrow5['salestax_id']) { 
						?> selected <?php //} 
									?> ><?php //echo $purrow5['tax_code'];
										?></option>
	 <?php //} 
		?>
</select></td>
</tr> -->
			</table>
			<br>
			<h3>Other Information</h3>
			<table width="100%" border="0" cellpadding="3" cellspacing="0">
				<tr class="row1">
					<?php if ($item_name_auto == '1') {
						$state_item_name = 'onkeyup="setItemName()"'; ?>
						<input type="hidden" name="setItemName_Flag" id="setItemName_Flag" value="1" />
					<?php
					} else {
						$state_item_name = '';
					}
					?>
					<td width="13%" align="right">Brand</td>
					<td width="20%"><input type="text" value="<?php echo $shade_name; ?>" id="shade_name" name="shade_name" placeholder="Comma separated brands" title="Use commas to enter multiple brands" <?php echo $state_item_name; ?> /></td>
					<td width="13%" align="right">Color</td>
					<td width="20%"><input type="text" value="<?php echo $product_sheet; ?>" id="product_sheet" <?php echo $state_item_name; ?> name="product_sheet" /></td>
					<td width="13%" align="right">Grade</td>
					<td><input type="text" <?php echo $state_item_name;  ?> value="<?php echo $serial_no; ?>" id="serial_no" name="serial_no" /></td>
				</tr>
				<tr class="row1">
					<td align="right">Type</td>
					<td><input type="text" <?php echo $state_item_name;  ?> name="brand_code" id="brand_code" value="<?php echo $brand_code; ?>" /></td>
					<td align="right">Material Type</td>
					<td>
						<select name="material_type" id="material_type" <?php echo $state_item_name; ?>>
							<option value="">Select</option>
							<option value="Tablet" <?php if ($material_type == 'Tablet') echo 'selected'; ?>>Tablet</option>
							<option value="Capsule" <?php if ($material_type == 'Capsule') echo 'selected'; ?>>Capsule</option>
							<option value="Syrup" <?php if ($material_type == 'Syrup') echo 'selected'; ?>>Syrup</option>
							<option value="Injection" <?php if ($material_type == 'Injection') echo 'selected'; ?>>Injection</option>
							<option value="Suspension" <?php if ($material_type == 'Suspension') echo 'selected'; ?>>Suspension</option>
							<option value="Drops" <?php if ($material_type == 'Drops') echo 'selected'; ?>>Drops</option>
							<option value="Cream" <?php if ($material_type == 'Cream') echo 'selected'; ?>>Cream</option>
							<option value="Ointment" <?php if ($material_type == 'Ointment') echo 'selected'; ?>>Ointment</option>
							<option value="Gel" <?php if ($material_type == 'Gel') echo 'selected'; ?>>Gel</option>
							<option value="Powder" <?php if ($material_type == 'Powder') echo 'selected'; ?>>Powder</option>
							<option value="Solution" <?php if ($material_type == 'Solution') echo 'selected'; ?>>Solution</option>
							<option value="Spray" <?php if ($material_type == 'Spray') echo 'selected'; ?>>Spray</option>
							<option value="Lotion" <?php if ($material_type == 'Lotion') echo 'selected'; ?>>Lotion</option>
							<option value="Infusion" <?php if ($material_type == 'Infusion') echo 'selected'; ?>>Infusion</option>
							<option value="Inhaler" <?php if ($material_type == 'Inhaler') echo 'selected'; ?>>Inhaler</option>
						</select>
					</td>
					<td align="right">Pack Description</td>
					<td><input type="text" name="material_item_desc" <?php echo $state_item_name;  ?> id="material_item_desc" value="<?php echo $material_item_desc; ?>" /></td>
				</tr>
			</table>
			<br>

	<?php
$currentItemId = !empty($_REQUEST['itemcode']) ? trim((string) $_REQUEST['itemcode']) : '';
$lookAlikeIds = isset($look_alike_item_id) ? $look_alike_item_id : array();
$soundAlikeIds = isset($sound_alike_item_id) ? $sound_alike_item_id : array();
$lookAlikeOrder = !empty($lookAlikeIds) ? "CASE WHEN id IN('" . implode("','", $lookAlikeIds) . "') THEN 0 ELSE 1 END," : "";
$soundAlikeOrder = !empty($soundAlikeIds) ? "CASE WHEN id IN('" . implode("','", $soundAlikeIds) . "') THEN 0 ELSE 1 END," : "";
$sqlLookAlikeLASA = "
SELECT id,item_name
FROM item_master
WHERE CategoryID='".$CategoryID."'
AND SubCategoryID='".$SubCategoryID."'
".($currentItemId !== '' ? "AND id<>'".$currentItemId."'" : "")."
ORDER BY ".$lookAlikeOrder." item_name";

$sqlSoundAlikeLASA = "
SELECT id,item_name
FROM item_master
WHERE CategoryID='".$CategoryID."'
AND SubCategoryID='".$SubCategoryID."'
".($currentItemId !== '' ? "AND id<>'".$currentItemId."'" : "")."
ORDER BY ".$soundAlikeOrder." item_name";
?>
<h3>Medicine Information</h3>

<table width="100%" border="0" cellpadding="3" cellspacing="0">

<tr class="row1">

    <td align="right">Generic Name</td>
    <td>
        <input type="text" name="generic_name"
               value="<?php echo $generic_name; ?>"
               placeholder="Comma separated generic names"
               title="Use commas to enter multiple generic names">
    </td>
</tr>

<tr class="row1">
    <td align="right">VED</td>
    <td>
        <select name="ved_type">
            <option value="">Select</option>
            <option value="Vital" <?php if($ved_type=='Vital') echo 'selected'; ?>>Vital</option>
            <option value="Essential" <?php if($ved_type=='Essential') echo 'selected'; ?>>Essential</option>
            <option value="Desired" <?php if($ved_type=='Desired') echo 'selected'; ?>>Desired</option>
        </select>
    </td>

    <td align="right">Item Strength(Dosage)</td>
    <td>
        <input type="text"
               name="item_strength"
               value="<?php echo $item_strength; ?>">
    </td>
</tr>

<tr class="row1">
    <td align="right">SNOMED CT</td>
    <td>
        <input type="text"
               name="snomed_ct"
               value="<?php echo $snomed_ct; ?>">
    </td>

    <td align="right">Schedule</td>
    <td>
        <select name="schedule_name">
            <option value="">Select</option>
            <option value="Schedule H" <?php if($schedule_name=='Schedule H') echo 'selected'; ?>>Schedule H</option>
            <option value="Schedule H1" <?php if($schedule_name=='Schedule H1') echo 'selected'; ?>>Schedule H1</option>
            <option value="Schedule X" <?php if($schedule_name=='Schedule X') echo 'selected'; ?>>Schedule X</option>
            <option value="Schedule G" <?php if($schedule_name=='Schedule G') echo 'selected'; ?>>Schedule G</option>
            <option value="Schedule OTC" <?php if($schedule_name=='Schedule OTC') echo 'selected'; ?>>Schedule OTC</option>
        </select>
    </td>
</tr>

<tr class="row1">
    <td align="right">Narcotic</td>
    <td>
        <input type="checkbox"
               name="narcotic"
               value="Y"
               <?php if($narcotic=='Y') echo 'checked'; ?>>
    </td>

    <td align="right">High Risk</td>
    <td>
        <input type="checkbox"
               name="is_high_risk"
               value="Y"
               <?php if($is_high_risk=='Y') echo 'checked'; ?>>
    </td>
</tr>

<tr class="row1">
    <td align="right">Emergency Item</td>
    <td>
        <input type="checkbox"
               name="is_emergency"
               value="Y"
               <?php if($is_emergency=='Y') echo 'checked'; ?>>
    </td>

    <td align="right">Expiry Cut Off (Days)</td>
    <td>
        <input type="text"
               name="expiry_cutoff_days"
               value="<?php echo $expiry_cutoff_days; ?>">
    </td>
</tr>

<tr class="row1">

<td align="right">Look Alike</td>
<td>
<select name="look_alike_item_id[]" id="look_alike_item_id" multiple size="5">

<?php
$resultLASA = DB_query($sqlLookAlikeLASA,$db);
while($rowLASA = DB_fetch_array($resultLASA)){
?>
<option value="<?php echo $rowLASA['id']; ?>"
<?php if(in_array($rowLASA['id'],$look_alike_item_id)) echo 'selected'; ?>>
<?php echo $rowLASA['item_name']; ?>
</option>
<?php } ?>

</select>
</td>

<td align="right">Sound Alike</td>
<td>
<select name="sound_alike_item_id[]" id="sound_alike_item_id" multiple size="5">

<?php
$resultLASA = DB_query($sqlSoundAlikeLASA,$db);
while($rowLASA = DB_fetch_array($resultLASA)){
?>
<option value="<?php echo $rowLASA['id']; ?>"
<?php if(in_array($rowLASA['id'],$sound_alike_item_id)) echo 'selected'; ?>>
<?php echo $rowLASA['item_name']; ?>
</option>
<?php } ?>

</select>
</td>

</tr>

</table>

			<table width="100%" border="0" cellpadding="3" cellspacing="0">
				<tr class="row1">
					<td width="13%" align="right">Item Front Image</td>
					<td width="20%"><input size="30" name="front_image" type="file" />
						<?php if ($_REQUEST['action'] == 'edit' || $_REQUEST['action'] == 'view') {
							if ($front_image != "") {
						?>
								<a href="download_items.php?download_file=<?php echo $front_image; ?>"><?php echo $front_image; ?></a>
							<?php
							} else {
							?>
								File Not Attached
						<?php
							}
						} ?>
					</td>
					<td width="13%" align="right">Item Back Image</td>
					<td width="20%"><input size="23" name="back_image" type="file" />
						<?php if ($_REQUEST['action'] == 'edit' || $_REQUEST['action'] == 'view') {
							if ($back_image != "") {
						?>
								</br><a href="download_items.php?download_file=<?php echo $back_image; ?>"><?php echo $back_image; ?></a>
							<?php
							} else {
							?>
								</br>File Not Attached
						<?php
							}
						} ?>
					</td>
					<td width="13%">&nbsp;</td>
					<td></td>
				</tr>
				<!-- <tr class="row1">
					<td align="right">BOM Required</td>
					<td><input name="type_of_material" type="checkbox" value="Bill" <?php echo $type_of_material == 'Bill' ? 'checked' : '' ?> /> </td>
<td align="right">Quality Check</td>
					<td><input name="quality_of_material" type="checkbox" value="QualityCheck" <?php echo $quality_of_material == 'QualityCheck' ? 'checked' : '' ?> /> </td>
					<td align="right">Excisable</td>
					<td><input name="item_exciable" type="radio" value="Y" <?php echo $item_exciable == 'Y' ? 'checked' : '' ?> />
						Non Excisable <input name="item_exciable" type="radio" value="N" <?php echo $item_exciable == 'N' ? 'checked' : '' ?> /></td>
				</tr> -->
				<tr class="row1">
					<td align="right">Quality Check</td>
					<td><input name="quality_of_material" type="checkbox" value="QualityCheck" <?php echo $quality_of_material == 'QualityCheck' ? 'checked' : '' ?> /> </td>
					<td align="right">Batch Item</td>
					<td>Yes <input name="batch_item" type="radio" value="Y" <?php echo $batch_item == 'Y' ? 'checked' : '' ?> />
						No <input name="batch_item" type="radio" value="N" <?php echo $batch_item == 'N' ? 'checked' : '' ?> /></td>
					<td colspan="2"></td>
					<td align="right">Medicine Item</td>
					<td>Yes <input name="medicine_item" type="radio" value="Y" <?php echo $medicine_item == 'Y' ? 'checked' : '' ?> />
						No <input name="medicine_item" type="radio" value="N" <?php echo $medicine_item == 'N' ? 'checked' : '' ?> /></td>
				</tr>
<tr class="row1">

    <td align="right">Item In Use</td>
    <td>
        Yes
        <input type="radio"
               name="item_in_use"
               value="Y"
               <?php echo ($item_in_use != 'N') ? 'checked' : ''; ?>
               onclick="toggleItemInUseReason();">

        No
        <input type="radio"
               name="item_in_use"
               value="N"
               <?php echo ($item_in_use == 'N') ? 'checked' : ''; ?>
               onclick="toggleItemInUseReason();">
    </td>

    <td id="item_reason_label"
        align="right"
        style="<?php echo ($item_in_use=='N') ? '' : 'display:none;'; ?>">
        Reason
    </td>

    <td id="item_reason_field"
        style="<?php echo ($item_in_use=='N') ? '' : 'display:none;'; ?>">

        <select name="item_not_in_use_reason"
                id="item_not_in_use_reason">
            <option value="">Select</option>
            <option value="Quarantine" <?php if($item_not_in_use_reason=='Quarantine') echo 'selected'; ?>>Quarantine</option>
            <option value="Damaged" <?php if($item_not_in_use_reason=='Damaged') echo 'selected'; ?>>Damaged</option>
            <option value="QC Check Failed" <?php if($item_not_in_use_reason=='QC Check Failed') echo 'selected'; ?>>QC Check Failed</option>
            <option value="Expired" <?php if($item_not_in_use_reason=='Expired') echo 'selected'; ?>>Expired</option>
        </select>

    </td>

</tr>
				<tr class="row1">
					<td style="text-align:right;">HSN Code</td>
					<td><input type="radio" name="hsn" id="hsn" value="1" onclick="get_hsncode(this.value,this.id);" <?php if ($hsn_applicable == '1') { ?> checked="checked" <?php } ?> />Applicable
						<input type="radio" name="hsn" id="hsn1" value="0" onclick="get_hsncode(this.value,this.id);" <?php if ($hsn_applicable == '0') { ?> checked="checked" <?php } ?> />Not Applicable
					</td>
					<td id="abc" <?php if ($_REQUEST['action'] != 'edit') { ?>style="display:none;" <?php } else {
																									if ($hsn_applicable == '1') { ?>style="display:block;" <?php } else { ?> style="display:none;" <?php }
																																															} ?>><input type="text" name="hsn_code" id="hsn_code" placeholder="HSN Code" value="<?php echo $hsn_code; ?>" /> </td>
					<td id="abc1" <?php if ($_REQUEST['action'] != 'edit') { ?>style="display:none;" <?php } else {
																										if ($hsn_applicable == '1') { ?>style="display:block;" <?php } else { ?> style="display:none;" <?php }
																																																} ?>> </td>
					<td><input type="checkbox" name="check_exempted" id="check_exempted" onclick="getexempted(this.id);" value="1" <?php if ($exempted == '1') { ?> checked="checked" <?php } ?> />Exempted</td>
					<td><input type="text" name="gst_percentage" id="gst_percentage" placeholder="GST Percentage" value="<?php echo $gst_percentage; ?>" readonly /> </td>
					<td colspan="2"></td>
				</tr>

			</table>
			<p style="text-align:center;">
				<?php if ($_REQUEST['action'] != 'view') { ?>
					<input name="SaveItem" type="submit" value="Save Item" class="search" onclick="return checkvalidate1()" /> <a href="index.php?route=item_list&modid=<?php echo $_REQUEST['modid'] ?>&frmid=<?php echo $_REQUEST['frmid'] ?>"><input name="save" type="button" value="Cancel" class="search" /></a><?php } ?>
			</p>
		</form>

	</div>
</div>


<script>
	function isNumberKey(sender, evt) {
		var txt = sender.value;
		//alert(evt.which);
		var dotcontainer = txt.split('.');
		var charCode = (evt.which) ? evt.which : event.keyCode;
		//alert(event.keyCode);
		if (!(dotcontainer.length == 1 && charCode == 46) && charCode > 31 && (charCode < 48 || charCode > 57))
			return false;

		return true;
	}

	function validate_floating(val, id) {
		var data = id.split("_");
		var val1 = parseFloat(val);

		if (val == "" || val1 == 0) { //document.getElementById(id).value="";
			//document.getElementById(id).focus();
		} else {
			document.getElementById(id).value = val1.toFixed(2);
			//document.getElementById(id).value=Math.floor(val1 * 100) / 100;   /* Fixing decimal two points*/ 
		}
	}

	function checkvalidate() {
		if (document.getElementById("CategoryID").value == '000') {
			alert("Must Select Category");
			return false;
		}
		if (document.getElementById("sub_group").value == '000') {
			alert("Must Select Sub Category");
			return false;
		}
		if (document.getElementById("orig_local").value == '000') {
			alert("Must Select Store Locations");
			return false;
		}

		if (document.getElementById("item_name").value == '') {
			alert("Must Enter Item Name");
			return false;

		}
		/*
		if(document.getElementById("setItemName_Flag").value!='')
		{
			if(document.getElementById("shade_name").value=='')
			{
				alert("Must Enter Shade Name");
				return false;
			
			}
			if(document.getElementById("product_sheet").value=='')
			{
				alert("Must Enter Product Sheet");
				return false;
			
			}
			if(document.getElementById("serial_no").value=='')
			{
				alert("Must Enter Serial No");
				return false;
			
			}
			if(document.getElementById("brand_code").value=='')
			{
				alert("Must Enter Brand Code");
				return false;
			
			}
			if(document.getElementById("material_type").value=='')
			{
				alert("Must Enter Material Type");
				return false;
			
			}
			if(document.getElementById("material_item_desc").value=='')
			{
				alert("Must Enter Material Item Desc");
				return false;
			
			}
			

		}*/
		/*if(document.getElementById("item_desc").value=='')
		{
		alert("Must Enter Item Desc");
		return false;
		}*/
		return true;




	}


	function get_hsncode(val, id) {
		if (val == 1) {
			document.getElementById("abc").style.display = '';
			document.getElementById("abc1").style.display = '';
		} else {
			document.getElementById("hsn_code").value = '';
			document.getElementById("abc").style.display = 'none';
			//document.getElementById("gst_percentage").value='';
			document.getElementById("abc1").style.display = 'none';

		}
	}

	function toggleItemInUseReason() {

    var val = document.querySelector('input[name="item_in_use"]:checked').value;

    if (val === "N") {

        document.getElementById("item_reason_label").style.display = "";
        document.getElementById("item_reason_field").style.display = "";

    } else {

        document.getElementById("item_reason_label").style.display = "none";
        document.getElementById("item_reason_field").style.display = "none";
        document.getElementById("item_not_in_use_reason").selectedIndex = 0;

    }
}

window.onload = function () {
    initializeGstSelection();
    toggleItemInUseReason();
};

	function getexempted(id) {
		//alert("hi");
		document.getElementById('gst_percentage').readOnly = true;
		if (document.getElementById("" + id).checked == true) {
			document.getElementById('gst_percentage').value = '';
		} else {
			syncGstPercentageFromTax();
		}
	}

	if (window.addEventListener) {
		window.addEventListener('load', initializeGstSelection);
	} else if (window.attachEvent) {
		window.attachEvent('onload', initializeGstSelection);
	}
</script>


<script>

  
    function generateBarcode() {
        const barcodeInput = document.getElementById('StockID');
        const barcodeView = document.getElementById('barcode_view');

        const barcodeValue = barcodeInput.value.trim();

        if (barcodeValue !== '') {
            JsBarcode("#barcode_view", barcodeValue, {
                format: "CODE128",
                displayValue: true,
                lineColor: "#000",
                width: 2,
                height: 60,
                margin: 2
            });
        } else {
            barcodeView.innerHTML = '';
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        const barcodeInput = document.getElementById('barcode_input');

        // If input already has value, barcode will show automatically
        generateBarcode();

        // If user types, barcode will update automatically
        barcodeInput.addEventListener('input', generateBarcode);
    });

</script>
