<?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 deductions
    ORDER BY deductionname ASC;";

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

    $countAllowances = mysqli_num_rows($resultAllowances);

      if ($countAllowances !== 0) { 

        while ($rowAllowances = mysqli_fetch_array($resultAllowances)) {
          $allowances[$rowAllowances['deductionid']] = $rowAllowances['deductionname'];
        }

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


       }

    // --- ALLOWANCES END HERE

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

  
        $sqlAddEmployeeDeductions = "INSERT INTO employee_deductions (
          employeeid,
          deductionid,
          deductionvalue,
          latest
          ) VALUES ";

          foreach (array_filter($allowances) as $deductionid => $deductionname) {
              $sqlAddEmployeeDeductions = $sqlAddEmployeeDeductions . "(" . $employee_id . "," . $deductionid . "," . $$deductionid . ",1)," ;
            }

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

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

        $employeeUpdate = "User added employee deduction ";

        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!!!";
   }
 
}

?>