<?php session_name('CAKEPHP'); session_start();
$PageSecurity = 2;
if (empty($_GET['identifier'])) {
			 $identifier=date('U');
		} else {
			$identifier=$_GET['identifier'];
		}
$title = _('Material Receipt Note');

$url_cancel= "index.php?route=LOG/transation/material_receipt_note_index".$rurl;
$url_add= "index.php?route=LOG/transation/material_receipt_note_add".$rurl;
$url_edit= "index.php?route=LOG/transation/material_receipt_note_edit".$rurl;
$url_view= "index.php?route=LOG/transation/material_receipt_note_view".$rurl;

//**************************************************************************************************************************//
	function privious_opening($site,$store,$item)
	{
	 global $db;
	 $receive=array();
	 $issueqty=array();	
	  $site=$site;
	  $store=$store;
	
/**************************************MRN*********************************************************************************/
	 
  
	$sqlmrn=DB_query("select sum(reciveqty) as reciveqty from dbl_addmrnqty 
	inner join dbl_addmrn on dbl_addmrn.id=dbl_addmrnqty.issue_id  where site='".$site."'
	 and StoreCode in ('".$store."')
	  and Cancel_status='N' and reciveqty!='0.00' 
	 and mst_itemid in ('".$item."')",$db);	
	 
	while($dbl_addmrn=DB_fetch_array($sqlmrn))
	{
	if($dbl_addmrn['reciveqty']!='')
	{
	$receive[]=$dbl_addmrn['reciveqty'];
	$total[]=$dbl_addmrn['total'];
	}
	}
		
/***************************************************Issue*****************************************************************/

	$sqlissue=DB_query("SELECT sum(issueqty) AS issueqty FROM 
                        issueqty INNER JOIN addissue ON addissue.id=issueqty.issue_id where site='".$site."' and
						mst_storeid in ('".$store."')  and issueqty!='0.00' 
						 and mst_itemid in ('".$item."') ",$db);	
	while($addissue=DB_fetch_array($sqlissue))
	{
	if($addissue['issueqty']!='')
	{
	$issueqty[]=$addissue['issueqty'];
	$total1[]=$addissue['total'];
	}
	}			
/***************************************************Receive***************************************************************/
	$sqlreceive=DB_query("SELECT sum(receiveqty) AS reciveqty
	                    FROM  material_return_details INNER JOIN material_return 
				        ON material_return.id=material_return_details.parentId where site='".$site."' and
						store in ('".$store."') and  receiveqty!='0.00'
						and itemid in ('".$item."')",$db);
	while($addreceive=DB_fetch_array($sqlreceive))
	{
	if($addreceive['reciveqty']!='')
	{
	$receive[]=$addreceive['reciveqty'];
	$total[]=$addreceive['total'];
	}
	}	
/***************************************************site to site***********************************************************/
	$sqlsite_site=DB_query("SELECT sum(issueqty) AS issueqty
	                     FROM  transfer_issue_details INNER JOIN transfer_issue 
				        ON transfer_issue.id=transfer_issue_details.transfer_issue_id where sitecode='".$site."' and
						fromstore in ('".$store."')   and issueqty!='0.00'
						and itemid in ('".$item."')",$db);
	while($addsitetosite=DB_fetch_array($sqlsite_site))
	{
	if($addsitetosite['issueqty']!='')
	{
	$issueqty[]=$addsitetosite['issueqty'];
	$total1[]=$addsitetosite['total'];
	}
	}
/***************************************************site to site receive***************************************************/
	$sqlsite_site1=DB_query("SELECT sum(reciveqty) AS reciveqty
	                      FROM  transfer_receipt_details INNER JOIN transfer_receipt 
				        ON transfer_receipt.id=transfer_receipt_details.transfer_receipt_id
						 where Received_to='".$site."' and
						Received_store in ('".$store."')  and reciveqty!='0.00'
						and itemid in ('".$item."')",$db);
	while($addsitetositereceive=DB_fetch_array($sqlsite_site1))
	{
	if($addsitetositereceive['reciveqty']!='')
	{
	$receive[]=$addsitetositereceive['reciveqty'];
	
	}
	}
/***************************************************Material Return********************************************************/
	$sqlsite_site1=DB_query("SELECT sum(ReturnQty) AS issueqty
	                    FROM  inv_material_return_details INNER JOIN inv_material_return 
				        ON inv_material_return.id=inv_material_return_details.parentId where sitecode='".$site."' and
						storecode in ('".$store."')  and ReturnQty!='0.00'
						and itemid in ('".$item."')",$db);
	while($addmrtov=DB_fetch_array($sqlsite_site1))
	{
	if($addmrtov['issueqty']!='')
	{
	$issueqty[]=$addmrtov['issueqty'];
	
	}
	
	}	
	
/***************************************************Opening****************************************************************/
	$sqlopen=DB_query("select reveive_date as date,itemcode as itemid,stock as reciveqty,amount
	from opening_stockitemwise  where site='".$site."'
	 and store in ('".$store."')  
	  and itemcode in ('".$item."')",$db);
	while($addopen=DB_fetch_array($sqlopen))
	{
	if($addopen['reciveqty']!='')
	{
	$receive[]=$addopen['reciveqty'];	
	}
	
	 $sqlsite_rgpchallan=DB_query("SELECT sum(qty) AS issueqty
	                    FROM  rgp_tab_details INNER JOIN rgp_tab 
				        ON rgp_tab.id=rgp_tab_details.parent_id where branch='".$_REQUEST['site']."' and
						store='".$_REQUEST['store1']."' and date <= '".$fdate."' and  date <='".$toyrdate."' 
						and mst_itemid='".$_REQUEST['item']."'",$db);
					while($addrgpchallan=DB_fetch_array($sqlsite_rgpchallan))
					{
					$issueqty[]=$addrgpchallan['issueqty'];
					
					}
	
/*******************************************************************************************************************************/
	
	
	
/********************************************RGP Return***********************************************************************/
	             
				 $sqlsite_rgpreturnchallan=DB_query("SELECT sum(qty) AS reciveqty
	                    FROM  rgp_return_details INNER JOIN rgp_return 
				        ON rgp_return.id=rgp_return_details.parent_id where branch='".$_REQUEST['site']."' and
						store='".$_REQUEST['store1']."' and return_date <= '".$fdate."' and  return_date <='".$toyrdate."' 
						and item_id='".$_REQUEST['item']."'",$db);
					while($addrgpchallanreturn=DB_fetch_array($sqlsite_rgpreturnchallan))
					{
					$receive[]=$addrgpchallanreturn['reciveqty'];
					
					}
	
/*******************************************************************************************************************************/
	
	
/********************************************NRGP***********************************************************************/
	             
				 $sqlsite_nrgpchallan=DB_query("SELECT sum(qty) AS issueqty
	                    FROM  nrgp_challan_details INNER JOIN nrgp_challan 
				        ON nrgp_challan.id=nrgp_challan_details.parant_id where branch='".$_REQUEST['site']."' and
						store='".$_REQUEST['store1']."' and date <= '".$fdate."' and  date <='".$toyrdate."' 
						and item_code='".$_REQUEST['item']."'",$db);
					while($addnrgpchallan=DB_fetch_array($sqlsite_nrgpchallan))
					{
					$issueqty[]=$addnrgpchallan['reciveqty'];
					
					}
	
	
	
	
	}
	
	$qty=array_sum($receive)-array_sum($issueqty);
	
	return $qty;   
	}
/*******************************************************************************************************************************/





if($_REQUEST['action']=='Cancel')
{
	$site=$_REQUEST['site'];
	$store=$_REQUEST['store'];
	
	$flag=0;
	$mrndate1=DB_query("select * from dbl_addmrn where id='".$_REQUEST['mrnid']."'",$db);
	$mrndate2=DB_fetch_array($mrndate1);
	//echo "select * from db_dbl_addmrnqty where issue_id='".$_REQUEST['mrnid']."'";
	$itemdata=DB_query("select * from db_dbl_addmrnqty where issue_id='".$_REQUEST['mrnid']."'",$db);
	while($itemid1=DB_fetch_array($itemdata))
	{    	
	
	$privious_open=privious_opening($site,$store,$itemid1['mst_itemid']);  	
	
	$receiveqty=$itemid1['reciveqty'];
	
	if($privious_open<$receiveqty)
	{
	$flag=1;
	}
	}
	if($flag==0)
	{	
			
	//*******************************************************End******************************************************************/
	
	$dbl_addmrn_Row= DB_fetch_array(DB_query("Select * from dbl_addmrn where id='".$_REQUEST['mrnid']."'",$db));
	//echo "update dbl_addmrn set Cancel_Status='Y' where id='".$_REQUEST['mrnid']."'";
	//exit;
	$Update_Query=DB_query("update dbl_addmrn set Cancel_Status='Y'  where id='".$_REQUEST['mrnid']."'",$db);
	
	$Update_Query1 =DB_query("update db_dbl_addmrnqty set Can_status='Y' where issue_id='".$_REQUEST['mrnid']."'",$db);
	
	$dbl_addmrn_Row= DB_fetch_array(DB_query("Select * from dbl_addmrn where id='".$_REQUEST['mrnid']."'",$db));
	$dbl_addmrn_Row2=DB_query("Select * from dbl_addmrn where PO_WO_MTO='".$dbl_addmrn_Row['PO_WO_MTO']."' and id='".$_REQUEST['mrnid']."' and Cancel_Status='N' ",$db);
	$dbl_addmrn_Row1= DB_fetch_array($dbl_addmrn_Row2);
	$numdata=DB_num_rows($dbl_addmrn_Row2);
		if($numdata>0)
		{
			$Purch_Sql=DB_query("update purchorderdetails set status='Receive' where orderno='".$dbl_addmrn_Row1['PO_WO_MTO']."'",$db);
			$Purch_Sql=DB_query("update purchorders set Po_recive_status='Receive' where orderno='".$PURCH_Row['PO_WO_MTO']."'",$db);
		}
		else
		{
			$PURCH_Row= DB_fetch_array(DB_query("Select * from purchorders where orderno='".$dbl_addmrn_Row['PO_WO_MTO']."'",$db));
			$Purch_Sql=DB_query("update purchorderdetails set status='Pending' where orderno='".$PURCH_Row['orderno']."'",$db);
			$Purch_Sql=DB_query("update purchorders set Po_recive_status='Pending' where orderno='".$PURCH_Row['orderno']."'",$db);
		}
	}
}

 

?>
<script src="js/jsapi.js" type="text/javascript">
</script>

<style>
#slidingDiv {
    display: none;
	height:100px;
	background-color: #D9D6DA;
	padding:20px;
}
</style>
<?php
	$type="paging";
	$rowsPerPage = 10;
	$pageNum = 1;
	if(isset($_GET['page']))
	{
		$pageNum = $_GET['page'];
	}
	$offset = ($pageNum - 1) * $rowsPerPage;

if (isset($_GET['SelectedStockItem'])){
	$SelectedStockItem=trim($_GET['SelectedStockItem']);
} elseif (isset($_POST['SelectedStockItem'])){
	$SelectedStockItem=trim($_POST['SelectedStockItem']);
}

if (isset($_GET['RequisitionNumber'])){
	$RequisitionNumber=trim($_GET['RequisitionNumber']);
} elseif (isset($_POST['RequisitionNumber'])){
	$RequisitionNumber=trim($_POST['RequisitionNumber']);
}


if (isset($_GET['SelectedSupplier'])){
	$SelectedSupplier=trim($_GET['SelectedSupplier']);
} elseif (isset($_POST['SelectedSupplier'])){
	$SelectedSupplier=trim($_POST['SelectedSupplier']);
}


echo '<form action="' . $_SERVER['PHP_SELF'] . '?' . 'route=DealerDistrbutions/Inventory/transation/material_receipt_note_index&modid='.$_REQUEST['modid'].'&frmid=' .$_REQUEST['frmid'].'" method=post>';

if (isset($_POST['ResetPart'])){
     unset($SelectedStockItem);
}

if (isset($RequisitionNumber) && $RequisitionNumber!='') 
{
	if (!is_numeric($RequisitionNumber)){
		  echo '<br><b>' . _('The Requisition Number entered') . ' <U>' . _('MUST') . '</U> ' . _('be numeric') . '.</b><br>';
		  unset ($RequisitionNumber);
	} else {
		echo _('Requisition Number') . ' - ' . $RequisitionNumber;
}
} else {
	if (isset($SelectedSupplier)) {
		echo '<br><div class="page_help_text">' . _('For supplier') . ': ' . $SelectedSupplier . ' ' . _('and') . ' ';
		echo '<input type=hidden name="SelectedSupplier" value="' . $SelectedSupplier . '"></div>';
	}
	if (isset($SelectedStockItem)) {
		 echo '<input type=hidden name="SelectedStockItem" value="' . $SelectedStockItem . '">';
	}
}

if (isset($_GET['orderno']) && isset($_GET['orderno'])!='' && isset($_GET['DeleteOnly']) ==1 && isset($_GET['mrnid']) !='')
 {
 	
$sql = 'Delete From dbl_addmrn Where id='.$_GET['mrnid'].'';
$Delresult = DB_query($sql,$db);
$Delsql = 'Delete From db_dbl_addmrnqty Where issue_id ='.$_GET['mrnid'].'';
$issuedelresult = DB_query($Delsql,$db);
$chargedelete="delete from mrn_charges where MRN_id='".$_GET['mrnid']."'";
$charge_res=DB_query($chargedelete,$db);

$poqty_sql="Delete from po_quantity where orderno='".$_GET['orderno']."' ";
$poqty_res=DB_query($poqty_sql,$db);

echo $url_cancel;

prnMsg(_('MaterialReceiptNote Number') . '  ' . $_GET['mrnid'] . ' ' . _('has been Deleted') ,'success');
}

if ($_SESSION['UserStockLocation'] == $_SESSION['UserStockLocation'])
  {
	if (!isset($RequisitionNumber) or $RequisitionNumber==''){
	
		
?>		

<div id="container">
<script type="text/javascript">
function showSlidingDiv(){
$("#slidingDiv").animate({"height": "toggle"}, { duration: 700 });
}
</script>

<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
<div class="tab_div"> 
 <h1>Material Receipt Note</h1>	
 

<div align="left">
<?php if($_SESSION['frmAdd']=='1'){?>
		<a href="<?php echo $url_add;?>"><input type="button" class="search" value="Add New" /></a>
<?php }?>
<a href="#" onClick="showSlidingDiv(); return false;"><input type="button" class="search" value="SEARCH" /></a>
<div id="slidingDiv" class="centre">

<table width="50%" border="0" cellspacing="1" cellpadding="2" align="center">
  <tr>
	<th width="40%"><strong>Site</strong></th>
    <td width="10%">
	<?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" onchange="showmrn(this.value);"> 
    <option  value="000">Select Site</option>
	<?php 
	
		while ($myrow=DB_fetch_array($site_sql)){
 				echo '<option Value="' . $myrow['loccode'] . '">' . $myrow['locationname'].'</option>';
 		}
       }

	?> </select></td>
	<th width="40%"><strong>MRN Number</strong></th>
    <td width="10%">
	<div id="mrnno1">
	<select  name="MRNnumber">
	<option  value="000">Select Site</option>
	<?php 
		$sql = "SELECT  MRNNo FROM dbl_addmrn";
		$resultStkLocs = DB_query($sql,$db);
		while ($myrow=DB_fetch_array($resultStkLocs)){
 				echo '<option Value="'.$myrow['MRNNo'].'">' . $myrow['MRNNo'].'</option>';
 		
       }

	?> </select>
	</div>
	
	</td></tr>
    <tr>
    <th scope="col"><strong>Vendor</strong></th>	
    <td>
	   <div id="vender_codedata">
		<select name="vendor" id="vendor" onchange="showvendor(this.value)">
		<option value="000">---Select---</option>-->
		<?php 
		$vendor_sql=DB_query("Select id,vendor_code,vendor_name from suppliers",$db);
		while($vendor_res=DB_fetch_array($vendor_sql))
		{?>
		<option value="<?php echo $vendor_res['id'];?>"><?php echo $vendor_res['vendor_code'];?></option>
		<?php } ?>
		</select>
		</div>
	</td>
	<th scope="col"><strong>Vendor Name</strong></th>
	<td>
	<div id="venderdata">
	<select name="vendor_name" id="vendor_name" onchange="showvendorcode(this.value)">
		<option value="000">---Select---</option>-->
		<?php 
	$vendor_sql=DB_query("Select id,vendor_code,vendor_name from suppliers",$db);
		while($vendor_res=DB_fetch_array($vendor_sql))
		{?>
		
		<option value="<?php echo $vendor_res['id'];?>"><?php echo  str_replace(array("M/s ","M/S"),'',$vendor_res['vendor_name']); ?></option>
		<?php } ?>
		</select>
		</div>
		</td>
  
    </tr>	
	<tr>
	<th><strong>From Date</strong></th>
	<td><input type="text" name="fromdate" class="datepicker"  size="12" /></td>
	<th><strong>To Date</strong></th>
	<td><input type="text" name="todate" class="datepicker"  size="12"  /></td>
	</tr>
  </table>
  <br />
  <table width="30%" border="0" cellspacing="1" cellpadding="2" align="center">
</table>
  <p align="center"><input name="Search" type="submit" value="Search" /></p>
</div>
	<br /><br />
	<br />
	<?php
	
	if($site='0' || $_REQUEST['MRNnumber']=='000')
	{
	 	$SQL="select * from dbl_addmrn";
	}
	   if(isset($_POST['Search']))
	   {
	   unset($_SESSION['filter1']);	  
		 $SQL="select * from dbl_addmrn";
		
		//echo $_REQUEST['MRNnumber'];
		
		
         $MRnumber=$_REQUEST['MRNnumber'];
		$site=$_REQUEST['site'];
		$vendor=$_REQUEST['vendor'];
		$vendor_name=$_REQUEST['vendor_name'];
		$fromdate=ConvertSQLDate($_POST['fromdate']);
	    $todate=ConvertSQLDate($_POST['todate']); 
	    $filter=array();
		if($fromdate!='//' ||$todate!='//')
		{
			 $filter[]="MRNDate BETWEEN '".$fromdate."' AND '".$todate."'";
		}
		if($site!='000')
		{
			$filter[]="site='".$site."'";
		}
		if($MRnumber!='000')
		{
			$filter[]="MRNNo ='".$MRnumber."'";
		}
		if($vendor!='000')
		{
			$filter[]="ReceivedFrom='".$vendor."'";
		}
		if($vendor_name!='000')
		{
			$filter[]="ReceivedFrom='".$vendor_name."'";
		}
		
		if(isset($filter))
		{
		 if(count($filter)>0)
		
			{
			$SQL=$SQL." where ".implode(" and ",$filter);
		    $_SESSION['filter1']="where "  . implode(" and ",$filter);
			}
		else
			{
				 $SQL = "SELECT * FROM dbl_addmrn where  companyID='".$_SESSION['ACGCompanyId']."' and Cancel_Status='N' or Cancel_Status IS NULL order by id DESC";
	        }
			
		}
		
	}
else 
{   
if($_SESSION['AssignedBranch']!='')
{
$SQL = "SELECT * FROM dbl_addmrn where  companyID='".$_SESSION['ACGCompanyId']."' and Cancel_Status='N' or Cancel_Status IS NULL order by id DESC";
}
else
{
 $SQL = "SELECT * FROM dbl_addmrn where  companyID='".$_SESSION['ACGCompanyId']."' and Cancel_Status='N' or Cancel_Status IS NULL order by id DESC";
}   


// $resultpaging_SQL = "Select MRNNo, MRNDate, OrderFromSite, StoreName, ReceivedAgainst, createdby from dbl_addmrn
					 // Where 1=1 ORDER BY MRNNo ASC ";
		   }
		  if(isset($_SESSION['filter1']))
		  {
		  $SQL="select * from dbl_addmrn ".$_SESSION['filter1'];
		  } 
     
	// echo $SQL;

        $ErrMsg = _('No orders were returned by the SQL because');
		$purchordersResult = DB_query($SQL,$db,$ErrMsg);
		$resultpaging = DB_query($SQL, $db, $ErrMsg);
		/*show a table of the orders returned by the SQL */
	?>
	<table border="1" cellpadding="3" cellspacing="0" width="100%">
      <tr>
        <th><strong>SITE</strong></th>
        <th><strong>MRN No</strong></th>
        <th><strong>MRN Date</strong></th>
        <th><strong>SMC Unit Code </strong></th>
        <th><strong>SMC Unit  Name</strong></th>
          <th><strong>Created by</strong></th>
        <th><strong>View</strong></th>
        <th><strong>Edit</strong></th>
        <th><strong>Print</strong></th>
        <th><strong>Export</strong></th>
        <th><strong>Delete</strong></th>
      </tr>
      <?php 
	  
	    //echo $SQL;
		$j = 1;$i=1;
		$k=0;
		if(DB_num_rows($purchordersResult)>0){
		
			$rpp = 10; // results per page
			$adjacents = 5;
			
			$page = intval($_GET["page"]);
			if($page<=0) $page = 1;
			
			$reload ="index.php?route=Inventory/transation/material_receipt_note_index".$rurl;
			
			
			// select appropriate results from DB:
			
			
			//$sql = "SELECT * FROM sub_preparation";
			$result =$purchordersResult;
			
			// count total number of appropriate listings:
			$tcount = DB_num_rows($result);
			
			// count number of pages:
			$tpages = ($tcount) ? ceil($tcount/$rpp) : 1; // total pages, last page number
			
			$count = 0;
			$i = ($page-1)*$rpp;
			
			while(($count<$rpp) && ($i<$tcount)) {
				DB_data_seek($result,$i);
				$query = DB_fetch_array($result);
					@extract($query);
				   	
				  
				
				
				
				
		//if($Cancel_Status!='Y')
		//{
		
		if($Cancel_Status=='Y')
		{
		$cancel_status="Cancelled";
		}
		else
		{
		$cancel_status="";
		}
		
		
		
		
			if ($k==1){/*alternate bgcolour of row for highlighting */ ?>
      <tr class="EvenTableRows">
        <?php	$k=0;
			} else {?>
      </tr>
      <tr class="OddTableRows">
        <?php 		$k++;
			}
			$ModifyPage = $rootpath . "/MR_Header.php?" . SID . "&ModifyRequisitionNumber=" . $requisitionno;
			if ($status==_('Printed')) {
				$ReceiveOrder = "<a href='".$rootpath . "/GoodsReceived.php?" . SID . "&MRNumber=" . $requisitionno."'>".
					_('Create Purchase Order').'</a>';
			} 
	        else {
				//$ReceiveOrder = "Create Purchase Order";$url_edit
				
				$modification = '<a href="index.php?route=DealerDistrbutions/Inventory/transation/material_receipt_note_edit&modid='.$_REQUEST['modid'].'&frmid='.$_REQUEST['frmid'].'&ModfingOnly=1&mrnid='.$id.'&page='.$_REQUEST['page'].'">' . "<img src='images/icon-edit.png' height='15' width='15'>". '</a>';
				$view = '<a href="index.php?route=DealerDistrbutions/Inventory/transation/material_receipt_note_view&modid='.$_REQUEST['modid'].'&frmid='.$_REQUEST['frmid'].'&ViewingOnly=1&mrnid='.$id.'">' . "<img src='images/search.gif' height='15' width='15'>". '</a>';
				$delete = '<a href="' . $rootpath . 'DealerDistrbutions/Inventory/transation/material_receipt_note_index.php?' . SID . '&orderno=' . $order_no.'&DeleteOnly=1&mrnid='.$id.'" onclick="return confirm("Are You Sure You Want To Delete This Record?")">' . "<img src='images/icon-edit.png' height='15' width='15'>". '</a>';
			}
			if ($allowprint==1){
				$PrintPurchOrder = '<a target="_blank" href="' . $rootpath . '/MR_PDFMaterialRequisition.php?' . SID . '&RequisitionNo=' . $requisitionno. ' ">' . _('Print Now') . '</a>';
			} else {
			}
			if ($status==_('Authorised')) {
				$PrintPurchOrder = '<a target="_blank" href="' . $rootpath . '/MR_PDFMaterialRequisition.php?' . SID . '&RequisitionNo=' . $requisitionno. '&realorderno=' . $realorderno. '&ViewingOnly=2">' . _('Print') . '</a>';
			} else {
				$PrintPurchOrder = 'Print';
			}
			$site_query=DB_query("Select locationname from locations where loccode='".$site."'",$db);
			$site_row=DB_fetch_array($site_query);
			
			
			$site_query1=DB_query("Select dealer_name from dbl_dealer where id='".$site."'",$db);
			$site_row1=DB_fetch_array($site_query1);
			
			
			/********************************** Check Status of items **************************************/
			
			       
				   
				    
                   $flag=0;
                
				 //echo "select * from dbl_addmrnqty where issue_id='".$id."'";
		          $itemdata=DB_query("select * from dbl_addmrnqty where issue_id='".$id."' and reciveqty!='0.00'",$db);
				  while($itemid1=DB_fetch_array($itemdata))
				  { 
				   
				 		
                        $privious_open=privious_opening($site,$StoreCode,$itemid1['mst_itemid']);  	
				     // echo "<br>";
					    $receiveqty=$itemid1['reciveqty'];
					
					
					if($privious_open<$receiveqty)
					{
					$flag=1;
					}
					
				  }
			
			
		     
			  if($cancel_status=='' && $flag==1)
			  {
			  $cancel_status="Can Not Cancel";
			  }
			
			
			if($userstype!='Dealer')
			$site=$site_row['locationname'];
			else
			$site=$site_row1['dealer_name'];
			
			/************************************************************************************************/
					
			
		?>
      </tr>
      <tr bgcolor="#FFFFFF">
        <td><?php echo $site;?></td>
        <td><?php echo $MRNNo;?></td>
        <td><?php echo ConvertSQLDate($MRNDate);?></td>
        <td><?php echo $ReceivedFrom;?></td>
        <td><?php echo $s->getField('locations','loccode',$ReceivedFrom,'locationname');?></td>
        <td><?php echo $username=$s->getField('www_users','id',$createdby,'realname'); ?></td>
        <td width="4%">
		<?php if($_SESSION['frmView']=='1'){echo $view;}else{echo "No Permission";}?></td>
        <td width="4%"><?php if($_SESSION['frmEdit']=='1'  && $cancel_status!='Cancelled')  { 
			echo $modification;}else{echo "No Permission";}?>
			
			</td>
        <td width="4%">
		<?php if($_SESSION['frmView']=='1'){?>
		<a href="material_receipt_print.php?mrnid=<?php echo $id;?>" target="_blank"><img src="images/icon_print.jpg" height="25" width="25"></a>
		<?php }else{?>
		
		<?php echo 'No Permission'; ?>
		
		<?php }?>
		
		
		</td>
        <td>
		<?php if($_SESSION['frmView']=='1'){?>
		<a href="dbl_addmrnexport.php?modid=<?php echo $_REQUEST['modid'];?>&frmid=<?php echo $_REQUEST['frmid'];?>&mrnid=<?php echo $id;?>"><img src="images/icon-export.png" height="20" width="20"></a>
		
		<?php }else{?>
		
		<?php echo 'No Permission'; ?>
		
		<?php }?>
		</td>
        <td>
		<?php if($_SESSION['frmDelete']=='1'){?>
		<?php if($cancel_status!='Cancelled' && $cancel_status!='Can Not Cancel') {	 ?>       
		    
            <a href="index.php?route=Inventory/transation/material_receipt_note_index&modid=<?php echo $_REQUEST['modid'];?>&frmid=<?php echo $_REQUEST['frmid'];?>&mrnid=<?php echo $id;?>&action=Cancel&site=<?php echo $site; ?>&store=<?php echo $StoreCode ; ?>" onclick="return confirm('Are You Sure You Want To Cancel?')"><img src="images/Icon_Delete.png" height="15" width="15"></a>
            <?php } else { 
			if($cancel_status=='Can Not Cancel') { ?>
			<a href="#" onclick="javascript:popup('CancelIssue.php?id=<?php echo $id; ?>&site=<?php echo $site; ?>&store=<?php echo $StoreCode ; ?>&modid=<?php echo $_REQUEST['modid'];?>&frmid=<?php echo $_REQUEST['frmid'];?>',500,300)"><?php echo $cancel_status; ?></a> <?php } else { echo $cancel_status; }  }?>
			
			<?php }else{?>
		
		<?php echo 'No Permission'; ?>
		
		<?php }?>
			
			
			</td>
      </tr>
      <?php 
			$j++;
			If ($j == 12){
				$j=1;
				 echo $TableHeader;
			}
		//end of page full new headings if
		//}
		$i++;  $count++;			}
		echo paginate_two($reload, $page, $tpages, $adjacents);
		}
		else
		{?>
      <tr>
        <td colspan="10"><h3 align="center"><strong><font color="#FF0000">No Record Found!</font></strong></h3></td>
      </tr>
      <?php }
		//end of while loop ?>
    </table>
	<input type="hidden" name="ReqNo" value="<?php echo $_POST['ShowRequisition'];?>">
	<?php 
	echo "<script>defaultControl(document.forms[0].StockCode);</script>"; ?>
	</form>
	</div>
	</div>
	</div>
<?php 
}
else 
{
		echo '<form action="' . $_SERVER['PHP_SELF'] . '?' . SID . '" method=post>';
			
		if (isset($_POST['ResetPart'])){
			 unset($SelectedStockItem);
		}
		
		if (isset($RequisitionNumber) && $RequisitionNumber!='') {
			if (!is_numeric($RequisitionNumber)){
				  echo '<br><b>' . _('The Requisition Number entered') . ' <U>' . _('MUST') . '</U> ' . _('be numeric') . '.</b><br>';
				  unset ($RequisitionNumber);
			} else {
				echo _('Requisition Number') . ' - ' . $RequisitionNumber;
			}
		} else {
			if (isset($SelectedSupplier)) {
				echo '<br><div class="page_help_text">' . _('For supplier') . ': ' . $SelectedSupplier . ' ' . _('and') . ' ';
				echo '<input type=hidden name="SelectedSupplier" value="' . $SelectedSupplier . '"></div>';
			}
			if (isset($SelectedStockItem)) {
				 echo '<input type=hidden name="SelectedStockItem" value="' . $SelectedStockItem . '">';
			}
		}
		
		if (isset($_POST['SearchParts'])) {
			$completed='purchorderdetails.completed=0';
		
			
			if ($_POST['Keywords']) {
				//insert wildcard characters in spaces
		//	$completed = "purchorderdetails.completed=0 AND ";
				$i=0;
				$SearchString = '%';
				while (strpos($_POST['Keywords'], ' ', $i)) {
					$wrdlen=strpos($_POST['Keywords'],' ',$i) - $i;
					$SearchString=$SearchString . substr($_POST['Keywords'],$i,$wrdlen) . '%';
					$i=strpos($_POST['Keywords'],' ',$i) +1;
				}
				$SearchString = $SearchString. substr($_POST['Keywords'],$i).'%';
		
				$SQL = "SELECT stockmaster.stockid, 
						stockmaster.description, 
						SUM(locstock.quantity) AS qoh,  
						stockmaster.units, 
						SUM(purchorderdetails.quantityord-purchorderdetails.quantityrecd) AS qord 
					FROM stockmaster INNER JOIN locstock 
						ON stockmaster.stockid = locstock.stockid 
						INNER JOIN purchorderdetails 
							ON stockmaster.stockid=purchorderdetails.itemcode 
					WHERE $completed
					stockmaster.description " . LIKE . " '$SearchString' 
					AND stockmaster.categoryid='" . $_POST['StockCat'] . "' 
					GROUP BY stockmaster.stockid, 
						stockmaster.description, 
						stockmaster.units 
					ORDER BY stockmaster.stockid";
					
					
			 } elseif ($_POST['StockCode']){
				$SQL = "SELECT stockmaster.stockid, 
						stockmaster.description, 
						SUM(locstock.quantity) AS qoh, 
						SUM(purchorderdetails.quantityord-purchorderdetails.quantityrecd) AS qord, 
						stockmaster.units 
					FROM stockmaster INNER JOIN locstock 
						ON stockmaster.stockid = locstock.stockid 
						INNER JOIN purchorderdetails 
							ON stockmaster.stockid=purchorderdetails.itemcode 
					WHERE $completed
					AND stockmaster.stockid " . LIKE . " '%" . $_POST['StockCode'] . "%' 
					AND stockmaster.categoryid='" . $_POST['StockCat'] . "' 
					GROUP BY stockmaster.stockid, 
						stockmaster.description, 
						stockmaster.units 
					ORDER BY stockmaster.stockid";
					
			 } elseif (!$_POST['StockCode'] AND !$_POST['Keywords']) {
				$SQL = "SELECT stockmaster.stockid, 
						stockmaster.description, 
						SUM(locstock.quantity) AS qoh, 
						stockmaster.units, 
						SUM(purchorderdetails.quantityord-purchorderdetails.quantityrecd) AS qord 
					FROM stockmaster INNER JOIN locstock 
						ON stockmaster.stockid = locstock.stockid 
						INNER JOIN purchorderdetails 
							ON stockmaster.stockid=purchorderdetails.itemcode 
					WHERE $completed 
					AND stockmaster.categoryid='" . $_POST['StockCat'] . "' 
					GROUP BY stockmaster.stockid, 
						stockmaster.description, 
						stockmaster.units 
					ORDER BY stockmaster.stockid";
			 }
		
			$ErrMsg = _('No stock items were returned by the SQL because');
			$DbgMsg = _('The SQL used to retrieve the searched parts was');
			$StockItemsResult = DB_query($SQL,$db, $ErrMsg, $DbgMsg);
		}
	
		
			echo '<div class="centre">'._('Puchase Requisition number') . ': <input type=text name="RequisitionNumber" MAXLENGTH =8 size=9>  ' . _('Into Site') . ':<select name="StockLocation"> ';
			$sql = 'SELECT locationname FROM locations WHERE loccode='."'$_SESSION[UserStockLocation]'".';';
			$resultStkLocs = DB_query($sql,$db);
			while ($myrow=DB_fetch_array($resultStkLocs)){
		if (isset($_POST['StockLocation'])){
			if ($myrow['loccode'] == $_POST['StockLocation']){
				echo '<option selected Value="' . $myrow['loccode'] . '">' . $myrow['locationname'];
			} else {
				echo '<option Value="' . $myrow['loccode'] . '">' . $myrow['locationname'];
			}
		} elseif ($myrow['loccode']== $_SESSION['UserStockLocation']){
			echo '<option selected Value="' . $myrow['loccode'] . '">' . $myrow['locationname'];
		} else {
			echo '<option Value="' . $myrow['loccode'] . '">' . $myrow['locationname'];
		}
	}
		echo '</select>  <input type=submit name="SearchOrders" VALUE="' . _('Search Puchase Requisition') . '"></div>';
				
	$SQL='SELECT categoryid, categorydescription FROM stockcategory ORDER BY categorydescription';
	$result1 = DB_query($SQL,$db);
	
	?>
<hr />
<br>
	<br>
	<?php
	
	if (isset($StockItemsResult)) {
	
		echo '<table cellpadding=2 colspan=7 BORDER=2>';
		$TableHeader = 	'<tr><th>' . _('Code') . '</th>
				<th>' . _('Description') . '</th>
				<th>' . _('On Hand') . '</th>
				<th>' . _('Orders') . '<br>' . _('Outstanding') . '</th>
				<th>' . _('Units') . '</th>
				</tr>';
		echo $TableHeader;
		$j = 1;
		$k=0; //row colour counter
	
		while ($myrow=DB_fetch_array($StockItemsResult)) {
	
			if ($k==1){
				echo '<tr class="EvenTableRows">';
				$k=0;
			} else {
				echo '<tr class="OddTableRows">';
				$k=1;
			}
	
			printf("<td><input type=submit name='SelectedStockItem' VALUE='%s'</td>
					<td>%s</td>
				<td align=right>%s</td>
				<td align=right>%s</td>
				<td>%s</td></tr>",
				$myrow['stockid'],
				$myrow['description'],
				$myrow['qoh'],
				$myrow['qord'],
				$myrow['units']);
	
			$j++;
			If ($j == 12){
				$j=1;
				echo $TableHeader;
			}
	//end of page full new headings if
		}
	//end of while loop
	
		echo '</table>';
	
	}	
	//end if stock search results to show
	else 
	{
		//figure out the SQL required from the inputs available
	$completed = " AND purchorderdetails.completed=0";
		if (isset($RequisitionNumber) && $RequisitionNumber !='') 
		{
				$SQL = 'SELECT * FROM dbl_addmrn';
		} 
		else if (isset($SelectedSupplier)) 
		{
				if (!isset($_POST['StockLocation'])) 
				{
					$_POST['StockLocation']='';
				}
				
				if (isset($SelectedStockItem)) 
				{
				$SQL = 'SELECT * FROM dbl_addmrn';
				} else 
				{
					$SQL = 'SELECT * FROM dbl_addmrn';
				}
			} 
			else 
			{ //no supplier selected
				if (!isset($_POST['StockLocation'])) {$_POST['StockLocation']='';
				}
				if (isset($SelectedStockItem) and isset($_POST['StockLocation'])) {
					$SQL = 'SELECT * FROM dbl_addmrn';
				} 
				else 
				{
				$SQL = 'SELECT * FROM dbl_addmrn';
				}
			} //end selected supplier
		} //end not order number selected
		$ErrMsg = _('No orders were returned by the SQL because');
		$PurchOrdersResult = DB_query($SQL,$db,$ErrMsg);
	
		/*show a table of the orders returned by the SQL */
	
		echo '<table cellpadding=2 colspan=7 WIDTH=100%>';
	
	//	               '</td><td class="tableheader">' . _('Receive') .	
		$TableHeader = '<tr><th>' . _('Site Name') .
		        '</th><th>' . _('Purchase Req. No.') .
				'</th><th>' . _('Purchase Req. Date') .
				'</th><th>' . _('Purchase At') .
				'</th><th>' . _('Created by') .
				'</th><th>' . _('Create Vendor Quotation') .
				'</th><th>' . _('Create Comperitive Quotation') .
		'</th></tr>';
	
		echo $TableHeader;
		$j = 1;
		$k=0; //row colour counter
		while ($myrow=DB_fetch_array($PurchOrdersResult)) {
		
		
		
	
	
			if ($k==1){ /*alternate bgcolour of row for highlighting */
				echo '<tr class="EvenTableRows">';
				$k=0;
			} else {
				echo '<tr class="OddTableRows">';
				$k++;
			}
	
			$ModifyPage = $rootpath . "/MR_Header.php?" . SID . "&ModifyRequisitionNumber=" . $myrow["requisitionno"];
			if ($myrow['status']==_('Printed')) {
				$ReceiveOrder = "<a href='".$rootpath . "/GoodsReceived.php?" . SID . "&MRNumber=" . $myrow["requisitionno"]."'>".
					_('Create Purchase Order').'</a>';
			} else {
				//$ReceiveOrder = "Create Purchase Order";
				$ReceiveOrder = "<a href='".$rootpath . "/PO_Header.php?" . SID . "&MRNumber=" . $myrow["requisitionno"]."&sitename=" . $myrow["requisition_site"]."&purchaseat=" . $myrow["intostocklocation"]."&reqdate=" . $myrow["prdate"]."&status=" . $myrow["status"]."&identifier=" .$identifier."'>".
					_('Create Purchase Order').'</a>';
			}
			if ($myrow["allowprint"]==1){
				$PrintPurchOrder = '<a target="_blank" href="' . $rootpath . '/MR_PDFMaterialRequisition.php?' . SID . '&RequisitionNumber=' . $myrow['requisitionno'] . '">' . _('Print Now') . '</a>';
			} else {
	// not open yet
	//			$PrintPurchOrder = '<font color=GREY>' . _('Printed') . '</font>';
	
			}
			if ($myrow['status']==_('Authorised')) {
				$PrintPurchOrder = '<a target="_blank" href="' . $rootpath . '/PO_PDFPurchOrder.php?' . SID . '&OrderNo=' . $myrow['orderno'] . '&realorderno=' . $myrow['realorderno'] . '&ViewingOnly=2">' . _('Print') . '</a>';
			} else {
				$PrintPurchOrder = 'Print';
			}
			$PrintPurchOrder2 = '<a target="_blank" href="' . $rootpath . '/PO_PDFPurchOrder.php?' . SID . '&OrderNo=' . $myrow['orderno'] . '&realorderno=' . $myrow['realorderno'] . '&ViewingOnly=1">' . _('Show') . '</a>';
			$s2 = '<a target="_blank" href="' . $rootpath . '/PO_PDFPurchOrder.php?' . SID . '&OrderNo=' . $myrow['orderno'] . '&realorderno=' . $myrow['realorderno'] . '&ViewingOnly=1">' . $myrow['realorderno']. '</a>';
	
			$FormatedOrderDate = ConvertSQLDate($myrow['orddate']);
			$FormatedOrderValue = number_format($myrow['ordervalue'],2);
	        $VenderQuotation = '<a href="' . $rootpath . '/VenderQutations.php?' . SID . '&RequisitionNo=' . $myrow['requisitionno'] . '&ViewingOnly=1">' . "Create Vendor Quotation". '</a>';
			$ComperitiveQuotation = '<a href="' . $rootpath . '/Comperitive.php?' . SID . '&RequisitionNo=' . $myrow['requisitionno'] . '&ViewingOnly=1">' . "Create Comperitive Quotation". '</a>';
			$RequisitionNo=$myrow["requisitionno"];
	// the tailed two column
	//			<td>%s</font></td>
	//			<td align=right>%s</font></td>
	//			$myrow['requisitionno'],	
	//			$myrow['initiator']);
	//			'</td><td class="tableheader">' . _('Requisition') .
	//			'</td><td class="tableheader">' . _('Initiator') .	               		
	//		        <td><a href='%s'>" . _('Receive') . "</a></td>			
			printf("<td><input type=submit name='ShowRequisition' value='%s'></td>
				<td>%s</td>
				<td>%s</td>
				<td>%s</td>
				<td>%s</font></td>
				<td>%s</font></td>
				<td>%s</font></td>
				</tr>",
				$RequisitionNo,						
				ConvertSQLDate($myrow['req_date']),
				$myrow['requisition_site'],	
				$myrow['intostocklocation'],		
				$myrow['initiator'],			
				$VenderQuotation,
				$ComperitiveQuotation
				);
	
			$j++;
			If ($j == 12){
				$j=1;
				 echo $TableHeader;
			}
		//end of page full new headings if
		}
		//end of while loop
	
							
	}
	
					/*$rows = DB_num_rows($resultpaging);
					$maxPage = ceil($rows/$rowsPerPage);
					$self = $_SERVER['PHP_SELF'];
					$nav  = '';
				     for($page = 1; $page <= $maxPage; $page++)
				     {
					if ($page == $pageNum)
					{
						$nav .= " $page "; 
					}
					else
					{
					   $nav .= " <a href=\"$self?page=$page\" class=\"gllink\">$page</a> ";
					} 
				}
				if ($pageNum > 1)
				{
					$page  = $pageNum - 1;
					echo $first = " <a href=\"$self?page=1\" class=\"gllink\">[First Page]</a> ";
					echo $prev  = " <a href=\"$self?page=$page\" class=\"gllink\">[Prev]</a> ";
				} 
				else
				{
				  echo $prev  = "&nbsp;"; 
				  echo $first = "&nbsp;";
				}
				if ($pageNum < $maxPage)
				{
					$page = $pageNum + 1;
					echo $next = " <a href=\"$self?page=$page\" class=\"gllink\">[Next]</a>";
					echo $last = " <a href=\"$self?page=$maxPage\" class=\"gllink\">[Last Page]</a>";
				} 
				else
				{
				   echo $next = "&nbsp;";
				   echo $last = "&nbsp;"; 
				}*/
		
	echo '<input type="hidden" name="ReqNo" value="'.$_POST['ShowRequisition'].'">';
	echo "<script>defaultControl(document.forms[0].StockCode);</script>";
	echo '</table>';
	echo '</form>';
  
include('includes/footer.inc');
?>
<link rel="stylesheet" href="css/jquery.ui.all.css" />
<script src="js/jquery-1.5.1.js"></script>
<script src="ui/jquery.ui.core.js"></script>
<script src="ui/jquery.ui.widget.js"></script>



<script>
$(function() {
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' ,changeMonth: true,
		changeYear: true,
		yearRange: '-80:+20'});
});
</script>


<script>

function showmrn(str)
{

if (str.length==0)
  		{
  			document.getElementById("mrnno1").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("mrnno1").innerHTML=xmlhttp.responseText;
    		}
  		}
		xmlhttp.open("GET","mrnnoshow.php?site="+str,true);
		xmlhttp.send();


}


function showvendor(str)
{

if (str.length==0)
  		{
  			document.getElementById("venderdata").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("venderdata").innerHTML=xmlhttp.responseText;
    		}
  		}
		xmlhttp.open("GET","mrnvendorshow.php?site="+str,true);
		xmlhttp.send();






}



function showvendorcode(str)
{

if (str.length==0)
  		{
  			document.getElementById("vender_codedata").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("vender_codedata").innerHTML=xmlhttp.responseText;
    		}
  		}
		xmlhttp.open("GET","mrnvendorcodeshow.php?site="+str,true);
		xmlhttp.send();






}


</script>






<?php




if(isset($_SESSION['success_msg']))
{ ?>
	<script> alert("<?php echo ($_SESSION['success_msg']);?>");</script>
<?php 
}
unset($_SESSION['success_msg']);
?>