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


if($_SESSION['UserType']=='SuperAdmin')
{
	$sqlchkprhead=DB_query("select * from purchase_head_approval",$db);
}	
else
{
	$sqlchkprhead=DB_query("select * from purchase_head_approval where find_in_set('".$_SESSION['UserID']."',userid)",$db);
}

$Numrows=DB_num_rows($sqlchkprhead);
?>

<script type="text/javascript" language="javascript">
function checkqty(str)
{
	var id=str.id.split("_");
        var val=str.value;
        var totlqty=parseFloat(document.getElementById("pending_qty_"+id[2]).value);
	var Appqty=parseFloat(val);
        if(val=="" || val==0)
            document.getElementById(str.id).value="";
        else
            document.getElementById(str.id).value=Appqty.toFixed(2);
        if(Appqty>totlqty || Appqty<totlqty)
        {
            alert("Approval Qty Must Equal To Pending Qty");
            document.getElementById(str.id).focus();
            document.getElementById(str.id).value="";
        }
        /*var courter=document.getElementById("count1").value;
	var courter1=courter-1;
	for(var i=1;i<=courter1;i++)
	{
	var totlqty=parseFloat(document.getElementById("pending_qty_"+i).value);
	var Appqty=parseFloat(document.getElementById("app_qty_"+i).value);
	if(Appqty>totlqty || Appqty<totlqty)
	{
	alert("Approval Qty Must Equal To Pending Qty");
	document.getElementById("app_qty_"+i).focus();
	document.getElementById("app_qty_"+i).value=0;
	}
	}*/
}

function frmvalidate()
{
	if(document.getElementById("Site").value=='0')
	{
		alert("Please Select The Branch First !");
		document.getElementById("Site").focus()
		return false;
	}
	if(document.getElementById("fdate").value=='')
	{
		alert("Please Select The From Date First !");
		document.getElementById("fdate").focus()
		return false;
	}
	if(document.getElementById("todate").value=='')
	{
		alert("Please Select The To Date First !");
		document.getElementById("todate").focus()
		return false;
	}
}

function chkApprovedQty(i)
{
	if(document.getElementById("Approval_"+i).checked==true)
	{
		var appqty=document.getElementById("app_qty_"+i).value;
		if(appqty=='')
		{
			alert("You Must Fill Some Quantity For Approval Then Check !");
			document.getElementById("Approval_"+i).checked=false;
		}
	}
}


function CheckApprovalBox()
{
	var count=document.getElementById("count1").value;
	var status=0;
	for(var j=1;j<count;j++)
	{
		if(document.getElementById("Approval_"+j).checked==true)
		{
			status=1;
			//return false;
		}
	}
	
	if(status=='0')
	{
		alert("Please Check At Least One For Approval");
		return false;
	}
	
}
</script>
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
<div class="tab_div">
<h1>Purchase Head Approval</h1>
<div class="centre" id="slidingDiv">
<form method="post" action="">	
<table width="100%" cellpadding="3" cellspacing="0">
<tr class="row1">
	<td class="tabledata1"><strong>Branch</strong></td>
	<td><select style="width:150px;" name="Site" id="Site">
			<?php
			$SiteName=DB_query("Select * from locations where mst_companyid='".$_SESSION['ACGCompanyId']."' and loccode in('".$_SESSION['AssignedBranch']."')",$db);
			while($SiteRow=DB_fetch_array($SiteName))
			{ ?>
			<option value="<?php echo $SiteRow['loccode']?>"<?php echo($_REQUEST['Site']==$SiteRow['loccode']?'selected':'');?>><?php echo $SiteRow['locationname']?></option>	
				
		<?php } ?>
		</select>
	</td>
	<!--<td class="tabledata1"><strong>Department</strong></td>
	<td><select style="width:150px;" name="deptId">
			<?php $DeptName=DB_query("SELECT * FROM deptmaster where deptname='STORE' and CompanyId='".$_SESSION['ACGCompanyId']."'",$db);
			while($DeptIdRow=DB_fetch_array($DeptName))
			{ ?>
			<option value="<?php echo $DeptIdRow['id']?>"<?php echo($_REQUEST['deptId']==$DeptIdRow['id']?'selected':'');?>><?php echo $DeptIdRow['deptname']?></option>	
				
		<?php } ?>
		</select>
	</td>-->
	<td class="tabledata1"><strong>From Date</strong></td>
	<td><input type="text" name="fdate" id="fdate" style="width:150px;"  class="datepicker" value="<?php echo $_REQUEST['fdate']?>"/></td>
	<td class="tabledata1"><strong>To Date</strong></td>
	<td><input type="text" name="todate" id="todate" style="width:150px;" class="datepicker"  value="<?php echo $_REQUEST['todate']?>"  /></td>
	
	<td class="tabledata1"><strong>Indent By</strong></td>
	<td><?php $EMPSQL=DB_query("SELECT * FROM empmaster where CompanyId='".$_SESSION['ACGCompanyId']."'",$db);?>
	<select style="width:150px;" name="user" id="user">
	<option value="0">All</option>
	<?php while($GetEmp=DB_fetch_array($EMPSQL)) {?>
	<option value="<?php echo $GetEmp['id']; ?>"<?php echo($_REQUEST['user']==$GetEmp['id']?'selected':''); ?>><?php echo $GetEmp['emp_name']; ?></option>
	<?php } ?>
	</select>
</td>
</tr>
<tr class="row1">
  <td colspan="8" style="text-align:center;"><input name="Go" type="submit" value="Go" onclick="return frmvalidate()" class="search" /></td>
</tr>
</table>
</form>
</div>
<br />
<?php
//echo $user_ids;
if($_REQUEST['Save'])
{
	//$arry=array();
	for($i=1;$i<=count($_REQUEST['requiNo']);$i++)
	{
	if($_REQUEST['Approval'][$i]==1){
	
	if($_REQUEST['app_qty1'][$i]=='')
	{
	$Totalqty=$_REQUEST['app_qty'][$i];
	}
	else
	{
	$Totalqty=$_REQUEST['app_qty'][$i]+$_REQUEST['app_qty1'][$i];
	}
	
	
	if($_REQUEST['reqi_qty'][$i]==$Totalqty)
	{
	$sts='3';
	}
	else
	{
	$sts='2';
	}
	
	
	
	$arry[]=$_REQUEST['appby'][$i];
	
	$data['ApproveQty_By_PurchaseHead']=$Totalqty;
	$data['Approval_status_of_purchaseHead']=$sts;
	$cond="id='".$_REQUEST['requiNo'][$i]."'";
	
	//echo "<pre>";
	//print_r($data);
	$row= $s->RecordEdit('requisitionorderdetails',$data,$cond);
	}
	}
	$UniqueArr=array_unique($arry);
	
	
	foreach($UniqueArr as $key =>$value)
	{
		$get=DB_query("select Approved_By_Purch_Head from materialrequisitions where requisitionno='".$value."'",$db);
		$GetAppid=DB_fetch_array($get);
		$explo=explode(",",$GetAppid['Approved_By_Purch_Head']);
		if($GetAppid['Approved_By_Purch_Head']!='')
		{
			if(!in_array($_SESSION['UserID'],$explo))
			{
			 $CombineUserId=$GetAppid['Approved_By_Purch_Head'].','.$_SESSION['UserID'];
			}
			else
			{
			$CombineUserId=$GetAppid['Approved_By_Purch_Head'];
			}
		}
		else
		{
			$CombineUserId=$_SESSION['UserID'];
		}
		$dataapp['Approved_By_Purch_Head']=$CombineUserId;
		$dataapp['mapped_vendor_status']='0';
		$codd="requisitionno='".$value."'";
		//echo "<pre>";
		//print_r($dataapp);
		$s->RecordEdit('materialrequisitions',$dataapp,$codd);
	}
	//exit;
	$_SESSION['success_msg']="Approved Successfully";
	$s->pageLocation($target);
}
?>
<?php if($_REQUEST['daction']==1){?>
<div class="success"><?php echo "Record Approved Successfully";?></div>
	<?php } ?>
<div style="width:100%; margin-left:auto; margin-right:auto;">
<form method="post" action="">
<?php
if($Numrows>0)
{
while($prheadApp=DB_fetch_array($sqlchkprhead))
{
	$Type[]=$prheadApp['category'];
} 

$CatType=implode("','",$Type);
if($_REQUEST['Go'])
{
	$todate=ConvertSQLDate($_REQUEST['todate']);
	$fromdate=ConvertSQLDate($_REQUEST['fdate']);
	$Site=$_REQUEST['Site'];
	if($_REQUEST['todate']!='' && $_REQUEST['fdate']!='' )
	{
	$filter[]="prdate between '".$fromdate."' and '".$todate."'";
	}
	if($_REQUEST['Site']!='0')
	{
	$filter[]="sitecode='".$Site."'";
	}
	if($_REQUEST['user']!='0')
	{
	$filter[]="requition_by='".$_REQUEST['user']."'";
	}
	if($filter!='')
	{
	$filter1=implode(" and ",$filter);
	if($_SESSION['UserType']=='SuperAdmin')
{
	$getlead= "SELECT * FROM materialrequisitions where $filter1 and CompanyId='".$_SESSION['ACGCompanyId']."'  ORDER BY requisitionno DESC";
	}
	else
	{
	$getlead= "SELECT * FROM materialrequisitions where $filter1 and CompanyId='".$_SESSION['ACGCompanyId']."' and category in('".$CatType."') ORDER BY requisitionno DESC";
	}
	}
	
	$getlead1=DB_query($getlead,$db);
	$i=1;
	$p=1;
?>
<table width="100%" border="1" cellspacing="0" cellpadding="3" style="border-collapse:collapse; border:#999999 solid 1px;">
		<?php if($_REQUEST['fdate']!='' && $_REQUEST['todate']!='') {?>
		<tr>
		<td colspan="11" style="color:#006699;"><strong>UnApproved Purchase Requisition List From <?php echo ConvertSQLDate($fromdate);?> TO <?=ConvertSQLDate($todate)?></strong></td>
		</tr>
		
		<tr>
		<td colspan="11" style="height:5px;"></td>
		</tr>
		<?php } ?>
<?php if(DB_num_rows($getlead1)>0){
		while($TelRes=DB_fetch_array($getlead1))
		{
		
		$sqlqry=DB_query("select * from requisitionorderdetails where requsitionno='".$TelRes['requisitionno']."' and (Approval_status_of_purchaseHead='1' || Approval_status_of_purchaseHead='2')",$db);
		 $n= DB_num_rows($sqlqry);
		$flag=0;
	  	if($n>0)
	  	{
		while($ChkRows=DB_fetch_array($sqlqry))
		{
			if($ChkRows['ApproveQty_By_soreHead']!='')
			{
				$flag=1;
			}
		}
		if($flag==1){
	  	$k=1;
		$q="Select S1.initiator,S1.prdate, S2.* from materialrequisitions S1,requisitionorderdetails  S2 where S2.requsitionno ='".$TelRes['requisitionno']."' and (S2.Approval_status_of_purchaseHead='1' || S2.Approval_status_of_purchaseHead='2') and S1.requisitionno=S2.requsitionno";
	   $itemSql=DB_query($q ,$db);?>
	 <tr align="center" bgcolor="#d4d4d4">
	 	<td colspan="4" style="font-size:12px;"><strong>Requisition No & Date :</strong>&nbsp;&nbsp;&nbsp;<a href="index.php?route=POModule/purchase_requisition_view&modid=<?php echo $_REQUEST['modid'] ?>&frmid=<?php echo $_REQUEST['frmid'] ?>&RequisitionNo=<?php echo $TelRes['requisitionno'];?>" target="_blank"><font size="2"><?php echo '<b>'.$TelRes['Reqno'].'</b>';?></font></a><strong><?php echo "  ".ConvertSQLDate($TelRes['prdate']); ?></strong></td>
	   <td  colspan="4"  style="font-size:12px;"><strong>Indent By:&nbsp;
	  <?php echo  $ClientName=$s->GetFieldValue('empmaster',"id='".$TelRes['requition_by']."'",'emp_name');?></strong></td>
			<td colspan="3"><strong>Created By :</strong>&nbsp;&nbsp;<strong><?php  echo  ucfirst($s->GetFieldValue('www_users',"id='".$TelRes['initiator']."'" ,'realname')); ?></strong></td>
	  </tr> 
	  <tr>
		<td class="tabledata">S. No.</td>
		<td class="tabledata">Part Code</td>
		<td class="tabledata">Part Name</td>	
		<td class="tabledata">UOM</td>
		<td class="tabledata">Indent/PR Qty</td>
		<td class="tabledata">Total Approved Till Now(By Store Head) </td>
		<td class="tabledata">Pending For Approval</td>
		<td class="tabledata">Qty To Approve</td>		
		<td class="tabledata">Last PO Rate</td>
		<td class="tabledata">Approved By</td>
		<td class="tabledata">Action</td>		
	  </tr>
	  <?php while($itemRow=DB_fetch_array($itemSql)){
	  if($itemRow['ApproveQty_By_soreHead']!=''){
	  $UnitId=$s->GetFieldValue('item_master',"id='".$itemRow['mst_itemid']."'",'mst_unitid');?>
	<tr bgcolor="#c1c1c1">
		<td><?php echo $k;?></td>
		<td><?php echo 	$s->GetFieldValue('item_master',"id='".$itemRow['mst_itemid']."'",'StockId'); ?></td>
		<td><?php echo 	$s->GetFieldValue('item_master',"id='".$itemRow['mst_itemid']."'",'item_name');?></td>
		<td><?php echo 	$s->GetFieldValue('unitsofmeasure',"unitid='".$UnitId."'",'unitname');?></td>
		<td><?php echo 	$itemRow['requisition_qty'];?></td>
		<td><?php if($itemRow['ApproveQty_By_PurchaseHead']=='')	
				{
					$Finalqty=$itemRow['ApproveQty_By_soreHead'];
				}
				else
				{
				$Finalqty=$itemRow['ApproveQty_By_soreHead']-$itemRow['ApproveQty_By_PurchaseHead'];
				}
		
		echo $itemRow['ApproveQty_By_soreHead']; ?>
		
<input type="hidden" name="appby[<?php echo $p?>]" value="<?php echo $TelRes['requisitionno']; ?>"  />

<input type="hidden" name="reqi_qty[<?php echo $p?>]" id="reqi_qty_<?php echo $p;?>" value="<?php echo $itemRow['requisition_qty']; ?>" />
		<input type="hidden" name="qty[<?php echo $p?>]" id="qty_<?php echo $p;?>" value="<?php echo $Finalqty; ?>" />
		</td>
		<td><?php echo $Finalqty; ?><input type="hidden" style="width:107px;" name="pending_qty[<?php echo $p ?>]" id="pending_qty_<?php echo $p;?>" value="<?php echo $Finalqty; ?>" ></td>
                <td><input type="text" onkeypress="javascript:return isNumberKey(this,event)" name="app_qty[<?php echo $p?>]" id="app_qty_<?php echo $p;?>" onblur="checkqty(this)" />
			 <input type="hidden" name="app_qty1[<?php echo $p?>]" id="app_qty1_<?php echo $p;?>" value="<?php echo $itemRow['ApproveQty_By_PurchaseHead'] ?>" />
		</td>
		
		<td><input type="text" style="width:107px;" name="lastpo_rate[<?php echo $p ?>]" ></td>
		<td><?php echo $UserId=$s->GetFieldValue('www_users',"id='".$_SESSION['UserID']."'",'realname');?>
			<input type="hidden" name="Approved_by[<?php echo $p; ?>]" id="Approved_by" value="<?php echo $_SESSION['UserID']; ?>" />
		</td>
		<td><input type="hidden" name="requiNo[<?php echo $p; ?>]" value="<?php echo $itemRow['id']?>"  />
			<input type="checkbox" name="Approval[<?php echo $p?>]" id="Approval_<?php echo $p;?>" onclick="chkApprovedQty(<?php echo $p;?>)" value="1">
		</td>
		</tr>
		
<?php $p++; ;$k++; }} ?>
<tr>
		<td colspan="11"><?php echo "&nbsp;"; ?></td>
</tr>
<?php $i++; }} ?>
		<input type="hidden" name="count" id="count" value="<?php echo $p;?>">
<?php } ?>
	  <input type="hidden" name="count1" id="count1" value="<?php echo $p;?>">
<?php   } else{ ?>
	<tr><td clospan="11"><font color="#FF0000">No Records Found</font></td></tr>
<?php } ?>
</table>
<?php if($k>0){?>
	<p align="center"><input type="submit" name="Save" value="Approve" onclick="return CheckApprovalBox()"  class="search" ></p>
<?php	} }}else{ ?>

<p align="center"><font style="font-size:12px; color:#FF0000;"><strong>You Have Not Permission To Approve The Requisition</strong></font></p>

<?php }?>
</form>
</div>
</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;
}
</script>
<!--main div Close -->