<?php
require_once("../config/config.php");
////// final submit form ////
@extract($_POST);
if($_POST['Submit']=='Save'){
	mysqli_autocommit($link1, false);
	$flag = true;
	
	////// count max no. of location in selected state
    $query_code="select MAX(temp_no) as tn from hrms_employe_master where 1 ";
    $result_code=mysqli_query($link1,$query_code)or die("ER2".mysqli_error($link1));
    $arr_result2=mysqli_fetch_array($result_code);
    $code_id=$arr_result2[0];
	/// make 4 digit padding
    $pad=str_pad(++$code_id,4,"0",STR_PAD_LEFT);
    /// make logic of location code
    $newemployeecode=substr(strtoupper(BRANDNAME),0,2)."EMP".$pad;
	 
	if(mysqli_num_rows(mysqli_query($link1,"SELECT empid from hrms_employe_master where loginid='".$newemployeecode."' "))==0){
		
		$sql1 = "INSERT INTO hrms_employe_master SET empname = '".$emp_name."', loginid = '".$newemployeecode."', temp_no = '".$code_id."', password = '".$newemployeecode."', companyid = '".$comp_name."', departmentid = '".$deprt_name."', designationid = '".$desig_name."', managerid = '".$mngr_name."', joining_date = '".$jd."', date_of_birth = '".$dob."', aletrnate_email = '".$email1."', alternate_no = '".$phone1."', remark = '".$remark."', address = '".$address."', city = '".$locationcity."', state = '".$locationstate."', circle = '".$circle."', phone = '".$phone."', email = '".$email."', utype = '".$emptype."', createby = '".$_SESSION['userid']."', createdate = '".date("Y-m-d H:i:s")."', status = '".$status."', emp_type = '".$jobtype."' ";
		
		$res1=mysqli_query($link1,$sql1);	
		/// check if query is execute or not//
		if(!$res1){
			$flag = false;
			$err_msg = "Error 1". mysqli_error($link1) . ".";
		}
		
		//// create password  ///
		$pwd=$newemployeecode."@321";
		
		$sql2 = "INSERT INTO admin_users SET username = '".$newemployeecode."', password = '".$pwd."', name = '".$emp_name."', utype = '11', phone = '".$phone."', emailid = '".$email."', city = '".$locationcity."', state = '".$locationstate."', status = '".$status."', create_by = '".$_SESSION['userid']."', createdate = '".date("Y-m-d H:i:s")."' ";
		
		$res2=mysqli_query($link1,$sql2);	
		/// check if query is execute or not//
		if(!$res2){
			$flag = false;
			$err_msg = "Error 2". mysqli_error($link1) . ".";
		}
		
	}else{
		////// return message
		$msg="Something went wrong like employee code was already in DB. Please try again.";
	}
	
	///// check all query are successfully executed
	if ($flag) {
		////// insert in activity table////
		dailyActivity($_SESSION['userid'],$newemployeecode,"EMPLOYEE","ADD",$ip,$link1,"");
		dailyActivity($_SESSION['userid'],$newemployeecode,"ADMIN USER","ADD",$ip,$link1,"");
		
        mysqli_commit($link1);
		$msg="You have successfully created a new employee with ref. no. and employee user id is ".$newemployeecode;
		///// move to parent page
		header("location:employee_master_list.php?msg=".$msg."&sts=success".$pagenav);
		exit;
    } else {
		mysqli_rollback($link1);
		$msg = "Request could not be processed. Please try again.";
		///// move to parent page
		header("location:employee_master_list.php?msg=".$msg."&sts=fail".$pagenav);
		exit;
	} 
    mysqli_close($link1);
}
?>

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title><?=siteTitle?></title>
 <script src="../js/jquery.min.js"></script>
 <link href="../css/font-awesome.min.css" rel="stylesheet">
 <link href="../css/abc.css" rel="stylesheet">
 <script src="../js/bootstrap.min.js"></script>
 <link href="../css/abc2.css" rel="stylesheet">
 <link rel="stylesheet" href="../css/bootstrap.min.css">
 <link rel="stylesheet" href="../css/bootstrap-select.min.css">
 <script src="../js/bootstrap-select.min.js"></script>
 <script src="../js/bootstrap-datepicker.js"></script>
 <script>
	$(document).ready(function(){
        $("#frm1").validate();
    });
 </script>
 <script>
 	$(document).ready(function() {
		$('#dob').datepicker({
			format: "yyyy-mm-dd",
			todayHighlight: true,
			autoclose: true
		});
	});
	$(document).ready(function() {
		$('#jd').datepicker({
			format: "yyyy-mm-dd",
			todayHighlight: true,
			startDate: "<?=$todayt?>",
			autoclose: true
		});
	});
	function makeSelect(){
	  $('.selectpicker').selectpicker({
		liveSearch: true,
		showSubtext: true
	  });
	}
 </script>
 <script type="text/javascript" src="../js/jquery.validate.js"></script>
 <script type="text/javascript" src="../js/common_js.js"></script>
 <script language="javascript" type="text/javascript">
  /////////// function to get state on the basis of circle
  $(document).ready(function(){
	$('#circle').change(function(){
	  var name=$('#circle').val();
	  $.ajax({
	    type:'post',
		url:'../includes/getAzaxFields.php',
		data:{circle:name},
		success:function(data){
	    $('#statediv').html(data);
	    }
	  });
    });
  });
 /////////// function to get city on the basis of state
 function get_citydiv(){
	  var name=$('#locationstate').val();
	  $.ajax({
	    type:'post',
		url:'../includes/getAzaxFields.php',
		data:{state:name},
		success:function(data){
	    $('#citydiv').html(data);
	    }
	  });
   
 }

function checkPWD(val){
  var val;
  var upperCase= new RegExp('[A-Z]');
  var lowerCase= new RegExp('[a-z]');
  var numbers = new RegExp('[0-9]');
 
  if(val.match(upperCase) && val.match(lowerCase) &&  val.match(numbers)){
	  $("#passwordErrorMsg").html("")
  }
  else{
	  $("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
  }
}
//////// Enter Number Only/////////
function onlyNumbers(evt){  
	var e = event || evt; // for trans-browser compatibility
	var charCode = e.which || e.keyCode;  
	if (charCode > 31 && (charCode < 48 || charCode > 57) &&  charCode!=43){
		return false;
	}
	return true;
}
///////Phone No. length////
function phoneN(){
	doc1=document.frm1.phone;
	doc2=document.frm1.phone1;
	if(doc1.value!=''){
	   if((isNaN(doc1.value)) || (doc1.value.length !=10)){
		  alert("Enter Valid Mobile No. Mobile No. must be in 10 digit.");
		  doc1.value='';
		  doc1.focus();
		  doc1.select();
	   }
	}
	if(doc2.value!=''){
	   if((isNaN(doc2.value)) || (doc2.value.length !=10)){
		  alert("Enter Valid Mobile No. Mobile No. must be in 10 digit.");
		  doc2.value='';
		  doc2.focus();
		  doc2.select();
	   }
	}
}

  </script>
<body>
<div class="container-fluid">
  <div class="row content">
	<?php 
    include("../includes/leftnav2.php");
    ?>
    <div class="col-sm-9">
      <h2 align="center"><i class="fa fa-users"></i> Add Employee</h2><br/><br/>
      <div class="form-group"  id="page-wrap" style="margin-left:10px;" >
          <form  name="frm1" id="frm1" class="form-horizontal" action="" method="post">
          <div class="form-group">
          	<div class="col-md-6"><label class="col-md-6 control-label">Employee Name <span class="red_small">*</span></label>
              <div class="col-md-6">
                <input name="emp_name" type="text" class="form-control required" required id="emp_name">
              </div>
            </div>
            <div class="col-md-6"><label class="col-md-6 control-label">Region/Circle <span class="red_small">*</span></label>
              <div class="col-md-6">
                 <select name="circle" id="circle" class="form-control selectpicker required" data-live-search="true" required>
                  <option value=""> -- Please Select -- </option>
                  <option value="EAST">EAST</option>
                  <option value="NORTH">NORTH</option>
                  <option value="SOUTH">SOUTH</option>
                  <option value="WEST">WEST</option>
                </select>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="col-md-6"><label class="col-md-6 control-label">State <span class="red_small">*</span></label>
              <div class="col-md-6" id="statediv">
                 <select name="locationstate" id="locationstate" class="form-control selectpicker required" data-live-search="true" required>
                  <option value=''> -- Please Select -- </option>
                
                </select>               
              </div>
            </div>
            <div class="col-md-6"><label class="col-md-6 control-label">City <span class="red_small">*</span></label>
              <div class="col-md-6" id="citydiv">
               <select name="locationcity" id="locationcity" class="form-control selectpicker required" data-live-search="true" required>
               <option value=''> -- Please Select -- </option>
               </select>  
              </div>
            </div>
          </div>
          
          <div class="form-group">
            <div class="col-md-6"><label class="col-md-6 control-label">Company Name <span class="red_small">*</span></label>
              <div class="col-md-6">
               <select id="comp_name" name="comp_name" required data-live-search="true" class="form-control selectpicker required" >
               		<option value="" > -- Please Select -- </option>
                    <?php
						$qr3 = mysqli_query($link1, "SELECT companyid,cname FROM hrms_company_master WHERE  status = '1'  ORDER BY cname ");
						while($row3 = mysqli_fetch_array($qr3)){
					?>
                    <option value="<?=$row3[0]?>" > <?=$row3[1]?> </option>
                    <?php } ?>
               </select>
              </div>
            </div>
            <div class="col-md-6"><label class="col-md-6 control-label">Department Name <span class="red_small">*</span></label>
              <div class="col-md-6">
               <select id="deprt_name" name="deprt_name" required data-live-search="true" class="form-control selectpicker required" >
               		<option value="" > -- Please Select -- </option>
                    <?php
						$qr1 = mysqli_query($link1, "SELECT departmentid,dname FROM hrms_department_master WHERE  status = '1'  ORDER BY dname ");
						while($row1 = mysqli_fetch_array($qr1)){
					?>
                    <option value="<?=$row1[0]?>" > <?=$row1[1]?> </option>
                    <?php } ?>
               </select>
              </div>
            </div>
          </div>
		  <div class="form-group">
            <div class="col-md-6"><label class="col-md-6 control-label">Designation <span class="red_small">*</span></label>
              <div class="col-md-6">
               <select id="desig_name" name="desig_name" required data-live-search="true" class="form-control selectpicker required" >
               		<option value="" > -- Please Select -- </option>
                    <?php
						$qr2 = mysqli_query($link1, "SELECT designationid,designame FROM hrms_designation_master WHERE  status = '1'  ORDER BY designame ");
						while($row2 = mysqli_fetch_array($qr2)){
					?>
                    <option value="<?=$row2[0]?>" > <?=$row2[1]?> </option>
                    <?php } ?>
               </select>
              </div>
            </div>
            <div class="col-md-6"><label class="col-md-6 control-label">Manager </label>
              <div class="col-md-6">
               <select id="mngr_name" name="mngr_name" data-live-search="true" class="form-control selectpicker" >
               		<option value="" > -- Please Select -- </option>
                    <?php
						$qr2 = mysqli_query($link1, "SELECT loginid,empname FROM hrms_employe_master WHERE  status = 'active' and utype = 'MEMP'  ORDER BY empname ");
						while($row2 = mysqli_fetch_array($qr2)){
					?>
                    <option value="<?=$row2[0]?>" > <?=$row2[1]?> </option>
                    <?php } ?>
               </select>
              </div>
            </div>            
          </div>		 
		  <div class="form-group">
            <div class="col-md-6"><label class="col-md-6 control-label">Email <span class="red_small">*</span></label>
              <div class="col-md-6">
                <input name="email" type="email" class="email required form-control" id="email" required onBlur="return checkEmail(this.value,'email');">
              </div>
            </div>
            <div class="col-md-6"><label class="col-md-6 control-label">Mo. Number<span class="red_small">*</span></label>
              <div class="col-md-6">
              	<input name="phone" type="text" class="digits form-control"  id="phone" required maxlength="10" onKeyPress="return onlyNumbers(this.value);" onBlur="return phoneN();">
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="col-md-6"><label class="col-md-6 control-label">Alternate Email </label>
              <div class="col-md-6">
                <input name="email1" type="email" class="email form-control" id="email1" onBlur="return checkEmail(this.value,'email1');">
              </div>
            </div>
            <div class="col-md-6"><label class="col-md-6 control-label">Alternate Mo. Number </label>
              <div class="col-md-6">
              <input name="phone1" type="text" class="digits form-control"  id="phone1"  maxlength="10" onKeyPress="return onlyNumbers(this.value);" onBlur="return phoneN();">
              </div>
            </div>
          </div>
          
          <div class="form-group">
          	  <div class="col-md-6" > 
                  <label class="col-md-6 control-label">DOB <span class="red_small">*</span></label> 
                  <div class="col-md-6 input-append date">
                  		<div style="display:inline-block;float:left; width:100%;">
                            <input type="text" class="form-control span2 required" name="dob"  id="dob" required>
                        </div>
                  </div>    
              </div>  
              <div class="col-md-6" > 
                  <label class="col-md-6 control-label">Joining Date <span class="red_small">*</span></label> 
                  <div class="col-md-6 input-append date">
                  		<div style="display:inline-block;float:left; width:100%;">
                            <input type="text" class="form-control span2 required" name="jd"  id="jd" required>
                        </div>
                  </div>    
              </div>  
          </div>  
          
          <div class="form-group">
            <div class="col-md-6"><label class="col-md-6 control-label">Job Type </label>
              <div class="col-md-6">
                <select name="jobtype" id="jobtype" data-live-search="true" class="form-control selectpicker"  >
                		<option value="" > -- Please Select -- </option>
                        <option value="Permanent" > Permanent </option>
                        <option value="Part Time" > Part Time </option>
                  </select>
              </div>
            </div>
            <div class="col-md-6"><label class="col-md-6 control-label">Employee Type <span class="red_small">*</span></label>
              <div class="col-md-6">
                  <select name="emptype" id="emptype" data-live-search="true" class="form-control selectpicker required" required >
                        <option value="" > -- Please Select -- </option>
                        <option value="EMP" > Employee </option>
                        <option value="MEMP" > Manager </option>
                  </select>
              </div>
            </div>
          </div>
		  
		  		  
          <div class="form-group">
          	<div class="col-md-6"><label class="col-md-6 control-label">Address <span class="red_small">*</span></label>
              <div class="col-md-6">
                <textarea name="address" id="address" class="form-control required addressfield" required onkeypress = " return ( (event.keyCode ? event.keyCode : event.which ? event.which : event.charCode)!= 13);"  onContextMenu="return false" style="resize:vertical"></textarea>
              </div>
            </div>
            <div class="col-md-6"><label class="col-md-6 control-label">Remark </label>
              <div class="col-md-6">
                <textarea name="remark" id="remark" required class="form-control addressfield" onkeypress = " return ( (event.keyCode ? event.keyCode : event.which ? event.which : event.charCode)!= 13);"  onContextMenu="return false" style="resize:vertical"></textarea>
              </div>
            </div>
          </div>
          
          <div class="form-group">
            <div class="col-md-6"><label class="col-md-6 control-label">Status <span class="red_small">*</span></label>
              <div class="col-md-6">
                  <select name="status" id="status" data-live-search="true" class="form-control selectpicker required" required >
                        <option value="active" > Active </option>
                        <option value="deactive" > Deactive </option>
                  </select>
              </div>
            </div>
          </div>
		  
          <br><br>
          
          <div class="form-group">
            <div class="col-md-12" align="center">
              <input type="submit" class="btn btn-primary" name="Submit" id="save" value="Save" title="" <?php if($_POST['Submit']=='Save'){?>disabled<?php }?>>
              <input title="Back" type="button" class="btn btn-primary" value="Back" onClick="window.location.href='employee_master_list.php?<?=$pagenav?>'">
            </div>
          </div>
    </form>
      </div><!--End form group-->
    </div><!--End col-sm-9-->
  </div><!--End row content-->
</div><!--End container fluid-->
<?php
include("../includes/footer.php");
include("../includes/connection_close.php");
?>
</body>
</html>