<?php
   include('session.php');
   include('connect.php');
   include('logging.php');

// start role specific 
$user_role = $_SESSION['role'];

if ($_SERVER["REQUEST_METHOD"] == "POST") {

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


    // --- ALLOWANCES START HERE

    $allowances = array();

    $sqlAllowances = "SELECT *
    FROM benefits
    ORDER BY benefitname ASC;";

    $resultAllowances = mysqli_query($db,$sqlAllowances);

    $countAllowances = mysqli_num_rows($resultAllowances);

      if ($countAllowances !== 0) { 

        while ($rowAllowances = mysqli_fetch_array($resultAllowances)) {
          $allowances[$rowAllowances['benefitid']] = $rowAllowances['benefitname'];
        }

        foreach (array_filter($allowances) as $benefitid => $benefitname) {
          $$benefitid = mysqli_real_escape_string($db,$_POST[$benefitid]);
        }


       }

    // --- ALLOWANCES END HERE

    $employee_id = mysqli_real_escape_string($db,$_POST['employee_id']);

  
        $sqlAddEmployeeBenefits = "INSERT INTO employee_benefits (
          employeeid,
          benefitid,
          benefitvalue,
          latest
          ) VALUES ";

          foreach (array_filter($allowances) as $benefitid => $benefitname) {
              $sqlAddEmployeeBenefits = $sqlAddEmployeeBenefits . "(" . $employee_id . "," . $benefitid . "," . $$benefitid . ",1)," ;
            }

          $sqlAddEmployeeBenefits = substr($sqlAddEmployeeBenefits, 0, -1) . ";";

      if(mysqli_query($db, $sqlAddEmployeeBenefits)) {

        $employeeUpdate = "User updated employee ";

        logEvent($db,"Employee updated",$employeeUpdate,$last_id);
        
        header("location: viewEmployee.php?employeeID=$employee_id");
        } else {
           echo "Error: " . mysqli_error($db);
      }

    } else {
    echo "Employee not selected!!!";
   }
 
}

?>