<?php
$EmpID = "";
$Designation = "";
$DepartmentName = "";
$FirstName = "";

if(!empty($Emp))
{
    foreach ($Emp as $Emp)
    {
		$EmpID = $Emp->EmpID ;
		$FirstName = $Emp->FirstName ;
		$Designation = $Emp->Designation;
		$DepartmentName =$Emp->DepartmentName;
	}
}
?>
<style>
            .table-bordered>thead>tr>th, .table-bordered>tbody>tr>th, .table-bordered>tfoot>tr>th, .table-bordered>thead>tr>td, .table-bordered>tbody>tr>td, .table-bordered>tfoot>tr>td {border: 1px solid #333;}
            </style>
<div class="content-wrapper">
    
 
	 <section class="content">
	  
	 <div>
         <center><b><h2>Siddharth Industries - Requisition Form</h2></b></center>
         <div class="container-fluid">
		  <div id="content"></div>
		   <?php
                      $attributes = array('class' => 'form-label-left requistion ','name'  => 'requistion','id'  => 'requistion');
                        
                        echo form_open($this->config->base_url().'requisitionform/SearchRequistList',$attributes); ?>
	 <div class="row">
	 <div class="col-md-12">
		 <div class="col-md-3">
		 <label>Request Type</label>
			<div>
				 <?php
				$options = array("-1"=>'Select Request Type');
				
				//print_r(  $options);
				
				if(!empty($RequestType))
				{
				foreach ($RequestType as $RID):
				  
			   
				  $options[$RID->ConfigValue] =  $RID->ConfigValue;

				endforeach;
				}										
	
				echo form_dropdown('RequestType', $options,set_value('ConfigValue'),'id="RequestType"' ,'class = "form-control select2"','required="true"');

				?>
				 
			</div>
		 </div>
		 <div class="col-md-3">
		 <label>Requested By</label>
			<div>
				
				 <?php
                                         $data = array('name' => 'EmpID','value' => set_value('EmpID',$FirstName),'id'=>'EmpID',  'class' => 'form-control' ,'readonly' => 'true');
                                        echo form_input($data);
                                        ?>  
 <input type="hidden" name="EmpID" id="EmpID" value=<?php echo $EmpID?> />										
			</div>
		 </div>
		 <div class="col-md-3">
		 <label>Department Name</label>
		 	<div class="form-group">
									<?php
                                         $data = array('name' => 'DeptName','value' => set_value('DeptName',$DepartmentName),'id'=>'DeptName',  'class' => 'form-control' ,'readonly' => 'true');
                                        echo form_input($data);
                                        ?>   
                                </div>
		 </div>
		 <div class="col-md-3">
		 <label>Designation</label>
		 	<div class="form-group">
									<?php
                                         $data = array('name' => 'Designation','value' => set_value('Designation',$Designation),'id'=>'Designation',  'class' => 'form-control' ,'readonly' => 'true');
                                        echo form_input($data);
                                        ?>   
                                </div>
		 </div>
	 </div>
	 <div class="col-md-12">
	
	  <div class="col-md-3">
		 <label>Cost Center Name</label>
		 <div>
				 <?php
				$Costs = array("-1"=>'Select Cost Center Name');
				//print_r(  $options);		
												
					if(!empty($CostCenter))
										{
									    foreach ($CostCenter as $SID):
                                         // echo $SID->ConfigValue;
									   	  $Costs[$SID->CostCenterCode] =  $SID->CostCenterCode .'-'. $SID->CostCenterName ;

										endforeach;
											
										}
				echo form_dropdown('CostCenter', $Costs,set_value('CostCenter'),'id="CostCenter"' ,'class = "form-control"');

		?>
				 
			</div>
		 </div>
	 <div class="col-md-3">
		 <label>Available Budget Amount</label>&nbsp;<img id="AlertImg"  src="<?php echo base_url(); ?>assets/dist/img/red.png" alt="your image" width="25px"  style="display:none"/>
		 	<div class="form-group">
				<?php
					 $data = array('name' => 'AvlBudgetAmount','value' => set_value('AvlBudgetAmount'),'id'=>'AvlBudgetAmount',  'class' => 'form-control' ,'readonly' => 'true');
					echo form_input($data);
					?>   
			</div>
		 </div>
		 	
	 </div>
	 
	 </div>
         </div>
	 
          <div class="container-fluid">    
  <table class="table table-bordered" style="border:1px solid #333">
  <div align="right" style="padding-right:10px">
<div align="right">
  <a  onclick="return validateBeforeAdd();"  class="btn btn-primary">Add Line Item</a>
  
  <div class="modal fade" id="myModal1" role="dialog">
		<div class="modal-dialog">
		
		  <!-- Modal content-->
		  <div class="modal-content">
			<div class="modal-header">
			  <button type="button" class="close" data-dismiss="modal">&times;</button>
			  <center><h4>Add Line Item </h4></center>				
			</div>
			<div align="left"> 
			 
			 <div class="col-md-6">
				<label>Material Code</label>
					<div >
						 <?php
						$options = array("0"=>'Material Code');     
						//print_r(  $options);
						
						if(!empty($MaterialList))
						{
						foreach ($MaterialList as $MID):
						  
					   
						  $options[$MID->MaterialCode] =  $MID->MaterialCode.' '.' - '.' '.$MID->MaterialName;

						endforeach;
						}										
			
						echo form_dropdown('MaterialCode', $options,set_value('MaterialCode'),'id="MaterialCode"' ,'class="form-control"');

						?>						 
					</div>
			</div>

			<div class="col-md-6">
				<label>Description</label>
				<div class="form-group">
						<?php
						 $data = array('name' => 'Description','value' => set_value('Description'),'id'=>'Description',  'class' => 'form-control','readonly' => 'true' );
						echo form_input($data);
						?>   
				</div>
			</div>
			<div class="col-md-6">
				<label>UOM</label>
					<div>
					<?php
						 $data = array('name' => 'UOM','value' => set_value('UOM'),'id'=>'UOM',  'class' => 'form-control','readonly' => 'true' );
						echo form_input($data);
						?>  
									 
					</div>
			</div>
			<div class="col-md-6">
				<label>Quantity</label>
					<div class="form-group">
								<?php
						 $data = array('name' => 'Quantity','value' => set_value('Quantity'),'id'=>'Quantity',  'class' => 'form-control' ,'onkeypress'=>'return isNumberKey(event)','maxlength'=>'20');
						echo form_input($data);
						?>   
					</div>
			</div>
			
		 
			</div>
			
			<div class="modal-footer">
			<a class="btn btn-info font addClick"   ID="addClick"  ><i class="fa fa-plus"></i>&nbsp;&nbsp;<span 	class="bold">Add</span></a>
						<a  class="btn btn-info" data-dismiss="modal"  value="Cancel">cancel</a>
			</div>
		  </div>
						  
						</div>
					  </div>
   
  
  </div><br/> <div class="modal fade" id="EditItem" role="dialog">
		<div class="modal-dialog">
		
		  <!-- Modal content-->
		  <div class="modal-content">
			<div class="modal-header">
			  <button type="button" class="close" data-dismiss="modal">&times;</button>
			  <center><h4>Edit Line Item </h4></center>				
			</div>
			<div align="left"> 
			 
			 <div class="col-md-6">
				<label>Material Code</label>
					<div >						
							<?php
                                         $data = array('name' => 'EditMaterialCode', 'value' => set_value('EditMaterialCode'),'id'=>'EditMaterialCode', 'class' => 'form-control','readonly'=>'true');
                                        echo form_input($data);
                                        ?>  						
					</div>
			</div>

			<div class="col-md-6">
				<label>Description</label>
				<div class="form-group">
						<?php
						 $data = array('name' => 'EditDescription','value' => set_value('EditDescription'),'id'=>'EditDescription',  'class' => 'form-control','readonly' => 'true' );
						echo form_input($data);
						?>   
				</div>
			</div>
			<div class="col-md-6">
				<label>UOM</label>
					<div>
					<?php
						 $data = array('name' => 'EditUOM','value' => set_value('EditUOM'),'id'=>'EditUOM',  'class' => 'form-control','readonly' => 'true' );
						echo form_input($data);
						?>  
									 
					</div>
			</div>
			<div class="col-md-6">
				<label>Quantity</label>
					<div class="form-group">
								<?php
						 $data = array('name' => 'EditQuantity','value' => set_value('EditQuantity'),'id'=>'EditQuantity',  'class' => 'form-control','onkeypress'=>'return isNumberKey(event)','maxlength'=>'20');
						echo form_input($data);
						?>   
					</div>
			</div>
			
		 
			</div>
			
			<div class="modal-footer">
			<a class="btn btn-info font EditClick"  ID="EditClick"  ><i class="fa fa-plus"></i>&nbsp;&nbsp;<span 	class="bold">Edit</span></a>
						<a  class="btn btn-info" data-dismiss="modal"  value="Cancel">Cancel</a>
			</div>
		  </div>
						  
						</div>
					  </div>
   
  
  </div></br>
  
   <table id="Items" class="table table-bordered table-hover" style="background-color:#fff;font-size:12px;">
                <thead style="background-color:#ddf">
        <tr>
        <th>SNo</th>
        <th>Material Code</th>
        <th>Material Name</th>
        <th>Uom</th>
		<th>Quantity</th>
         <th>Action</th>
      </tr>
    </thead>
    <tbody id="tempAppend">
       
     
    </tbody>
	
  </table>
         
 <div align="right" style="padding-right:10px">
   <input type="hidden" name="txtRowCount" id="txtRowCount" />
   <input type="hidden" name="txtDeletedRow" id="txtDeletedRow" />
  <a class="btn btn-primary Save"  ID="Save" onclick="Save()" >&nbsp;&nbsp;<span class="bold">Save</span></a> 

  <input type="submit" class="btn btn-primary" >
  <input type="reset" class="btn btn-primary">
   
  </div>
         <br>
	 </div>
         </div>
         
        </section>
</div>

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

          return true;
       }
	
$(function() {
	
    $( ".datePicker" ).datepicker({ dateFormat: 'dd/mm/yy' });

    //Initialize Select2 Elements
    $(".select2").select2();
	
$('#CostCenter').change(function() {
    
 var id = $('#CostCenter').val();
 $("#AvlBudgetAmount").val('');

 var ReqType = $('#RequestType').val();
  
		if(id != '-1' && ReqType != '-1')
		{
			
			$('#content').loader('show');
		  $.ajax({ 
			data:{id:id},
			type:"POST",
			url:"<?php echo base_url() ?>servicepurchaseorder/AvilBudgetAmount?ReqType="+ReqType, 
			success:function(data) {
			if(data)
			{
				$('#content').loader('hide'); 
				$("#AvlBudgetAmount").val(data);
				if(parseFloat($("#AvlBudgetAmount").val()) <= 0)
				{
					$('#AlertImg').removeAttr("style");	
					isExceed = 1;					
				}
				else
				{
					 $('#AlertImg').attr("style","display:none;");
					 isExceed =0;	
				}
			}
			else
			{
				$('#content').loader('hide'); 
				alert("Error");	
			}
			}			
			  
			});	
			
		}
		else
		{
			alert('Please select the Requistion Type');
			$('#CostCenter').val("-1");
			return false;
		}
  
});
	$('#RequestType').change(function() 
	{
	 $("#AvlBudgetAmount").val('');	
    $('#AlertImg').attr("style","display:none;");
	$('#txtRowCount').val('');
	$('#txtDeletedRow').val('');	
    $("#Description").val('');
	$("#UOM").val('');
	$('#CostCenter').val("-1");
		 
	 removeHiddenRows($('#Items').find('tr').length);
	 $('#tempAppend').empty();
	var id = $('#RequestType').val(); 

		if(id != '-1')
		{
			$('#content').loader('show');

			$.ajax({
			data:{id:id},
			dataType: 'json',
			type:"POST",
			url:"<?php echo base_url();?>requisitionform/getMaterialCode",
			success:function(json) {		
			$('#content').loader('hide');
				
				$("#MaterialCode").empty();
				$("#MaterialCode").append(json.Material);
               // $("#Description").val(json.MaterialName);	
				//$("#UOM").val(json.UOM);					
		      }
			  
			});	
			//$('#content').loader('hide');
		}
		else
		{
			alert('Please select the RequestType');
			return false;
		}
  
});
$('#MaterialCode').change(function() {
    
 var id = $('#MaterialCode').val(); 

$("#Description").val('');	
$("#UOM").val('');	
		if(id != '-1')
		{
			$('#content').loader('show');

			$.ajax({
			data:{id:id},
			dataType: 'json',
			type:"POST",
			url:"<?php echo base_url();?>requisitionform/getMaterialDetails",
			success:function(json) {		
			$('#content').loader('hide');
			//alert(json.MatDetail);
					$("#Description").val(json.MatDetail[0]['MaterialName']);	
					$("#UOM").val(json.MatDetail[0]['UOM']);									
		      }
			  
			});	
			//$('#content').loader('hide');
		}
		else
		{
			alert('Please select the RequestType');
			return false;
		}
  
});


});
	</script>
	<script type="text/html" id="tempList">
<tr  id="<%=index%>">
<td align="left"><%=index%></td>
 <td align="left"><%=MaterialCode%></td>
 
  <td align="left"><%=MaterialName%></td>
  
  <td align="left"><%=UOM%></td>

  <td align="left"><%=Quantity%></td> 
   <td>
                          <a    data-target='#EditItem'	data-id="<%=index%>" data-userid="<%=index%>" data-toggle="modal" href="#EditItem"><i class="fa fa-pencil" data-toggle="tooltip" title="Click here to view/Edit the  <%=MaterialCode%> Material details"></i>&nbsp;&nbsp;&nbsp;</a> <a href='#' onclick = "Deleterow(<%=index%>)" class="link" data-id="<%=index%>" data-userid="<%=index%>"  id="Del" ><span class="glyphicon glyphicon-trash"></span></a>
						 
						  
                      </td>
</tr>
</script>
<script>
var index     = '1';
var userid  = '';
function removeHiddenRows(rowcount)
{
	var step;
	alert(rowcount);
	if(rowcount > 2)
	{
for (step = 1; step < rowcount ; step++) {
	var td = document.getElementById(step);
	td.parentNode.removeChild(td);
	$("#MaterialCode"+step).remove();
	$("#Description"+step).remove();
	$("#UOM"+step).remove();
	$("#Quantity"+step).remove();
	index     = '1';
	userid  = '';
}	
}
}
function Save()
{  

 var id = '<?php echo REQ_DRAFT;?>'
	if(validate())
		{ 	
			if(document.getElementById('Items').rows.length < 0)
			{
				alert('Please Select Line item to Create Requisition');
				$('#Deliverydt').focus();
				return false;
			}
			
			else
			{
				$('#content').loader('show');
		  $.ajax({ 
			data:$('.requistion').serialize(),
			type:"POST",
			url:"<?php echo base_url() ?>requisitionform/addNewRequistion?ID="+id, 
			success:function(data) {
			if(data)
			{
				$('#content').loader('hide'); 
				alert(data);
				$('#txtRowCount').val('');
				$('#txtDeletedRow').val('');
				
				window.location =	"Requisition";
			
			}
			else
			{
				alert("Error");	
			}			
		
		}
  
});
			}

}
}
function validate()
{
	if($("option:selected", $("#RequestType")).val() == '-1')
	{
		alert('Please Select ReqType Names');
		return false;
	}
	else if($("option:selected", $("#EmpID")).val() == '-1')
	{
		alert('Please Select Reqby');
		return false;
	}
	else if($("#txtRowCount").val().length < 1)
	{
		alert('Please Add Line Item');
		return false;
	}
	else if(isExceed == 1)
	{
		alert('You dont have Budget and You cant Raise New Requisition');
		return false;
	}
	else 
	{
	return true;
	}
	
}	
function Deleterow(rowid)
{
	   var DelRows  = $('#txtDeletedRow').val();
	  
	   var answer = confirm(" Do you want to delete the Item from the List?")
		if (answer) 
		{ 			
			var td = document.getElementById(rowid);
			td.parentNode.removeChild(td);
	
		  if(DelRows != '')
		  {
		  DelRows = DelRows + ":" + rowid;
		  }
		  else
		  {
			  DelRows=  "0" + ":" + rowid;
		  }
		  $('#txtDeletedRow').val(DelRows);
		}
       	
} 
function validateBeforeAdd()
{
	if($("option:selected", $("#RequestType")).val() == '-1')
	{
		alert('Please select the Request Type ');
		$("#RequestType").focus();
		return false;
	}
	else if($("#CostCenter").val() == '-1')
	{
		alert('Please select the Cost center to check the Budget Availablity ');
		$("#CostCenter").focus();
		return false;
	}
	else if( isExceed == '1')
	{
		alert('You dont have available Budget Amount. You cant raise new Requisition');
		return false;
	}	
	else
	{
		 $('#myModal1').modal('show');
	}
}

$('.addClick').click(function(){
         
       if ($("#MaterialCode option:selected").val() =='-1' )
		{
			 alert('Please Select the MaterialCode ');
			 return false;
		}	
			
    	if(document.getElementById('Quantity').value == '' )
		{
		  alert('Please Enter the Quantity');
		  return false;
		  
		}	  
		
        if ($("#MaterialCode option:selected").val() !='-1' &&  $('#Quantity').val() != ''  )
        {		       
         var temp = index;
         var materialCode = $("#MaterialCode option:selected").val();
         var materialName =  $("#Description").val();
         var uom = $("#UOM").val();
		 var quantity = $("#Quantity").val();
		 
		$('#MaterialCode option[value='+materialCode+']').remove();
		  
		 $('#Description').val(''); 
		  $('#UOM').val(''); 
		   $('#Quantity').val('');       
			
			index = parseInt(index)+1;		
		 
	      var template = jQuery("#tempList").html();
	   
	     
          $('#tempAppend').append(_.template(template,{index:temp,MaterialCode:materialCode,MaterialName:materialName,UOM:uom,Quantity:quantity}));
		  
		  
		 var theForm = $(".requistion");
		
		 addHidden(theForm,"MaterialCode"+temp,materialCode);
		 addHidden(theForm,"Description"+temp,materialName);
	     addHidden(theForm,"UOM"+temp,uom);
		 addHidden(theForm,"Quantity"+temp,quantity);		
		 
		 $('#txtRowCount').val(temp); 			
		
      }    
   
 });
 function addHidden(theForm, key, value) {
    // Create a hidden input element, and append it to the form:
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = key;'name-as-seen-at-the-server';
    input.id = key;'name-as-seen-at-the-server';
    input.value = value;
    theForm.append(input);
}
$("#myModal1").on("shown.bs.modal", function(e) {
    if($("option:selected", $("#RequestType")).val() == '-1')
	{
		alert('Please select the Request Type ');
		e.close();
	}
});

$("#EditItem").on("shown.bs.modal", function(e) {
     userid = $(e.relatedTarget).data('userid');
	// alert(userid);
	 var tr= document.getElementById(userid);
	 var cellval = tr.cells;
	 //alert(x[1].innerHTML);
	$('#EditMaterialCode').val(cellval[1].innerHTML);
	$('#EditDescription').val(cellval[2].innerHTML);
   $('#EditUOM').val(cellval[3].innerHTML);
    $('#EditQuantity').val(cellval[4].innerHTML);
});

$('.EditClick').click(function(){
         
   		if(document.getElementById('EditQuantity').value == '' )
		{
		  alert('Please Enter the Quantity' );
		 }  
		
        if ( $('#EditQuantity').val() != '' )
        {	
      
			var editMaterialCode =  $("#EditMaterialCode").val();
			var editDescription = $("#EditDescription").val();		
			var editUOM = $('#EditUOM').val();
			var editQuantity = $('#EditQuantity').val();
     	
            var tr= document.getElementById(userid);
			var cellval = tr.cells;   
			cellval[1].innerHTML = editMaterialCode;
			cellval[2].innerHTML = editDescription;
			cellval[3].innerHTML =editUOM;
			cellval[4].innerHTML = editQuantity;
			
			$('#MaterialCode'+userid).val(editMaterialCode);
			$('#Description'+userid).val(editDescription);
			$('#UOM'+userid).val(editUOM);
			$('#Quantity'+userid).val(editQuantity);
            			
		
      }
    
 });
  $(".requistion").submit(function(e) {
        
		var id='<?php echo REQ_PENDING_APPROVAL;?>'
		e.preventDefault();
		if(validate())
		{
			if(document.getElementById('Items').rows.length < 0)
			{
				alert('Please Select Line item to Create Requisition');
				$('#Deliverydt').focus();
				return false;
			}
			else
			{
				$('#content').loader('show');
		  $.ajax({ 
			data:$('.requistion').serialize(),
			type:"POST",
			url:"<?php echo base_url() ?>requisitionform/addNewRequistion?ID="+id, 
			success:function(data) {
			if(data)
			{
				$('#content').loader('hide'); 
				alert(data);
				$('#txtRowCount').val('');
				$('#txtDeletedRow').val('');
				
				window.location =	"Requisition";
			
			}
			else
			{
				alert("Error");	
			}			
		
		}
  
	}); 
	
			}
		}
	
		 });
		 <!-- script for table , It works under the datatable plugin-->
 $(function () {  
    $('#Items').DataTable({
      "paging": false,
      "lengthChange": true,
      "searching": false,
      "ordering": false,
     "info": false,
      "autoWidth": true
	   
    }); 
  });
</script>