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


$DeptId=$s->GetDeptIdByUser($_SESSION['UserID'],$_SESSION['ACGCompanyId']);
$DeptHead=$s->GetDeptHead($DeptId,$_SESSION['UserID'],'DepartmentWiseIndentApproval');



if($DeptHead!='')
{
	$AllDeptWiseEmp=$s->GetDeptWiseEmp($DeptId,$_SESSION['ACGCompanyId']);
	if($AllDeptWiseEmp!='')
	{
	$DeptWiseEmplist=implode(",",$AllDeptWiseEmp);
	}
}
$Explode=explode(",",$DeptHead);
?>
<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)
        {
            alert("Approval Qty is Not Greater Than 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);
        document.getElementById("app_qty_"+i).value=Appqty.toFixed(2);
        if(Appqty>totlqty)
        {
            alert("Approval Qty is Not Greater Than Total Qty");
            document.getElementById("app_qty_"+i).focus();
            document.getElementById("app_qty_"+i).value=0;
        }
        }*/
}

function frmvalidate()
{
	var fdate=document.getElementById("fdate").value;
	var fdate2=fdate.split("/");
	var fdate3=fdate2[1]+"/"+fdate2[0]+"/"+fdate2[2];
	var todate=document.getElementById("todate").value;
	var todate2=todate.split("/");
	var todate3=todate2[1]+"/"+todate2[0]+"/"+todate2[2];
	var d = new Date();
	var cdate = d.getDate();
    var cmonth = d.getMonth() + 1;
    var cyear = d.getFullYear();
    var today = cmonth+"/"+cdate+"/"+cyear;

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

	var fdate1=new Date(fdate3);
	fdate1=fdate1.getTime();

	var todate1=new Date(todate3);
	todate1=todate1.getTime();

	if(fdate1>today1)
	{
		alert("From Date not greater than Today Date!");
		document.getElementById("fdate").focus()
		return false;
	}
	if(todate1>today1)
	{
		alert("To Date not greater than Today Date!");
		document.getElementById("todate").focus()
		return false;
	}
	if(fdate1>todate1)
	{
		alert("From Date not greater than To Date!");
		document.getElementById("todate").focus()
		return 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;
	}	
}

function checkapproveqty(i)
{
	if(document.getElementById("Approval_"+i).checked==true)
	{
		if(document.getElementById("app_qty_"+i).value=='' || document.getElementById("app_qty_"+i).value=='0')
		{
			alert("You Must Fill Approve Qty First Then Ckeck For Approval");
			document.getElementById("Approval_"+i).checked=false;
			document.getElementById("app_qty_"+i).focus();
		}
	}
}

</script>
<?php
//echo $user_ids;
if($_REQUEST['Save'])
{
	//$arry=array();
	for($i=1;$i<=count($_REQUEST['requiNo']);$i++)
	{
	if($_REQUEST['Approval'][$i]==1){
	if($_REQUEST['qty'][$i]==$_REQUEST['app_qty'][$i])
	{
	$sts='3';
	}
	else
	{
	$sts='2';
	}
	if($_REQUEST['app_qty1'][$i]=='')
	{
	$Totalqty=$_REQUEST['app_qty'][$i];
	}
	else
	{
	$Totalqty=$_REQUEST['app_qty'][$i]+$_REQUEST['app_qty1'][$i];
	}
	
	$arry[]=$_REQUEST['appby'][$i];
	
	$data['App_quantity']=$Totalqty;
	$data['ApprovalStatus']=$sts;
	$cond="id='".$_REQUEST['requiNo'][$i]."'";
	
	//echo "<pre>";
	//print_r($data);
	$row= $s->RecordEdit('requisitionorderdetails',$data,$cond);
	}
	}
	//exit;
	$UniqueArr=array_unique($arry);
	
	
	foreach($UniqueArr as $key =>$value)
	{
		$get=DB_query("select Approved_by from materialrequisitions where requisitionno='".$value."'",$db);
		$GetAppid=DB_fetch_array($get);
		$explo=explode(",",$GetAppid['Approved_by']);
		if($GetAppid['Approved_by']!='')
		{
			if(!in_array($_SESSION['UserID'],$explo))
			{
			 $CombineUserId=$GetAppid['Approved_by'].','.$_SESSION['UserID'];
			}
			else
			{
			$CombineUserId=$GetAppid['Approved_by'];
			}
		}
		else
		{
			$CombineUserId=$_SESSION['UserID'];
		}
		$dataapp['Approved_by']=$CombineUserId;
		$codd="requisitionno='".$value."'";
		//echo "<pre>";
		//print_r($dataapp);
		$s->RecordEdit('materialrequisitions',$dataapp,$codd);
	}
	echo "<div class='success'>Record Approval Successfully Made</div>";
	//$_SESSION['success_msg']="Approved Successfully";
	$s->pageLocation($target);
}
?>

<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
<div class="tab_div">
<h1><?php echo $s->GetFieldValue('modules_form','id="'.$_REQUEST['frmid'].'"','description');?></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
			$ss1 = "Select * from locations where mst_companyid='".$_SESSION['ACGCompanyId']."' and loccode in('".$_SESSION['AssignedBranch']."')";
			$ss = "Select * from locations where mst_companyid='".$_SESSION['ACGCompanyId']."'";
			$SiteName=DB_query($ss,$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='PURCHASE' 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 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(in_array($_SESSION['UserID'],$Explode))
{
if($_REQUEST['Go'])
{
	$todate=ConvertSQLDate($_REQUEST['todate']);
	$fromdate=ConvertSQLDate($_REQUEST['fdate']);
	$Site=$_REQUEST['Site'];
	if($_REQUEST['todate']!='' && $_REQUEST['fdate']!='' )
	{
	$filter[]="prdate between '".str_replace("/","-",$fromdate)."' and '".str_replace("/","-",$todate)."'";
	}
	if($_REQUEST['Site']!='0')
	{
	$filter[]="sitecode='".$Site."'";
	}
	if($_REQUEST['user']!='0' AND $_SESSION['UserType']!='SuperAdmin')
	{
	$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 requition_by in($DeptWiseEmplist) 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="10" style="color:#006699;"><strong>UnApproved Purchase Requisition List From <?php echo ConvertSQLDate($fromdate);?> TO <?php echo ConvertSQLDate($todate)?></strong></td>
		</tr>
		<tr>
		<td colspan="10" 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 ApprovalStatus!='3'",$db);
		$n= DB_num_rows($sqlqry);
	  	if($n>0)
	  	{
	  	$k=1;
		$q="Select S1.initiator,S1.prdate, S2.* from materialrequisitions S1,requisitionorderdetails  S2 where S2.requsitionno ='".$TelRes['requisitionno']."' and (S2.ApprovalStatus='1' || S2.ApprovalStatus='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="3"  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">Approve Qty</td>
		<td class="tabledata">Pending Qty</td>
		<td class="tabledata">Last PO Rate</td>
		<td class="tabledata">Approved By</td>
		<td class="tabledata">Check For Approval </td>		
	  </tr>
	  <?php while($itemRow=DB_fetch_array($itemSql)){
	  $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 if($itemRow['App_quantity']=='')	
				{
					$Finalqty=$itemRow['requisition_qty'];
				}
				else
				{
				$Finalqty=$itemRow['requisition_qty']-$itemRow['App_quantity'];
				}
		
		echo $itemRow['requisition_qty']; ?>
		
<input type="hidden" name="appby[<?php echo $p?>]" value="<?php echo $TelRes['requisitionno']; ?>"  />
		<input type="hidden" name="qty[<?php echo $p?>]" id="qty_<?php echo $p;?>" value="<?php echo $Finalqty; ?>" />
		</td>
                <td><input type="text" maxlength="11" name="app_qty[<?php echo $p?>]" id="app_qty_<?php echo $p;?>" onkeypress="javascript:return isNumberKey(this,event)" onblur="checkqty(this)" />
			 <input type="hidden" name="app_qty1[<?php echo $p?>]" id="app_qty1_<?php echo $p;?>" value="<?php echo $itemRow['App_quantity'] ?>" />
		</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" style="width:107px;" value="<?php echo $UserId=$s->GetFieldValue('item_master',"id='".$itemRow['mst_itemid']."'",'last_po_price'); ?>" readonly 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="checkapproveqty(<?php echo $p;?>)" value="1">
		</td>
		</tr>
		
<?php $p++; ;$k++; } ?>
<tr>
		<td colspan="10"><?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="10"><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" style="font-size:10px; color:#FF0000;">You Have Not Rights</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 -->
