<?php 

 ob_start();
session_start();

if( !isset($_SESSION['user']) ) {
 header("Location: ../index.php");
 exit;
}

include('../dbconnect.php');
$salarycode = $_GET['salarycode'];


//number of rows
$comnumsql = "SELECT * FROM compensation WHERE salarycode = '$salarycode'";

$comnumresult = mysqli_query($conn, $comnumsql);
 $crow = mysqli_num_rows($comnumresult) ;

$monerowsql = "SELECT * FROM monetary";

$monrowresult = mysqli_query($conn, $monerowsql);
$mrow = mysqli_num_rows($monrowresult);


if ($crow >= $mrow) {
  $butstat = "disabled";

}
$totalrow =  abs($crow - $mrow);


$sql = "SELECT * FROM `salarypackage` WHERE salarycode= '$salarycode'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$level = $row['level'];


if(isset($_POST['savesal'])){
  $updateamount = $_POST['updateamount'];
  $monetaryid = $_POST['monetaryid'];
  $monetary=$_POST['monetary'];
  $amount=$_POST['amount'];







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

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


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

  if( $monetary[$i]!="" && $amount[$i]!="" )
  {
   
   $comsql1 = "SELECT * FROM compensation WHERE salarycode='$salarycode' AND monetaryid='$monetary[$i]'";
   $comsqlres1 = mysqli_query($conn, $comsql1);


}

}


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

  //check update 

if (mysqli_num_rows($vvresult) > 0) 
{
  $alert="<div class='alert alert-danger'>
  <strong style='font-size:12pt;'> Monetary Existed</strong> 
</div>";
   $delsql = "TRUNCATE table tempcomp";
 $delvvresult = mysqli_query($conn, $delsql); 
}
elseif (mysqli_num_rows($comsqlres1) > 0) {
  $alert="<div class='alert alert-danger'>
  <strong style='font-size:12pt;'> Monetary Existed 01</strong> 
</div>";
}

else {
  for($i=0;$i<count($monetary);$i++)
  {
   if( $monetary[$i]!="" && $amount[$i]!="")
   {
    
    $comsql = "INSERT INTO `compensation`(`salarycode`, `monetaryid`, `amount`) 
    VALUES ('$salarycode','$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>";
    } else {
        echo "Error: " . $comsql . "<br>" . mysqli_error($conn);
    }
    
   
   
   }
  }
  for($i=0;$i<count($updateamount);$i++)
 {
  if($updateamount[$i]!="")
  {
   


   $updatesql ="UPDATE compensation SET amount='$updateamount[$i]' WHERE salarycode='$salarycode' AND monetaryid='$monetaryid[$i]' ";
   
   
   if (mysqli_query($conn, $updatesql)) {
    $alert="<div class='alert alert-success'>
    <strong style='font-size:12pt;'>Salary Package Successfully Saved</strong> 
  </div>";
   } else {
       echo "Error: " . $updatesql . "<br>" . mysqli_error($conn);
   }
   
  
  
  }
 }
 $delsql = "TRUNCATE table tempcomp";
 $delvvresult = mysqli_query($conn, $delsql); 

}


}

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

  <head>

    <meta 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>Add Employee</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>
    <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("0000,000,000,000.00", {reverse: true}); </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>



    <nav class="navbar navbar-expand navbar-dark bg-dark static-top">

      <a class="navbar-brand mr-1" href="index.html">Super Admin</a>

      <button class="btn btn-link btn-sm text-white order-1 order-sm-0" id="sidebarToggle" href="#">
        <i class="fas fa-bars"></i>
      </button>

      <!-- Navbar Search -->
    

      <!-- Navbar -->
      <ul class="navbar-nav ml-auto ml-md-0">
       

    </nav>

    <div id="wrapper">

      <!-- 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">
                <a href="viewsalary.php?salarycode=<?php echo $salarycode?>">View Salary </a> 
            </li>
            <li class="breadcrumb-item active"> Update Salary</li>
          </ol>
          <form method="post" id="insert_form">
            <div class="row justify-content-lg-center" style="padding: 10px 100px;">
            
              <div class="col-sm-12 ">
                <?php echo $error.$alert?>
              </div>

          
                <div class="col-sm-12 ">
                    <h3> Update Salary Package </h3> <br>
                </div>
                <div class="col-sm-6 form-group">
                  <label class="control-label">Salary Code </label> <br>
                    <input type="text" class="form-control" name="salarycode" id="salarycode" placeholder="Salary Code" value="<?php echo $salarycode?>" required readonly>
                </div>
                <div class="col-sm-6 form-group">
                  <label class="control-label">Level</label> <br>
                    <input type="text" class="form-control" name="level" id="level" placeholder="Level" value="<?php echo $level?>" required readonly>
                </div>  

                  <?php 
                $sql = "SELECT * FROM compensation 
                JOIN monetary ON compensation.monetaryid = monetary.monetaryid
                WHERE compensation.monetaryid = monetary.monetaryid AND salarycode='$salarycode'";
                $result = mysqli_query($conn, $sql);
              
                    while($row = mysqli_fetch_assoc($result)) {
                        echo' 
                        <div class="col-sm-12 form-group">
                        <label class="control-label">'.$row['name'].'</label> <br>
                        <input type="number" class="money">
                          <input type="number" class="form-control money" name="updateamount[]" id="amount" placeholder="amount" value="'.$row['amount'].'" required >
                          <input type="text" name="monetaryid[]" value="'.$row['monetaryid'].'" hidden>
                      </div>  
                        ';

                    }
                    mysqli_close($conn);
                ?>
              <div class="col-sm-12 form-group">
                <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>
              <div class="col-sm-12 form-group">
          
                            <div class="row justify-content-end">
                                        
                            <input type="submit" name="savesal" class="btn btn-success" name="createemp" value="Save" style="margin-right: 5px;" > 
                      
                            <a href="viewsalary.php?salarycode=<?php echo $salarycode?>" class="btn btn-danger" role="button" style="margin-right: 5px;">Cancel </a>
                            </div>
                       

              </div>



            </div>
        </form>
          <!-- 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">Select "Logout" below if you are ready to end your current session.</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>

    <!-- 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>
        $(document).ready(function(){
        
        $(document).on('click', '.add', function(){
          var html = '';
          html += '<tr>';
          html += '<td><select name="monetary[]" class="form-control item_unit"><option value="">Select Monetary</option><?php echo fill_unit_select_box($connect); ?></select></td>';
          html += '<td><input type="number" name="amount[]" class="form-control item_quantity" /></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 $totalrow ?>";
    

    var count = 0;
 
     function plus(){
       
         
           
         if(count < monrow){
          
           count++;
 
           
         
         }else if(count = monrow) {
           norow.disabled = true;
         }
     }
     function minus(){
       count--;
   
       norow.disabled = false;
      
     }
 
        

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

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



        </script>
</body>

</html>
