<?php ob_start();
function getFieldvalue_cake($table, $condition, $val, $field)
{
	global $db;
	//echo "select ".$field." from ".$table." where ".$condition." ='".$val."'";
	$sql = mysqli_query($db, "select " . $field . " from " . $table . " where " . $condition . " ='" . $val . "'");
	$r = mysqli_fetch_array($sql);
	//echo "select ".$field." from ".$table." where ".$condition." ='".$val."'"; 
	return ($r[$field]);
}
if (isset($_POST['Save'])) {



	date_default_timezone_set('Asia/Calcutta');


	$prefix_sql = DB_query("Select * from prefix_tbl where prefix_name='" . $_REQUEST['frmid'] . "'  and module_id='" . $_REQUEST['modid'] . "' ", $db);
	$prefix_row = DB_fetch_array($prefix_sql);
	//$prefixf=explode("/",$prefix_row['prefix_code']);
	$prefixcode = $prefix_row['prefix_code'];
	//  $prefixcode="jjRS/RS";
	$financial = substr($_SESSION['YearStart'], -2) . "-" . substr($_SESSION['YearEnd1'], -2);
	$sql = "select * from material_return where site = '" . $_REQUEST['site'] . "' order by id desc limit 0,1";
	$result = DB_query($sql, $db);
	$numrows = DB_num_rows($result);
	$sqldata = DB_query("select locationname from locations where loccode='" . $_REQUEST['site'] . "'", $db);
	$sqltext = DB_fetch_array($sqldata);
	$sitename = $sqltext['locationname'];
	$siteCode = $sitename;
	if ($numrows > 0) {
		$i = 0;
		$strmax = "";
		$myrow = DB_Fetch_array($result);
		$ExplBill = explode("/", $myrow['return_slipno']);
		$maxval = $ExplBill[3]; {
			$strChar = $_REQUEST['site'] . "/" . $financial . "/" . $prefixcode . "/";
		}
	} else {
		$maxval = 0;
		$strChar = $_REQUEST['site'] . "/" . $financial . "/" . $prefixcode . "/";
	}
	$strFinal = $maxval + 1;
	$strBothFinal = $strChar . str_pad($strFinal, 4, "0", STR_PAD_LEFT);
	if (empty($_REQUEST['received_by'])) {
		$receive = $_REQUEST['issueto'];
	} else {
		$receive = $_REQUEST['received_by'];
	}
	$sql = "INSERT INTO material_return set
						site='" . $_REQUEST['site'] . "',
						store='" . $_REQUEST['store'] . "',  
						receivefrom='" . $receive . "',  
						issue_slipno='" . $_REQUEST['issue_slipno'] . "',  
						return_slipno='" . $strBothFinal . "',  
						returndate='" . FormatDateForSQL1($_REQUEST['returndate']) . "',
						remarks='" . $_REQUEST['remarks'] . "',
						slip_return_type='" . $_REQUEST['return_type'] . "',
						createdby='" . $_SESSION['UserID'] . "', 
						transaction_time='" . date("Y-m-d H:i:s") . "', 
						store_to='" . $_REQUEST['to_store'] . "',
						createddate='" . FormatDateForSQL(date('d/m/Y')) . "' ";
	$insertResult = DB_query($sql, $db, $ErrMsg);
	$Lastreq_id = DB_Last_Insert_ID($db, 'material_return', $ErrMsg);
	//$Lastreq_id=1;

	if ($Lastreq_id != '') {
		$totalreceivedqty = 0;
		for ($i = 0; $i < count($_REQUEST['itemdataid']); $i++) {

			// $totalamt=($_REQUEST['rate'][$i]*$_REQUEST['receiveqty'][$i]);	
			$sql2 = "INSERT INTO material_return_details set
								parentId='" . $Lastreq_id . "', 
								itemid='" . $_REQUEST['itemdataid'][$i] . "', 
								issueqty='" . $_REQUEST['pending_qty'][$i] . "',
								stock_qty2='" . $_REQUEST['secondaryqty'][$i] . "',
								mst_unitid='" . $_REQUEST['uom'][$i] . "',
								conv_unitid='" . $_REQUEST['uom1'][$i] . "',
								confac='" . $_REQUEST['confac[]'][$i] . "',
								batchno='" . $_REQUEST['batchno'][$i] . "',
								receiveqty='" . $_REQUEST['issueqty'][$i] . "'";
			// $totalreceivedqty=$totalreceivedqty+$_REQUEST['receiveqty'][$i];
			$insertResult2 = DB_query($sql2, $db, $ErrMsg);

			$dtls_Lastreq_id = DB_Last_Insert_ID($db, 'material_return_details', $ErrMsg);

			// ###################################### STOCK VALUATION ###################################################

			$primary_unit = $s->getField('item_master', 'id', $_POST['itemdataid'][$i], 'mst_unitid');
			$secondary_unit = $s->getField('item_master', 'id', $_POST['itemdataid'][$i], 'conv_unit');
			$stock_rate = $s->GetFieldValue("stock_valuation_tbl", "against_voucher_main_id='" . $_REQUEST['issue_slipno'] . "'
             and  mst_itemid='" . $_POST['itemdataid'][$i] . "'", "inward_rate");

			$stock_qty = $s->GetFieldValue("stock_valuation_tbl", "against_voucher_main_id='" . $_REQUEST['issue_slipno'] . "'
             and  mst_itemid='" . $_POST['itemdataid'][$i] . "'", "pending_qty");

			$id1 = $s->GetFieldValue("stock_valuation_tbl", "against_voucher_main_id='" . $_REQUEST['issue_slipno'] . "'
                  and  mst_itemid='" . $_POST['itemdataid'][$i] . "'", "id");
			if ($stock_rate != '')
				$status1 = 1;
			else
				$status1 = 0;

			$data_stock['site']                     = $_REQUEST['site'];
			$data_stock['store']                    = $_REQUEST['to_store'];
			$data_stock['mst_itemid']               = $_POST['itemdataid'][$i];
			$data_stock['primary_unit']             = $primary_unit;
			$data_stock['secondary_unit']           = $secondary_unit;
			$data_stock['against_voucher_main_id']  = $Lastreq_id;
			$data_stock['against_voucher_dtls_id']  = $dtls_Lastreq_id;
			$data_stock['type']                     = 'RTN';
			$data_stock['inwardqty_primary']        = $_REQUEST['issueqty'][$i];
			$data_stock['inwardqty_secondary']      = $_REQUEST['secondaryqty'][$i];
			// $data_stock['inwared_value']            =$_REQUEST['issueqty'][$i]*$stock_rate;	
			// $data_stock['inward_rate']              =$stock_rate;	
			$data_stock['status']	                  = $status1;
			$data_stock['trasaction']               = FormatDateForSQL($_REQUEST['returndate']) . " " . date('H:i:s', time());
			$data_stock['batch_no']                 = $_REQUEST['batchno'][$i];
			$data_stock['against_tra_id']           = $_REQUEST['issue_slipno'];
			$data_stock['pending_qty']              = $_REQUEST['issueqty'][$i];
			$s->RecordInsert('stock_valuation_tbl', $data_stock);


			$data_stock1['site']                     = $_REQUEST['site'];
			$data_stock1['store']                    = $_REQUEST['store'];
			$data_stock1['mst_itemid']               = $_POST['itemdataid'][$i];
			$data_stock1['primary_unit']             = $primary_unit;
			$data_stock1['secondary_unit']           = $secondary_unit;
			$data_stock1['against_voucher_main_id']  = $Lastreq_id;
			$data_stock1['against_voucher_dtls_id']  = $dtls_Lastreq_id;
			$data_stock1['type']                     = 'RTN';
			$data_stock1['outwardqty_primary']        = $_REQUEST['issueqty'][$i];
			$data_stock1['outwardqty_secondary']      = $_REQUEST['secondaryqty'][$i];
			//$data_stock['outward_value']            =$_REQUEST['issueqty'][$i]*$stock_rate;	
			//$data_stock['inward_rate']              =$stock_rate;	
			$data_stock1['status']	                  = $status1;
			$data_stock1['trasaction']               = FormatDateForSQL($_REQUEST['returndate']) . " " . date('H:i:s', time());
			$data_stock1['batch_no']                 = $_REQUEST['batchno'][$i];
			$data_stock1['against_tra_id']           = $_REQUEST['issue_slipno'];
			$data_stock1['pending_qty']              = $_REQUEST['issueqty'][$i];
			$s->RecordInsert('stock_valuation_tbl', $data_stock1);

			$pending_qty_issue = $stock_qty - $_REQUEST['issueqty'][$i];

			if ($pending_qty_issue == 0)
				$flag = 1;
			else
				$flag = 0;
			// $update=DB_query("update stock_valuation_tbl set pending_qty='".$pending_qty_issue."',flag='".$flag."' where id='".$id1."'",$db);
			if ($_REQUEST['issueqty'][$i] >= $_REQUEST['pending_qty'][$i])
				$status_slip = "1";
			else
				$status_slip = "0";
			//  echo "update issueqty set status_Receive='".$status_slip."' where issue_id='".$_REQUEST['issue_slipno']."' 
			//and mst_itemid='".$_REQUEST['itemdataid'][$i]."'";

			$update = DB_query("update issueqty set status_Receive='" . $status_slip . "' where issue_id='" . $_REQUEST['issue_slipno'] . "' 
			          	and mst_itemid='" . $_REQUEST['itemdataid'][$i] . "'", $db);
		}
	}


	$get_num_rows = DB_query("Select * from issueqty where issue_id='" . $_REQUEST['issue_slipno'] . "'", $db);
	$num_rows = DB_num_rows($get_num_rows);
	$check_item_stat = DB_query("Select * from issueqty where issue_id='" . $_REQUEST['issue_slipno'] . "'
		and status_Receive='1'", $db);
	$received_num_rows = DB_num_rows($check_item_stat);

	if ($num_rows == $received_num_rows) {
		$updatePOStat = DB_query("Update addissue set status='Receive' where 
			id='" . $_REQUEST['issue_slipno'] . "'", $db);
	} else {

		$updatePOStat = DB_query("Update addissue set status='Pending' where 
			id='" . $_REQUEST['issue_slipno'] . "'", $db);
	}



	prnMsg(_('Record Insert Successfully'), 'success');
	$s->pageLocation("index.php?route=Inventory/transation/Return_Slip_index" . $rurl);
}
?>
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
	<div class="tab_div">
		<h1><?php echo $s->getField('modules_form', 'id', $_REQUEST['frmid'], 'frm_name'); ?></h1>
		<form name="form1" action="" method="post">
			<div align="center">
				<table width="100%" border="0" cellspacing="0" cellpadding="3">
					<tr class="row1">
						<td width="13%" align="right">Branch</td>
						<td width="20%">
							<?php
							if ($_SESSION['AssignedBranch'] != '') {
								$ss = "Select loccode, locationname from locations  where CompanyId='" . $_SESSION['ACGCompanyId'] . "' and loccode in('" . $_SESSION['AssignedBranch'] . "')";
								$site_sql = DB_query($ss, $db);
							} else {
								$ss = "Select loccode,locationname from locations where CompanyId='" . $_SESSION['ACGCompanyId'] . "'";
								$site_sql = DB_query($ss, $db);
							}
							?>
							<select name="site" id="site" onchange="showsitename159(this.value)">
								<option value="0">Select</option>
								<?php
								while ($myrow = DB_fetch_array($site_sql)) {
								?>
									<option value="<?php echo $myrow['loccode']; ?>" <?php echo ($_REQUEST['site'] == $myrow['loccode'] ? 'selected' : '') ?>><?php echo $myrow['locationname']; ?></option>
								<?php  }	?>
							</select>
						</td>
						<td width="13%" align="right">Store</td>
						<td width="20%">
							<select name="store" id="store" onchange="getIssuesleep(this.value);">
								<option value="0">Select Store</option>
								<?php
								$sql_store = "select   id, StoreCode, StoreName from storetype  where Store_Site in('" . $_SESSION['AssignedBranch'] . "') ";
								$resultStkLocs = DB_query($sql_store, $db);
								while ($myrow = DB_fetch_array($resultStkLocs)) {
									$k = '';
									if ($myrow['id'] == $_REQUEST['store'])
										$k = "selected"; ?>
									<option value="<?php echo $myrow['id']; ?>" <?php echo $k; ?>><?php echo $myrow['StoreName']; ?></option>
								<?php } ?>
							</select>
						</td>
						<!-- <td width="13%" align="right">Employee</td>
    <td><select name="received_by" id="received_by"  onchange="getIssuesleep(this.value)">
		<option value="0">Select</option>
	<?php
	$floor_sql = DB_query("Select * from empmaster where CompanyId='" . $_SESSION['ACGCompanyId'] . "' order by emp_name ASC  ", $db);
	while ($floor_row = DB_fetch_array($floor_sql)) {
		$p = '';
		if ($floor_row['id'] == $received_by)
			$p = 'selected';

	?>
	<option value="<?php echo $floor_row['id']; ?>"<?php echo $received_by == $floor_row['id'] ? 'selected' : ''; ?>><?php echo $floor_row['emp_name']; ?></option>
	<?php
	}
	?>
    </select></td> -->

						<td width="13%" align="right">Issue Slip No.</td>
						<td id="IssueSlip-div">
							<select name="issue_slipno" id="issue_slipno" onchange="getItemsDetails(this.value)">
								<option value="0">Select</option>
							</select>
						</td>
					</tr>
					<tr class="row1">
						<td align="right">Received Slip No.</td>
						<td><input name="return_slipno" type="text" id="return_slipno" value="Auto Generate" readonly /></td>
						<td align="right">Receive Date</td>
						<td><input name="returndate" type="text" id="returndate" readonly="" value="<?php echo date('d/m/Y') ?>" class="datepicker" /></td>
						<td align="right">Receipt type</td>
						<td><select name="return_type" id="return_type">
								<option value="Process">Process</option>
								<option value="Direct">Direct</option>
							</select>
						</td>
					</tr>
					<tr class="row1">
						<td align="right">To Store</td>
						<td><select name="to_store" id="to_store">
								<option value="0">Select</option>
							</select>
						</td>
						<td colspan="4">&nbsp;</td>
					</tr>
				</table>

				<div style="overflow:auto; width:100%; height:auto; margin:8px 0;">
					<div id="itemsdetails"></div>
				</div>

				<table width="100%" border="0" cellpadding="3" cellspacing="0">
					<tr class="row1">
						<td width="13%" align="right">Remarks</td>
						<td><textarea name="remarks" style="width:99%; height:60px;" rows="3" id="remark"><?php echo $mysqlrow['remarks']; ?></textarea></td>
					</tr>
				</table>
				<p style="text-align:center;"><input type="submit" name="Save" class="search" value="Save" onclick="return validate()" /></p>
		</form>

	</div>
</div>
<div id="lightbox1"></div>
<script language="javascript" type="text/javascript">
	function getItemsDetails(issueid) {

		var site = document.getElementById('site').value;
		var store = document.getElementById('store').value;

		$.post('FindIssueSlip.php', {
			'issueid': issueid,
			'showitems': 'yes',
			'site': site,
			'store': store
		}, function(data) {

			$('#itemsdetails').html(data);
		});
		getotherstore(issueid);

	}


	function getotherstore(str) {
		//alert(str);
		var type1 = 'issueid';

		$.post('FindIssueSlip.php', {
			'issueid': str,
			'type1': type1
		}, function(data) {
			$('#to_store').html(data);
		});


	}


	function isNumberKey(evt) {
		var charCode = (evt.which) ? evt.which : event.keyCode;
		if (charCode != 46 && charCode > 31 &&
			(charCode < 48 || charCode > 57))
			return false;

		return true;
	}

	function calamtNew(value, id) {
		var ids = id.split('_');
		if (ids[1] == undefined) {

		} else {
			var stock = document.getElementById('Stockbalance_' + ids[1]).value;
			var val = parseFloat(value);
			if (parseFloat(value) > parseFloat(stock)) {
				alert("Quantity can not be greater than stock");
				document.getElementById('issueqty_' + ids[1]).value = '';
				return false;

			}
			var conv = parseFloat(document.getElementById('confac_' + ids[1]).value);
			if (val == '') val = 0;
			var total = parseFloat(val * conv);
			document.getElementById('secondary_' + ids[1]).value = total.toFixed(2);
		}

	}






	function issuedetails(str) {
		var branch = document.getElementById("site").value;
		var godown = document.getElementById("store").value;

		if (str.length == 0) {
			document.getElementById("ISSUE").innerHTML = "";
			return;
		}
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				document.getElementById("ISSUE").innerHTML = xmlhttp.responseText;
			}
		}
		xmlhttp.open("GET", "get_IssueDetails.php?q=" + str + "&site=" + branch + "&store=" + godown, true);
		xmlhttp.send();

	}

	function calTotal(str) {
		var k = parseFloat(document.getElementById('issueqty_' + str).value);
		var j = parseFloat(document.getElementById('receiveqty_' + str).value);
		if (k < j) {
			alert("Receiveqty Not Grater then Issue Qty");
			document.getElementById('receiveqty_' + str).focus();
			document.getElementById('').hide();
		}
	}

	function getIssuesleep(str) {
		var site = document.getElementById('site').value;
		var type = 'issueslip';
		$.post('FindIssueSlip.php', {
			'site': site,
			'store': str,
			'type': type
		}, function(data) {
			//alert(data);
			$('#issue_slipno').html(data);
		});


	}





	function chkbalance(str) {


		//alert(str);
		var k = parseFloat(document.getElementById('pending_qty_' + str).value);
		var j = parseFloat(document.getElementById('receiveqty_' + str).value);
		var confac = document.getElementById("confac_" + str).value;

		if (k < j) {
			alert("Receive Qty Not Grater then Issue Qty Balance");
			document.getElementById('receiveqty_' + str).value = '';
			document.getElementById("secondary_" + str).value = '';
			document.getElementById('receiveqty_' + str).focus();
		} else {

			var qty = parseFloat(j) * parseFloat(confac);

			document.getElementById("secondary_" + str).value = qty.toFixed(2);
		}

	}

	function showsitename159(str) {

		$.post('GoDownIssueSlip1.php', {
			'site': str
		}, function(data) {
			$('#store').html(data);
		});

	}


	function validate() {
		if (document.getElementById("returndate").value == '') {
			alert("Please enter return date");
			return false;
		}
		if (document.getElementById("site").value == '0') {
			alert("Must Select Branch Name");
			return false;
		}
		if (document.getElementById("issueto").value == '0') {
			var count = 0;
		}
		if (document.getElementById("received_by").value == '0') {
			var count = 0;
		}
		if (document.getElementById("issueto").value != '0' || document.getElementById("received_by").value != '0') {
			var count = 1;
		}
		if (count == 0) {
			alert("Must Select Contractor Name /Employee Name");
			return false;
		}
		if (document.getElementById("issue_slipno").value == '') {
			alert("Must Select Issue Slip No");
			return false;
		}

		var rowCount = document.getElementById("count").value;

		//alert(rowCount);
		for (var i = 1; i <= rowCount; i++) {
			if (isNaN(document.getElementById("receiveqty_" + i).value)) {
				alert("Sting Not Allowed");
				document.getElementById("receiveqty_" + i).value = '';
				document.getElementById("receiveqty_" + i).focus();
				return false;
			}
			var countdata;
			if (document.getElementById("receiveqty_" + i).value == '') {
				countdata = 0;
			} else {
				countdata = 1;
			}
			if (countdata == 0) {
				alert("Must Enter Atleast One Return Qty");
				return false;
			}
			var issuqty = parseFloat(document.getElementById("pending_qty_" + i).value);
			var receiveqty;
			if (document.getElementById("receiveqty_" + i).value == '') {
				receiveqty = 0;
			} else {
				receiveqty = parseFloat(document.getElementById("receiveqty_" + i).value);
			}
			if (receiveqty > issuqty) {
				alert("Received Qty Not Greater Then Issue Qty");
				document.getElementById("receiveqty_" + i).value = '';
				document.getElementById("receiveqty_" + i).focus();
				return false;
			}
		}
		if (document.getElementById("returndate").value == '') {
			alert("Must Select Return Date");
			return false;
		}
		return true;

	}

	function displayBatch(value, id) {
		// alert("The paragraph was double-clicked."); 
		// alert(value+"  "+id);
		//alert(id);
		var itemcode = '';
		var itemname = '';
		var unit = '';
		var item_ids = '';

		if (id.indexOf('_') != '-1') {
			var ids = id.split('_');
			itemcode = document.getElementById('itemcode_' + ids[1]).value;
			itemname = document.getElementById('itemname_' + ids[1]).value;
			unit = document.getElementById('uom_' + ids[1]).value;
			unit1 = document.getElementById('uom1_' + ids[1]).value;
			item_ids = document.getElementById('itemid_' + ids[1]).value;
			//alert(item_ids);

		} else {
			itemcode = document.getElementById('itemcode').value;
			itemname = document.getElementById('itemname').value;
			unit = document.getElementById('uom_').value;
			unit1 = document.getElementById('uom1_').value;
			item_ids = document.getElementById('itemids').value;
			//alert("asdas"+item_ids);

		}

		if (itemcode == '') {
			alert("Please select items");
		} else if (itemname == '') {
			alert("Please enter itemname");
		} else if (unit == '') {
			alert("Please enter unit");
		} else {
			//var LeaveType=document.getElementById("LeaveType_"+tt2).value;
			$("#lightbox1").dialog({
				title: 'Batch List',
				modal: true,
				resizable: false,
				width: 900,
				height: 400,
				closeText: 'fechar',
				draggable: true,
				show: 'fade',
				hide: 'fade',
				dialogClass: 'main-dialog-class',
				buttons: {
					Exit: function() {
						$(this).dialog("close");
					}
				}
			});
			var site = document.getElementById("site").value;
			var store = document.getElementById("store").value;
			//var invoiceTime=$('#invoiceTime').val();
			//alert('Getstock_items_store.php?site='+site+'&invoicedate='+invoicedate+'&invoiceTime='+invoiceTime);
			$.ajax({
				url: 'getItemBatch.php?item_id=' + item_ids + '&batch_id=' + id + '&site=' + site + '&store=' + store,
				success: function(result) {
					$('#lightbox1').html(result);
				}
			});
		}
	}
</script>