<!-- https://stackoverflow.com/questions/3234205/html-form-input-tag-name-element-array-with-javascript 
https://www.digitalocean.com/community/tutorials/how-to-add-javascript-to-html
https://www.encodedna.com/2013/07/dynamically-add-remove-textbox-control-using-jquery.htm
https://www.jqueryscript.net/form/jQuery-Currency-Input-Filed-Mask-Plugin-maskmoney.html
-->
<?php 

include('../dbconnect.php');
ob_start();
session_start();
$user = $_SESSION['user'];
$sqla = "SELECT * FROM account WHERE userid = '$user'";
$resulta = mysqli_query($conn, $sqla);
$rowa  = mysqli_fetch_assoc($resulta);

if( !isset($_SESSION['user']) ) {
 header("Location: ../index.php");
 exit;
}
elseif($rowa['level']=='admin'){
  header("Location: ../accessdenied.php");
}



//RANK AND FILE
$RAFsql = "SELECT * FROM salarypackage WHERE level='Rank and File'";
$RAFresult = mysqli_query($conn, $RAFsql);
$RAFrowcount=mysqli_num_rows($RAFresult);

$RAFcount = $RAFrowcount + 1;

$RAFstrlength = strlen($RAFcount);

if($RAFstrlength = 1){
  $RAFgensal = str_pad($RAFcount, 2, '0', STR_PAD_LEFT);
 
}
else{
  $RAFgensal = $RAFcount;
}
//SUP
$SUPsql = "SELECT * FROM salarypackage WHERE level='Supervisor'";
$SUPresult = mysqli_query($conn, $SUPsql);
$SUProwcount=mysqli_num_rows($SUPresult);

$SUPcount = $SUProwcount + 1;

$SUPstrlength = strlen($SUPcount);

if($SUPstrlength = 1){
  $SUPgensal = str_pad($SUPcount, 2, '0', STR_PAD_LEFT);
 
}
else{
  $SUPgensal = $SUPcount;
}
//MID
$MIDsql = "SELECT * FROM salarypackage WHERE level='Middle Management'";
$MIDresult = mysqli_query($conn, $MIDsql);
$MIDrowcount=mysqli_num_rows($MIDresult);

$MIDcount = $MIDrowcount + 1;

$MIDstrlength = strlen($MIDcount);

if($MIDstrlength = 1){
  $MIDgensal = str_pad($MIDcount, 2, '0', STR_PAD_LEFT);
 
}
else{
  $MIDgensal = $MIDcount;
}
//EXE
$EXEsql = "SELECT * FROM salarypackage WHERE level='Executive'";
$EXEresult = mysqli_query($conn, $EXEsql);
$EXErowcount=mysqli_num_rows($EXEresult);

$EXEcount = $EXErowcount + 1;

$EXEstrlength = strlen($EXEcount);

if($MIDstrlength = 1){
  $EXEgensal = str_pad($EXEcount, 2, '0', STR_PAD_LEFT);
 
}
else{
  $EXEgensal = $EXEcount;
}


$monesql = "SELECT * FROM monetary";
$moneresult = mysqli_query($conn, $monesql);
$monerow = mysqli_fetch_assoc($moneresult);
$monecount = mysqli_num_rows($moneresult);

$connect = new PDO("mysql:host=192.169.232.59;dbname=atvinter_dbproject", "atvinter_atv19", "KoDq(=tt6d}(");

function fill_unit_select_box($connect)
{ 
 $output = '';
 $query = "SELECT * FROM monetary";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["monetaryid"].'">'.$row["name"].'</option> ';
 }
 return $output;
}

if(isset($_POST['submit_row']))
{

 
 $salcode =$_POST['salarycode'];
 $monetary= $_POST['monetary'];
 $amount= $_POST['amount'];
 $level =$_POST['level'];
 $description =$_POST['description'];


 
 
 /*
  $b = 0;
  $a = 0;

 for($i == 0;$i<count($monetary); $i++)
 {
  $a = $monetary[$i];

  for($j == $i; $j<count($monetary); $j++)
  {
    if($a == $monetary[$j])
    { $b++;}
    echo $b;
  }
  
 }
*/
if(empty($monetary)){

  $alert="<div class='alert alert-danger'>
  <strong style='font-size:12pt;'>Please Add Items for Monetary and Amount</strong> 
</div>";
 }else if(empty($amount)){
  $alert="<div class='alert alert-danger'>
  <strong style='font-size:12pt;'>Please Add Amount</strong> 
</div>";
 }
else{

  for($i=0;$i<count($monetary);$i++)
 {
  if( $monetary[$i]!="" && $amount[$i]!="")
  {
   
   $comsql = "INSERT INTO `tempcomp`(`salarycode`, `monetaryid`, `amount`) 
   VALUES ('$salcode','$monetary[$i]','$amount[$i]')";
   $comsqlres = mysqli_query($conn, $comsql);
   
       
  }
}




  $vvsql = "SELECT * FROM tempcomp WHERE monetaryid IN ( SELECT monetaryid FROM tempcomp GROUP BY monetaryid HAVING count(*) > 1 )";
  $vvresult = mysqli_query($conn, $vvsql);




if (mysqli_num_rows($vvresult) > 0) 
{
  $alert="<div class='alert alert-danger'>
  <strong style='font-size:12pt;'>Duplicate Entry Cannot Add</strong> 
</div>";
   $delsql = "TRUNCATE table tempcomp";
 $delvvresult = mysqli_query($conn, $delsql); 
}
else {
        $salsql= "INSERT INTO `salarypackage`(`salarycode`, `level`, `description`) VALUES ('$salcode','$level','$description')";
        $salsqlresult = mysqli_query($conn, $salsql);  
 

          for($i=0;$i<count($monetary);$i++)
          {
            if( $monetary[$i]!="" && $amount[$i]!="")
            {
   
                $comsql = "INSERT INTO `compensation`(`salarycode`, `monetaryid`, `amount`) 
                VALUES ('$salcode','$monetary[$i]','$amount[$i]')";
                
                
                if (mysqli_query($conn, $comsql))
                 {
                  $alert="<div class='alert alert-success'>
                  <strong style='font-size:12pt;'>Salary Package Successfully Added</strong> 
                  </div>";
                  header('location: salarypackage.php');
                 } 
                 else 
                 {
                   echo "Error: " . $comsql . "<br>" . mysqli_error($conn);
                 }
              }     
            }

            $delsql = "TRUNCATE table tempcomp";
            $delvvresult = mysqli_query($conn, $delsql);  
       }




}



}//LAST BRACKER


  

?>
<!DOCTYPE html>
<html lang="en">

  <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Super Admin | Add Salary Package</title>

    <!-- Bootstrap core CSS-->
    <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">

    <!-- Page level plugin CSS-->
    <link href="../vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet">

    <!-- Custom styles for this template-->
        <link href="../css/sb-admin.css" rel="stylesheet">
    <link href="../css/style.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="icon" href="../images/logo.jpg" type="image/gif" sizes="16x16">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.13.4/jquery.mask.min.js"></script>
<script src="../js/jquery.maskMoney.js" type="text/javascript"></script>

    <script>
      $('.money').mask("000,000,000,000.00", {reverse: true});
      
    function salcode(){
                          var level = document.getElementById("level").value;
                          var lvl;
                          var RAF= "<?php echo $RAFgensal; ?>";
                          var SUP= "<?php echo $SUPgensal; ?>";
                          var MID= "<?php echo $MIDgensal; ?>";
                          var EXE= "<?php echo $EXEgensal; ?>";
                          switch(level){
                            case "Rank and File": 
                                  lvl = "RAF";
                                  document.getElementById("salarycode").value = "ATV"+lvl+"-"+RAF;

                                  break;

                            case "Supervisor": 
                                  lvl = "SUP";
                                  document.getElementById("salarycode").value = "ATV"+lvl+"-"+SUP;
                                  break;

                            case "Middle Management": 
                                  lvl = "MID";
                                  document.getElementById("salarycode").value = "ATV"+lvl+"-"+MID;
                                  break;
                          
                            
                            case "Executive": 
                                  lvl = "EXE";
                                  document.getElementById("salarycode").value = "ATV"+lvl+"-"+EXE;
                                  break;

                          }
          
                   
                        }
    </script>


  </head>

   <body id="page-top">
	<div id="preloader">
   		<img src="../images/loaderS.gif" alt="processing..." height="150px" width="200px"/>
	</div>

  <div id="pageloader">
   <img src="../images/loaderS.gif" alt="processing..." height="150px" width="200px"/>
</div>


    <?php include('uppernav.php')?>


      <!-- Sidebar -->
      
      <?php 
      $salarypack = "active";
      $admintools = "active";
      include('sidebar.php');
       ?>
      <div id="content-wrapper">

        <div class="container-fluid">

          <!-- Breadcrumbs-->
          <ol class="breadcrumb">
            <li class="breadcrumb-item">
              <a href="salarypackage.php">Salary Package</a>
            </li>
            <li class="breadcrumb-item active">Add Salary Package</li>
          </ol>
          <form method="post" id="insert_form">
              <div class="row justify-content-lg-center" style="padding: 10px 100px;">
                <?php echo $error.$alert?>

                      <div class="col-sm-12 form-group required">
                          <h4> Add Salary Package</h4>
                              <label class="control-label">Level</label> <br>
                              <select id="level" name="level" class="form-control" onchange="salcode()"  required>
                              <option value="" disabled selected> ---</option>
                                <option value="Rank and File"> Rank and File </option>
                                <option value="Supervisor">Supervisor </option>
                                <option value="Middle Management">Middle Management </option>
                                <option value="Executive">Executive</option>
                                    
                              </select>
                      </div>
              
                      <div class="col-sm-6 form-group required" >
                        <label class="control-label">Salary Code</label> <br>
                        <input type="text" class="form-control" name="salarycode" id="salarycode" placeholder="Salary Code" value="<?php echo $salcode?>"  required readonly> 
 
                        <br />
                      </div>
                      <div class="col-sm-6 form-group required" >
                        <label class="control-label">Description</label> <br>
                        <input type="text" class="form-control" name="description" id="salarycode" placeholder="Description" value="<?php echo $description?>"  required> 
 
                        <br />
                      </div>

            <div class="container">

            <br />
            
              <div class="table-repsonsive">
              <span id="error"></span>
              <table class="table table-bordered" id="item_table">
                <tr>

                <th>Monetary</th>
                <th>Amount</th>
                <th><button type="button" name="add" class="btn btn-success btn-sm add" id="norow" onclick="plus()">+</button></th>
                </tr>
              </table>
           
              </div>
 
                        <div class="col-sm-12 form-group required">
                            <div class="row justify-content-end">


                           <button type="button" class="btn btn-success" data-toggle="modal" onclick="view()" data-target="#confirm"><i class="fa fa-check"></i> Submit</button>  &nbsp
                        
                          
                      
                            <a href="salarypackage.php" class="btn btn-danger" role="button" style="margin-right: 5px;"><i class="fa fa-close"></i> Cancel </a>
                         
                            </div>
                        </div>
                     
                <!-- Modal -->
                <div class="modal fade" id="confirm" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" data-backdrop="static">
                  <div class="modal-dialog modal-dialog-centered" role="document">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title" id="modaltitle">Are you sure you want to add </h5> &nbsp <h5 class="modal-title" id="sc"></h5> <h5 id="ques">?</h5>
                     
                        <button class="close" type="button" onclick="dup()" data-dismiss="modal" aria-label="Close">
                          <span aria-hidden="true">×</span>
                        </button>
                        
                      </div>
                      <div class="modal-body" id="modbod">
                      <center><h5 id="lev"></h5> </center>
                        <table class="table table-hover" style="border:none">
                        <tr>
                          <td> Monetary </td>
                          <td> Amount </td>
                        </tr>
                        
                        <tr  id="frow">
                        <td> <p id="mone"> </p> </td>
                         <td> <p id="amo"> </p> </td>
                        
                        </tr>
                        <tr>
                         <td> <p id="mont"> </p> </td>
                         <td> <p id="amnt"> </p> </td>
                      
                        </tr>
                        
                        
                        </table>
                      
                      </div>
                      <div class="modal-footer">
                      <button type="submit" id="yesadd" name="submit_row" class="btn btn-success" style="margin-right: 5px;" ><i class="fa fa-check"></i> Yes </button>
                        <button class="btn btn-danger" id="noadd" type="button"  onclick="dup()" data-dismiss="modal"><i class="fa fa-close"></i> No</button>
                       
                      </div>
                    </div>
                  </div>
                </div>
          </div>
              <!-- End of modal-->
          </form>
        </div>
      </div>
          
                <script language="javascript" type="text/javascript">
            $(document).ready(function(){
            $("form").on("submit", function(){
                $("#pageloader").fadeIn();
            });//submit

             $('#preloader').fadeOut();
            });//document ready



        </script>
</body>
        </html>

        <script>
        $(document).ready(function(){
        
        $(document).on('click', '.add', function(){
          var html = '';
          html += '<tr>';
          html += '<td><select name="monetary[]" id="mon" class="form-control item_unit" required><option value="" selected disabled>Select Monetary</option><?php echo fill_unit_select_box($connect); ?></select></td>';
          html += '<td><div class="input-group"> <div class="input-group-prepend" style="width: 100%;"> <span class="input-group-text" style="background-color: white; border-right:none;">₱</span> <input type="text" name="amount[]" id="amn"    class="form-control item_quantity money" placeholder="Amount" style="border-left:none;" required/></div> </div></td>';
          html += '<td><button type="button" name="remove" id="minus" onclick="minus()" class="btn btn-danger btn-sm remove">-</button></td></tr>';
          $('#item_table').append(html);
        });
        
        $(document).on('click', '.remove', function(){
          $(this).closest('tr').remove();
          minus();
        });
        
       
        
        });
        
       

        var button = document.getElementById("norow");
        var minusb = document.getElementById("minus");
        var monrow = "<?php echo $monecount ?>";
    

   var count = 0;

    function plus(){
      
        
          
        if(count < monrow){
         
          count++;

          
        
        }else if(count = monrow) {
          norow.disabled = true;
        }
    }
    function minus(){
      count--;
  
      norow.disabled = false;
     
    }
    var a;
    var b;
    function view(){
      var myform = document.forms.insert_form;
    var x = myform.elements['monetary[]'];
    var y = myform.elements['amount[]'];
    var p = "₱";
    var mn;


    
    var level = myform.elements['level'].value;
      var sal = document.getElementById('salarycode').value;
      var lvl = document.getElementById('level').value;
      
      document.getElementById('sc').innerHTML = sal;
      document.getElementById('lev').innerHTML = lvl; 
      document.getElementById('modaltitle').innerHTML ="Are you sure you want to add";
      document.getElementById('modbod').style.display ="block";
      document.getElementById('ques').innerHTML = "?";


      if(level == ""){
      document.getElementById('modaltitle').innerHTML ="<i class='fas fa-exclamation-triangle text-danger' style='font-size: 30px;'></i> &nbsp Please fill out salary level field";
      document.getElementById('amnt').innerHTML ="";
      document.getElementById('sc').innerHTML = "";
      document.getElementById('lev').innerHTML = "";
      document.getElementById('ques').innerHTML = "";
      document.getElementById('modbod').style.display ="none";
      document.getElementById('yesadd').style.display = "none"; 
      document.getElementById('noadd').style.display = "none"; 
      
      }else{
        document.getElementById('modbod').style.display ="block";
      document.getElementById('yesadd').style.display = "block"; 
      document.getElementById('noadd').style.display = "block"; 

      }
  
      var montxt = document.getElementById("mon");
      var z = montxt.options[montxt.selectedIndex].text;
  

      document.getElementById('mone').innerHTML = z;
      document.getElementById('amo').innerHTML = p + y.value;
      document.getElementById('frow').style.display = "";
      
      var total;
    for (var i = 0 ; i < monrow; i++){

          a =  x[i];
          b = y[i];
     
  
       mn = a.options[a.selectedIndex].text; 
 
 
    
      
      document.getElementById('mont').innerHTML += mn + "<br>";
      document.getElementById('amnt').innerHTML += p + " " +  b.value + "<br>";
      document.getElementById('mone').innerHTML = "";
      document.getElementById('amo').innerHTML = "";
      document.getElementById('frow').style.display = "none";
    

    
    }
   

    
    

     

     
      /*
    if(x.length = x.length){
    mnz = x.options[x.selectedIndex].text; 
        document.getElementById('amnt').innerHTML =y.value;
        document.getElementById('mont').innerHTML =mnz;
        alert("1");
    }
     *//*
     if(x.length = x.length){
      document.getElementById('mont').innerHTML = mn + "<br>";
      document.getElementById('amnt').innerHTML = p + b.value + "<br>";
  
     }
    
*/





  

    

    

      
    }
    function dup(){
      document.getElementById('mont').innerHTML = " ";
      document.getElementById('amnt').innerHTML = " ";
      document.getElementById('mone').innerHTML = " ";
      document.getElementById('amo').innerHTML = " ";

    }




       
        

 





  

        

        

        </script>
                              
        
                    
                    </div>


          <!-- Icon Cards-->
      
        <!-- /.container-fluid -->

        <!-- Sticky Footer -->
<!--  -->

      </div>
      <!-- /.content-wrapper -->

    </div>
    <!-- /#wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
      <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
            <button class="close" type="button" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">×</span>
            </button>
          </div>
          <div class="modal-body">
           
          </div>
          <div class="modal-footer">
            <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
            <a class="btn btn-primary" href="login.html">Logout</a>
          </div>
        </div>
      </div>
    </div>

    <?php 
       mysqli_close($conn);
    
    ?>

    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Page level plugin JavaScript-->
    <script src="../vendor/chart.js/Chart.min.js"></script>
    <script src="../vendor/datatables/jquery.dataTables.js"></script>
    <script src="../vendor/datatables/dataTables.bootstrap4.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin.min.js"></script>

    <!-- Demo scripts for this page-->
    <script src="../js/demo/datatables-demo.js"></script>
    <script src="../js/demo/chart-area-demo.js"></script>

          <script language="javascript" type="text/javascript">
            $(document).ready(function(){
            $("form").on("submit", function(){
                $("#pageloader").fadeIn();
            });//submit

             $('#preloader').fadeOut();
            });//document ready



        </script>
</body>

</html>
