<?php
require_once("../includes/config.php");

///////// for page ///////
if(isset($_REQUEST['pid'])){ $pidvar = $_REQUEST['pid']; }else{ $pidvar = "";}

///////// required data /////////
if(isset($_REQUEST['status'])){ $statusvar = $_REQUEST['status']; }else{ $statusvar = "";}
if(isset($_REQUEST['request_from'])){ $request_fromvar = $_REQUEST['request_from']; }else{ $request_fromvar = "";}
if(isset($_REQUEST['request_to'])){ $request_tovar = $_REQUEST['request_to']; }else{ $request_tovar = "";}
if(isset($_REQUEST['daterange'])){ $daterangevar = $_REQUEST['daterange']; }else{ $daterangevar = "";}


$get_opr_rgts = getOprRights($_SESSION['userid'],$pidvar,$link1);
/////////check approval is applicable or not
$apply_app = getAnyDetails($pidvar,"apply_approval","tabid","tab_master",$link1);
///// get access location details
$access_loc = getAccessLocation($_SESSION['userid'],$link1);
@extract($_POST);
////// if we want to Add BOM
if($_POST){
	if ($_POST['saveButton']=='Save'){
		
		///// make a string token
		$messageIdent = md5($_POST['saveButton'] . $_POST['request_to'] . $_POST['request_from']);
		//and check it against the stored value:
    	$sessionMessageIdent = isset($_SESSION['raisePoAddSession'])?$_SESSION['raisePoAddSession']:'';
    	if($messageIdent!=$sessionMessageIdent){//if its different:          
        //save the session var:
        $_SESSION['raisePoAddSession'] = $messageIdent; 
		//// check if approval is applicable then status will set to 3(PFA) otherwise 6 (Pending)
		if($apply_app=="Y"){ $current_status = 3;}else{ $current_status = 6;}
		//// initialize transaction parameters
		$flag=true;
		mysqli_autocommit($link1, false);
		$error_msg="";
		//// check atleast one entry should be done
		if(is_array($_POST['req_qty'])){
			$qty_var = $_POST['req_qty'];
			$price_var = $_POST['price'];
			$value_var = $_POST['value'];
			$schedule_date_var = $_POST['schedule_date'];
			$item_id = $_POST['partcode'];
			$remk = $_POST['rmk'];
			$len = count($_POST['req_qty']);
			if($len>0){
				////// get address ////////////
				$from_addr = getAnyDetails($_POST['request_from'],"locationaddress","location_code","location_master",$link1);
				$to_addr = getAnyDetails($_POST['request_to'],"billing_address","vendor_code","vendor_master",$link1);
				
				/////// pick PO series from document counter
				$rs = mysqli_fetch_array(mysqli_query($link1,"SELECT doc_str,doc_count from document_counter where doc_type='PO' and location_code='".$_POST['request_from']."'"));
				if($rs['doc_str']){
					$req_no = $rs['doc_count'] + 1;
					$request_no = $rs['doc_str'].str_pad($req_no,5,0,STR_PAD_LEFT);
					// insert request no detail in parent table \\					
					$req_res1 = mysqli_query($link1,"INSERT INTO po_master set from_location='".$_POST['request_from']."',to_location='".$_POST['request_to']."', system_ref_no='".$request_no."',temp_no='".$req_no."',document_type='PO',entry_date='".$today."',entry_time='".$currtime."',entry_by='".$_SESSION['userid']."',entry_ip='".$ip."',status='".$current_status."',from_address='".$from_addr."',to_address='".$to_addr."',bill_address='".$_POST['bill_address']."',ship_address='".$_POST['ship_address']."',remark='".$_POST['remark']."'");
					//// check if query is not executed
					if (!$req_res1) {
						$flag = false;
						$err_msg = "Error Code1: ".mysqli_error($link1);
					}
					////// pick all parts and insert in data table
					//$total_qty = 0;
					for($i = 0; $i < $len; $i++){
						$item = $item_id[$i];
						$quan = $qty_var[$i];
						$rate = $price_var[$i];
						$val = $value_var[$i];
						$schedule = $schedule_date_var[$i];
						$production_rmk = $remk[$i];
						if($item!="" && $quan!="0"){
							$getpart = explode("~",$item);
							// insert model qty detail in child table \\
							$req_res2 = mysqli_query($link1,"INSERT INTO po_data set system_ref_no='".$request_no."', partcode='".$getpart[0]."', req_qty='".$quan."',pending_qty='".$quan."',price='".$rate."',value='".$val."',schedule_date='".$schedule."',purchase_unit='".$getpart[1]."',remark='".$production_rmk."'");
							//// check if query is not executed
							if (!$req_res2) {
								$flag = false;
								$err_msg = "Error Code2: ".mysqli_error($link1);
							}
							//$total_qty += $quan;
						}
					}// close for loop
				}else{
					$flag = false;
					$err_msg = "Error Code2.1 :Document series not found for request to location.";		
				}
			}//if($total_qty == 0)
			else{
				$flag = false;
				$err_msg = "Error Code4: You have not selected any part.";
			}
		}
		//update document count
		$req_res3 = mysqli_query($link1,"UPDATE document_counter set doc_count = doc_count+1 where doc_type='PO' and location_code='".$_POST['request_from']."'");
		if (!$req_res3) {
			$flag = false;
			$err_msg = "Error Code3: ".mysqli_error($link1);
		}
		////// insert in activity table////
		$flag =	dailyActivity($_SESSION['userid'],$request_no,"RAISE PO","ADD",$ip,$link1,$flag);
		///// check both master and data query are successfully executed
		if ($flag) {
			mysqli_commit($link1);
			$msg = "Raise PO with ref. no. ".$request_no;
			$cflag="success";
			$cmsg = "Success";
		} else {
			mysqli_rollback($link1);
			$msg = "Request could not be processed ".$err_msg.". Please try again.";
			$cflag="danger";
			$cmsg = "Failed";
		} 
		mysqli_close($link1);
		} else {
        	//you've sent this already!
  			$msg = "Re-submission is not allowed";
			$cflag="warning";
			$cmsg = "Warning";
    	}	
		///// move to parent page
    	header("location:po_status_list.php?msg=".$msg."&chkflag=".$cflag."&chkmsg=".$cmsg."".$pagenav);
    	exit;
	}
}
?>
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title><?=siteTitle?></title>
 <link rel="shortcut icon" href="../images/titleimg.png" type="image/png">
 <script src="../js/jquery.js"></script>
 <?php 
 include("../includes/fontawesome.html");
 include("../includes/main_css.html"); 
 include("../includes/bootstrap.html");
 ?>
 <script>
$(document).ready(function(){
	var spinner = $('#loader');
        $("#frm1").validate({
		  submitHandler: function (form) {
			if(!this.wasSent){
				this.wasSent = true;
				$(':submit', form).val('Please wait...')
								  .attr('disabled', 'disabled')
								  .addClass('disabled');
				spinner.show();				  
				form.submit();
			} else {
				return false;
			}
          }
		});
	$('.selectpicker').selectpicker({
	  //actionsBox: true,
	  //container: true,
      liveSearch: true
	});
	$('.number').on('input', function() {
		match = (/(\d{0,6})[^.]*((?:\.\d{0,6})?)/g).exec(this.value.replace(/[^\d.]/g, ''));
		this.value = match[1] + match[2];
  	});
});
function makedropdown(){
	$('.selectpicker').selectpicker({
      liveSearch: true
	});
	$('.number').on('input', function() {
		match = (/(\d{0,6})[^.]*((?:\.\d{0,6})?)/g).exec(this.value.replace(/[^\d.]/g, ''));
		this.value = match[1] + match[2];
  	});
}
/////// add new row 
$(document).ready(function() {
	$("#add_row").click(function() {		
		var numi = document.getElementById('rowno');
		var itm = "partcode[" + numi.value+"]";
		var preno=document.getElementById('rowno').value;
		var num = (document.getElementById("rowno").value -1)+2;
		numi.value = num;
		if ((document.getElementById(itm).value != "") || ($("#addr1_" + numi.value + ":visible").length == 0)) {
			var r = '<tr id="addr1_'+num+'"><td width="26%"><div><select name="partcode['+num+']" id="partcode['+num+']" class="form-control required selectpicker show-tick" required data-width="350px" onChange="getunit(this.value,'+num+')"><option value="">--Select Part--</option><?php $res_pro = mysqli_query($link1,"select partcode,part_name,bom_unit,purchase_unit,material from partcode_master where status='1' order by part_name")or die(mysqli_error($link1));while($row_pro = mysqli_fetch_assoc($res_pro)){?><option value="<?=$row_pro['partcode']."~".$row_pro['purchase_unit']?>"><?=$row_pro['part_name']." | ".$row_pro['material']." | ".$row_pro['partcode']?></option><?php } ?></select></div><div style="display:inline-block;float:left;"><i class="fa fa-close fa-lg" onClick="fun_remove('+num+');"></i></div></td><td width="10%"><input type="text" name="req_qty['+num+']" class="form-control number required" required id="req_qty['+num+']" value="0" onKeyUp="getValue('+num+')" /></td><td width="10%"><input type="text" name="price['+num+']" class="form-control number required" required id="price['+num+']" value="0" onKeyUp="getValue('+num+')"/></td><td width="12%"><input type="text" name="value['+num+']" class="form-control number required" required id="value['+num+']" readonly="readonly"/></td><td width="10%"><span id="unit'+num+'"></span></td><td width="12%"><input type="text" class="form-control  required span2" required name="schedule_date['+num+']"  id="schedule_date'+num+'" value=""></td><td width="20%"><input type="text" name="rmk['+num+']" class="form-control addressfield" id="rmk['+num+']"/> </td></tr>';
			$('#itemsTable1').append(r);
			makedropdown();
			makeCalDOP(num);
		}
	});
});
function fun_remove(con){
	var c = document.getElementById('addr1_' + con);
	c.parentNode.removeChild(c);
	con--;
	document.getElementById('rowno').value = con;
}
function getunit(val,indx){
	var split_val = val.split("~");
	document.getElementById("unit"+indx).innerHTML = split_val[1];
	checkDuplicatePart(indx,split_val[0]);
}
$(document).ready(function() {
    $("#request_type").change(function() {
        if(this.value == "JC"){
			$("#job_no").show();
			$("#ref_no").hide();
		}else{
			$("#job_no").hide();
			$("#ref_no").show();
		}
    });
});

//// make dynamic calender
function makeCalDOP(ind){
	$('#schedule_date'+ind).datepicker({
		format: "yyyy-mm-dd",
		startDate: "<?=$today?>",
		todayHighlight: true,
		autoclose: true,
	});
}
$(document).ready(function () {
	$('#schedule_date0').datepicker({
		format: "yyyy-mm-dd",
		startDate: "<?=$today?>",
		todayHighlight: true,
		autoclose: true
	});
});
/////// get billing and shipping address ////////////
function getAddress(val){
	$.ajax({
		type:'post',
		data:{get_address:val,fields:"locationaddress,deliveryaddress"},
		url:'../includes/getAzaxFields.php',
		success:function(data){
			var addr = data.split("~");
			document.getElementById("bill_address").value = addr[0];
			document.getElementById("ship_address").value = addr[1];
		}
	});
}
//////// calculate value ///////////
function getValue(indx){
	var req_qty = document.getElementById('req_qty['+indx+']').value;
	var price = document.getElementById('price['+indx+']').value;
	if(req_qty!='' && price!=''){
		document.getElementById('value['+indx+']').value = (req_qty*price);
	}else{
		document.getElementById('value['+indx+']').value = 0.00;
	}
}

///// function for checking duplicate partcode
function checkDuplicatePart(fldIndx1,val){
  if(val!=''){
     var check2="partcode["+fldIndx1+"]";
	 var flag=1;
	 for(var i=0;i<=fldIndx1;i++){
	  	 var check1="partcode["+i+"]";
		 if(fldIndx1!=i && document.getElementById(check2).value!='' && document.getElementById(check1).value!=''){
		    if((document.getElementById(check2).value==document.getElementById(check1).value) ){
			    document.getElementById("error_msg").innerHTML="Duplicate Part selection";
				document.getElementById(check2).value="";
			    //document.getElementById(check2).className="form-control required selectpicker show-tick alert-danger";
				flag*=0;
			}
		    else{
				document.getElementById("error_msg").innerHTML="";
			    //document.getElementById(check2).className="form-control required selectpicker show-tick";
				flag*=1;
			 ///do nothing
			}
		 }
	 }//// close for loop
	 if(flag==0){ 
	 	return false;
	 }else{ 
	 	return true;
	 }
  }
}
////////////////// Calculate Tax/////////////////////
function checkAllRows(){
	var rowno1 = document.getElementById("rowno").value;
	var flag=1;
	if(rowno1 > 0){
		for(var j=0;j<rowno1;j++){
        	var check2="partcode["+j+"]";
				for(var i=0;i<=rowno1;i++){
					if(j!=i){
						var check1="partcode["+i+"]";
						var rqty="req_qty["+i+"]";
						var runit="unit"+i+"";
						var rrmk="rmk["+i+"]";
		 				if(document.getElementById(check2).value==document.getElementById(check1).value){
			 				document.getElementById("error_msg").innerHTML="Duplicate Part selection";
							document.getElementById(check1).value="";
							document.getElementById(rqty).value='';
							document.getElementById(runit).innerHTML='';
							document.getElementById(rrmk).value="";
							flag*=0;
						}
		 				else{
			 			//document.getElementById(defQty).value='1';
						flag*=1;
						}
					}
				}
		}
		//////////
		if(flag==0){ 
			return false;
		 }else{ 
			return true;
		 }
		}
}
</script>
<script src="../js/bootstrap-select.js"></script>
<link href="../css/bootstrap-select.css" rel="stylesheet"/>
<script src="../js/jquery.validate.js"></script>
<link href="../css/loader.css" rel="stylesheet"/>
<!-- Include Date Picker -->
<link rel="stylesheet" href="../css/datepicker.css">
<script src="../js/bootstrap-datepicker.js"></script>
</head>
<body>
<div class="container-fluid">
  <div class="row content">
	<?php 
    include("../includes/leftnav_admin.php");
    ?>
    <div class="<?=$screenwidth?>">
      <h2 align="center"><i class="fa <?=$fa_icon?>"></i> Add Raise PO</h2><br/>
      <h4 align="center"><span id="error_msg" class="red_small" style="text-align:center"></span></h4>
      <div class="form-group"  id="page-wrap" style="margin-left:10px;">
          <form id="frm1" name="frm1" class="form-horizontal" action="" method="post">
          <div class="form-group">
              <div class="col-md-6">
                <label class="col-md-6 control-label">Raise From <span class="red_small">*</span></label>
                <div class="col-md-6">
                  <select name="request_from" id="request_from" class="form-control required custom-select" required onChange="getAddress(this.value);" >
                    <option value="">--Please Select--</option>
                    <?php
					$sql1 = "SELECT location_code,locationname FROM location_master where statusid= '1' and location_code in (".$access_loc.") order by locationname";
					$res1 = mysqli_query($link1,$sql1);
					while($row1 = mysqli_fetch_array($res1)){
					?>
                    <option value="<?=$row1['location_code']?>"<?php if(isset($_REQUEST['request_from'])){if($_REQUEST['request_from']==$row1['location_code']){ echo "selected";}}?>><?php echo $row1['locationname']." (".$row1['location_code'].")";?></option>
                    <?php }?>
                  </select>
                </div>
              </div>
              <div class="col-md-6">
                <label class="col-md-6 control-label">Raise To <span class="red_small">*</span></label>
                <div class="col-md-6">
				  <select name="request_to" id="request_to" class="form-control required custom-select" required >
                    <option value="">--Please Select--</option>
                    <?php
					$sql1 = "SELECT vendor_code,vendor_name FROM vendor_master where status = '1' order by vendor_name";
					$res1 = mysqli_query($link1,$sql1);
					while($row1 = mysqli_fetch_array($res1)){
					?>
                    <option value="<?=$row1['vendor_code']?>"<?php if(isset($_REQUEST['request_to'])){if($_REQUEST['request_to']==$row1['vendor_code']){ echo "selected";}}?>><?php echo $row1['vendor_name']." (".$row1['vendor_code'].")"; ?></option>
                    <?php }?>
                  </select>
                </div>
              </div>
            </div>
            
            <div class="form-group">
             <div class="col-md-6">
                <label class="col-md-6 control-label">Billing Address<span class="red_small">*</span></label>
                <div class="col-md-6">
                  <textarea name="bill_address" id="bill_address" class="form-control addressfield required" style="resize:none" required></textarea>
                </div>
              </div>
              <div class="col-md-6">
                <label class="col-md-6 control-label">Shipping Address<span class="red_small">*</span></label>
                <div class="col-md-6">
                  <textarea name="ship_address" id="ship_address" class="form-control addressfield required" style="resize:none" required></textarea>
                </div>
              </div>
            </div>
			
			<div class="form-group">
             <div class="col-md-6">
                <label class="col-md-6 control-label">Remark</label>
                <div class="col-md-6">
                  <textarea name="remark" id="remark" class="form-control addressfield" style="resize:none"></textarea>
                </div>
              </div>
            </div>
			





        <div class="col-md-12"><label class="col-md-4 control-label">Attach File<span class="red_small">*</span></label>
                            <div class="col-md-4">
                                <div class="input-group">
                                    <label class="input-group-btn">
                        <span class="btn btn-primary">
                            Browse… <input type="file" name="file" id="file" class="form-control required" required="" style="display:none;" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
                        </span>
                                    </label>
                                    <input type="text" class="form-control" name="billfile" id="billfile" readonly="">
                                </div>
                            </div>
                            <div class="col-md-4" align="right"><span class="red_small">NOTE: Attach only <strong>.xlsx (Excel Workbook)</strong> file</span></div>
                        </div>






          <div class="form-group">
          	<div class="col-md-4" style="display:inline-block; float:left">
               
                <input type="hidden" name="rowno" id="rowno" value="0"/>
           </div>
           <div class="col-md-8" style="display:inline-block; float:right" align="left">
           	  <button class='btn<?=$btncolor?>' id="save" type="submit" name="saveButton" value="Save" onClick="checkAllRows();"><i class="fa fa-save fa-lg"></i>&nbsp;&nbsp;Upload</button>
              <button title="Back" type="button" class="btn<?=$btncolor?>" onClick="window.location.href='raise_po_list.php?status=<?=$statusvar?>&request_from=<?=$request_fromvar?>&request_to=<?=$request_tovar?>&daterange=<?=$daterangevar?><?=$pagenav?>'"><i class="fa fa-reply fa-lg"></i>&nbsp;&nbsp;Back</button>
            </div>
          </div>
    </form>
      </div>

    </div>
    
  </div>
</div>
<div id="loader"></div>
<?php
include("../includes/footer.php");
include("../includes/connection_close.php");
?>
</body>
</html>