<?php
   include('session.php');
   include('header1.php');
   include('ietpartial.php');
   include('calculations.php');

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

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

  $payrollid = $_GET['payrollID'];
  $payrollStatus = "";

  $sqlViewPayroll = "SELECT *
  FROM periods
  WHERE periodid = $payrollid;";

  $resultPayroll = mysqli_query($db,$sqlViewPayroll);

  $countPayroll = mysqli_num_rows($resultPayroll);

  if(isset($_GET['updated'])) {

    $updated = $_GET['updated'];

  }



    $sqlView = "SELECT 
          employees.employeeid AS employeeid,
          employees.employeename AS employeename,
          employees.employeesurname AS employeesurname,
          employees.employee_edf_amount AS edf_amount,
          employees.edf_months_value AS edf_months_value,
          employees.employee_paye_rate AS payeRate,
          employees.employee_join_date AS joinDate,
          employees.employee_termination_date AS terminationDate,
          employees.employee_citizen_boolean AS citizenboolean,
          employees.employee_pension_boolean AS pensionboolean,
          departments.departmentname AS department,
          positions.positionname AS position,
          salaries.salaryvalue AS basic,
          travellings.travellingvalue AS travelling,
          employees.employee_carbenefit AS carbenefitlinkid
          FROM employees
          LEFT JOIN employee_job
          ON employees.employeeid = employee_job.employeeid
          LEFT JOIN departments
          ON employee_job.departmentid = departments.departmentid
          LEFT JOIN positions
          ON employee_job.positionid = positions.positionid
          LEFT JOIN salaries
          ON employees.employeeid = salaries.employeeid
          LEFT JOIN travellings
          ON employees.employeeid = travellings.employeeid
          WHERE companyid = $companyID;";
  
    $result = mysqli_query($db,$sqlView);

    $count = mysqli_num_rows($result);

    $numberOfDaysInMonth = 0;

  echo "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"></script>";



    echo "<main role=\"main\" class=\"col-md-9 ml-sm-auto col-lg-10 px-4\">";

    echo "<div class=\"d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom\">";

    if ($count !== 0) { // COUNT EMPLOYEES START HERE
      $periodSelectID = 0;
      while ($rowperiods = mysqli_fetch_array($resultPayroll)) { 
        $periodSelectID = $rowperiods['periodid'];
          echo "<h1 class=\"h2\">New Payroll - " . $rowperiods['startDate'] . " - " . $rowperiods['endDate'] . " (" . $rowperiods['periodName'] . ") ";
          
          $payrollStart = $rowperiods['startDate'];
          $payrollEnd = $rowperiods['endDate'];
          
          if ($rowperiods['status'] == '1') {
            echo "<i>(Open)</i>";
            $payrollStatus = "open";
          } else if ($rowperiods['status'] == '2') {
            echo "<i>(Closed)</i>";
            $payrollStatus = "closed";
          }
          echo "</h1>";
          $numberOfDaysInMonth = $rowperiods['workingDays'];
      }

      $payrollDate = explode ("-", $payrollStart);
      echo $payrollDate[1];
      $booleanDecember = 0;
      if ($payrollDate[1] == '12') {
        $booleanDecember = 1;
      }

      //echo $payrollEnd;

      $booleanBonusExists = 0;
      if ($booleanDecember == 1) { //CHECK IF BONUS EXISTS
        $checkBonusForDec = "SELECT * FROM periods WHERE endDate = '$payrollEnd' AND bonusBoolean = '1' AND companyid = '$companyID';";

        $resultCheckBonus = mysqli_query($db,$checkBonusForDec);

        $resultCheckBonusCount = mysqli_num_rows($resultCheckBonus);
        $bonusid = 0;
        if ($resultCheckBonusCount != 0) {
          $booleanBonusExists = 1;
          while ($rowbonuscheck = mysqli_fetch_array($resultCheckBonus)) {
            $bonusid = $rowbonuscheck['periodid'];
          } 
        }
        //echo "Bonus: " . $booleanBonusExists;
        
        
      } 

      //echo $bonusid;
      $employeeBonusArray = array();

      if ($booleanBonusExists == 1 && $bonusid > 0) {
        $sqlGetBonusData = "SELECT * FROM bonuspayouts WHERE bonusPayrollid = $bonusid;";

        $resultGetBonusData = mysqli_query($db,$sqlGetBonusData);

        $resultGetBonusDateCount = mysqli_num_rows($resultGetBonusData);
        
        if ($resultGetBonusDateCount != 0) {
          
          while ($rowbonusdata = mysqli_fetch_array($resultGetBonusData)) {
            //echo $rowbonusdata['employeeid'];

            if ($rowbonusdata['finalBonusValue'] == 0 || $rowbonusdata['finalBonusValue'] == null) {
              $netBonus = $rowbonusdata['bonusAmount'] - $rowbonusdata['bonusPayeAmount'] - $rowbonusdata['employeeCSG'];

              $employeeBonusArray[$rowbonusdata['employeeid']] = array($rowbonusdata['bonusAmount'],$rowbonusdata['bonusPayeAmount'],$rowbonusdata['employeeCSG'],$netBonus);
            
            } else {
              $netBonus = $rowbonusdata['finalBonusValue'] - $rowbonusdata['bonusPayeAmount'] - $rowbonusdata['employeeCSG'];

              $employeeBonusArray[$rowbonusdata['employeeid']] = array($rowbonusdata['finalBonusValue'],$rowbonusdata['bonusPayeAmount'],$rowbonusdata['employeeCSG'],$netBonus);
            
            }

            

            
          } 

          
          //echo '<pre>'; print_r($employeeBonusArray); echo '</pre>';
        }

      }
      


      echo "<div class=\"btn-toolbar mb-2 mb-md-0\">"; // TOOLBAR STARTS HERE

      if ($payrollStatus == "open") {

                echo "<div class=\"btn-group mr-2\">";
        echo "<a href=\"closePeriod.php?payrollID=" . $periodSelectID . "\" class=\"btn btn-sm btn-outline-secondary\" role=\"button\">Close Period</a>";
      
        if ($booleanBonusExists == 1) {
          //echo "<b>Bonus Exists</b>";
        } 
      
        echo "</div>";
} else if ($payrollStatus == "closed") {

                echo "<div class=\"btn-group mr-2\">";
        echo "<a onclick=\"javascript: return confirm('Please confirm re-opening of period');\" href=\"openPeriod.php?payrollID=" . $periodSelectID . "\" class=\"btn btn-sm btn-outline-secondary\" role=\"button\">Re-Open Period</a>";
      echo "</div>";
}
          echo "</div>";

    echo "</div>";

    // --- 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'];
        }

       }

    // --- ALLOWANCES END HERE

    // --- DEDUCTIONS START HERE

    $deductions1 = array();

    $sqlDeductions1 = "SELECT *
    FROM deductions
    ORDER BY deductionname ASC;";

    $resultDeductions = mysqli_query($db,$sqlDeductions1);

    $countDeductions = mysqli_num_rows($resultAllowances);

      if ($countDeductions !== 0) { 

        while ($rowdDeductions = mysqli_fetch_array($resultDeductions)) {
          $deductions1[$rowdDeductions['deductionid']] = $rowdDeductions['deductionname'];
        }

       }

    // --- DEDUCTIONS END HERE

    // TABLE STARTS HERE

       echo "<style>
       table {background-color:white;}
       
       #myInput {
        background-image: url('/css/searchicon.png'); /* Add a search icon to input */
        background-position: 10px 12px; /* Position the search icon */
        background-repeat: no-repeat; /* Do not repeat the icon image */
        width: 100%; /* Full-width */
        font-size: 16px; /* Increase font-size */
        padding: 12px 20px 12px 40px; /* Add some padding */
        border: 1px solid #ddd; /* Add a grey border */
        margin-bottom: 12px; /* Add some space below the input */
      }

       .tableheader { top:50px;position: sticky;background-color:white;}</style>";

      /*
      if ($booleanDecember == 1) {
        echo "December";
      }
      */

  echo "<input type=\"text\" id=\"myInput\" onkeyup=\"myFunction()\" placeholder=\"Search for employee..\">";
  echo "<table class = \"table\" id = \"myTable\">";
  echo "<thead>";
  echo "<tr class=\"tableheader\">";
  echo "<th>Employee Name</th>";
  echo "<th>Job</th>"; 
  echo "<th>Sick Leaves Taken</th>";
  echo "<th>Sick Leaves Balance</th>";
  echo "<th>Local Leaves Taken</th>";
  echo "<th>Local Leaves Balance</th>";

  echo "<th>Working Days</th>";
  
  echo "<th>Presence</th>";
  echo "<th>UnAuth Absences (Days)</th>";

  
  echo "<th>Basic Salary</th>";
  
  echo "<th>Travelling Adjust</th>";
  echo "<th>Bus Fare</th>";
  


  foreach (array_filter($allowances) as $benefitid => $benefitname) {
    if($benefitname == "Taxable Car Allowance" || $benefitname == "Excempt Car Allowance") {

    } else {
      echo "<th>" . $benefitname . "</th>";
    }
    
  }

  echo "<th>IET</th>";
  echo "<th>Car Allowance</th>";
  echo "<th>Special Bonus</th>";
  echo "<th>Taxable Allowance</th>";
  echo "<th>Non-Taxable Allowance</th>";
  echo "<th>Commission</th>";
  echo "<th>Overtime</th>";
  //echo "<th><i>Car Benefit</i></th>";

  if ($booleanDecember == 1) {
    echo "<th><i>EOY Bonus</i></th>";
  }  

  echo "<th>Total Package</th>";
  echo "<th>UnAuth Abs Deduct</th>";
  echo "<th>NSF</th>";
  echo "<th>PAYE</th>";

  if ($booleanDecember == 1) {
    echo "<th><i>PAYE on Bonus</i></th>";
  }  

  echo "<th>Solidarity Levy</th>";

  if ($booleanDecember == 1) {
    echo "<th><i>CSG on Bonus</i></th>";
  } 

  echo "<th>Employee CSG</th>";

  foreach (array_filter($deductions1) as $deductionid => $deductionname) {
    echo "<th>" . $deductionname . "</th>";
  }
  echo "<th>One-Off Deductions</th>";
  
  

  if ($booleanDecember == 1) {
    echo "<th><i>EOY Paid</i></th>";
  }  


  echo "<th>Total Deductions</th>";
  echo "<th>Net Salary</th>";
  echo "<th>Employer CSG</th>";
  echo "<th>Employer NSF</th>";
  echo "<th>Employer LEVY</th>";
  echo "<th></th>";
  echo "<th>Employer PRGF</th>";
  echo "<th>Employee CSG</th>";
  echo "<th>Employee NSF</th>";
  echo "<th>Total CSG</th>";
  echo "<th>Total NSF</th>";
  echo "<th>Total LEVY</th>";
  echo "<th>Total MRA</th>";

  if ($payrollStatus == "open") {
           // echo "<td>Check</td>";
      } else if ($payrollStatus == "closed") {}

  echo "</tr>";
  echo "</thead>";
  echo "<tbody>";


  $employeearray = array();

  while ($rowemployee = mysqli_fetch_array($result)) { // FETCHING EMPLOYEE DATA START

    

    echo "<tr id = \"employeerow" . $rowemployee['employeeid'] . "\" >";
    // check employee start date and end date against payroll data
    $employeeJoin = $rowemployee['joinDate'];
    $employeeTermination = $rowemployee['terminationDate'];

    echo "<input type=\"hidden\" id = \"joindate" . $rowemployee['employeeid'] . "\" value = \"" . $employeeJoin . "\" >";
    echo "<input type=\"hidden\" id = \"terminationdate" . $rowemployee['employeeid'] . "\" value = \"" . $employeeTermination . "\" >";
    echo "<input type=\"hidden\" id = \"payrollstart" . $rowemployee['employeeid'] . "\" value = \"" . $payrollStart . "\" >";
    echo "<input type=\"hidden\" id = \"payrollend" . $rowemployee['employeeid'] . "\" value = \"" . $payrollEnd . "\" >";

    if (($employeeTermination == NULL || $employeeTermination == "0000-00-00")) {
      if ($employeeJoin > $payrollEnd) {
        continue;
      } 
    } else {
      if ($employeeTermination < $payrollStart) {
        continue;
      } 
    } 
    
    if ($employeeJoin > $payrollEnd) {
      continue;
    }

    // end check

//
    $sqlCheckForSavedPayrollData = "
    SELECT * FROM payrollbasicdetails
    WHERE payrollid = '$payrollid' AND employeeid = '" . $rowemployee['employeeid'] . "';";

    $resultCheckSavedPayrollData = mysqli_query($db,$sqlCheckForSavedPayrollData);

    $count101Check = mysqli_num_rows($resultCheckSavedPayrollData);

    if ($count101Check !== 0) { 
      $rowSavedPayrollData = mysqli_fetch_assoc($resultCheckSavedPayrollData); 
    }

             

//

    echo "<form id=\"payrollform\" name=\"form\">";
    
    array_push($employeearray,$rowemployee['employeeid']);
    echo "<input type=\"hidden\" id = \"payrollid" . $rowemployee['employeeid'] . "\" value = \"" . $periodSelectID . "\" >";
    echo "<input type=\"hidden\" id = \"employeeid" . $rowemployee['employeeid'] . "\" value = \"" . $rowemployee['employeeid'] . "\" >";
    echo "<style>.col-emp-name { left:200px;position: sticky;background-color:white;z-index:100;}</style>";
    echo "<td class=\"col-emp-name\" scope = \"row\">" . $rowemployee['employeesurname'] . ", " . $rowemployee['employeename'];
    if ($count101Check !== 0) { 
      echo "<b>*</b>";
    }
    echo "</td>";
    echo "<td>" . $rowemployee['position'] . ", " . $rowemployee['department'] . "</td>";

    if ($count101Check !== 0) {
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['s_taken'] . " id = \"sickleavestaken" . $rowemployee['employeeid'] . "\" ></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\" id = \"sickleavestaken" . $rowemployee['employeeid'] . "\" ></td>";
    }

    if ($count101Check !== 0) {
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['s_balance'] . " id = \"sickleavesbalance" . $rowemployee['employeeid'] . "\" ></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\" id = \"sickleavesbalance" . $rowemployee['employeeid'] . "\" ></td>";   
    }

    if ($count101Check !== 0) {
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['l_taken'] . " id = \"localleavestaken" . $rowemployee['employeeid'] . "\" ></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\" id = \"localleavestaken" . $rowemployee['employeeid'] . "\" ></td>";
    }

    if ($count101Check !== 0) {
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['l_balance'] . " id = \"localleavesbalance" . $rowemployee['employeeid'] . "\" ></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\" id = \"localleavesbalance" . $rowemployee['employeeid'] . "\" ></td>";
    }


    // working days starts here
    if ($count101Check !== 0) {

      if ($rowSavedPayrollData['WorkingDaysValue'] == 0) {
        echo "<td><input type = \"number\" style=\"background:#FCCC85;\" value = ". $numberOfDaysInMonth . " id = \"workingDaysValue" . $rowemployee['employeeid'] . "\" ></td>";
      } else {
        echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = ". $rowSavedPayrollData['WorkingDaysValue'] . " id = \"workingDaysValue" . $rowemployee['employeeid'] . "\" ></td>";
      
      }
    
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = ". $numberOfDaysInMonth . " id = \"workingDaysValue" . $rowemployee['employeeid'] . "\" ></td>";
    }
    // working days ends here

    
    // presence starts here
    if ($count101Check !== 0) {

      if ($rowSavedPayrollData['numberWrkDays'] == 0) {
        echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = ". $numberOfDaysInMonth . " id = \"numWrkDays" . $rowemployee['employeeid'] . "\" ></td>";
      } else {
        echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = ". $rowSavedPayrollData['numberWrkDays'] . " id = \"numWrkDays" . $rowemployee['employeeid'] . "\" ></td>";
      
      }
    
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = ". $numberOfDaysInMonth . " id = \"numWrkDays" . $rowemployee['employeeid'] . "\" ></td>";
    }
    // presence ends here


    // unauth absence days starts here
    if ($count101Check !== 0) { 
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['absencesInput'] . " id = \"absencesInput" . $rowemployee['employeeid'] . "\" ></td>";

      //echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['absencesValue'] . " id = \"absencesValue" . $rowemployee['employeeid'] . "\" readonly=\"readonly\"></td>";
    } else {

      echo "<td><input type=\"number\" name=\"absences\" style=\"background:#FCEC85;\" value = \"0\" id=\"absencesInput" . $rowemployee['employeeid'] . "\"></td>"; //Absences
    //echo "<td><input type=\"number\" name=\"absencesValue\" id=\"absencesValue" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";
    }
    // unauth absence days ends here



    
    //echo "<td><input type = \"number\" value = ". $numberOfDaysInMonth . " id = \"numWrkDays" . $rowemployee['employeeid'] . "\" ></td>";

    echo "<td><input type = \"number\" value = ". $rowemployee['basic'] . " id = \"basicSal" . $rowemployee['employeeid'] . "\"  readonly=\"readonly\"></td>";
    

    if ($count101Check !== 0) { 
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['travellingAdjust'] . " id = \"travellingAdjust" . $rowemployee['employeeid'] . "\"></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\" id = \"travellingAdjust" . $rowemployee['employeeid'] . "\"></td>";
    }

    if ($count101Check !== 0) {
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = \"" . $rowSavedPayrollData['travellingAmt'] . "\" id = \"travellingAmt" . $rowemployee['employeeid'] . "\" ></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\" id = \"travellingAmt" . $rowemployee['employeeid'] . "\" ></td>";
    }

    echo "<input type = \"hidden\" value = " . $rowemployee['travelling'] . " style=\"background:#FCEC85;\" id = \"employeeTravelling" . $rowemployee['employeeid'] . "\">";

    //echo "<td><input type = \"number\" value = \"0\" id = \"travellingAmt" . $rowemployee['employeeid'] . "\" ></td>";

    /*
    if ($rowemployee['travelling'] == 0) {
      echo "<td><input type = \"number\" value = \"0\" id = \"travellingAmt" . $rowemployee['employeeid'] . "\" ></td>";
    } else {
      //$busFareForTheMonth = $rowemployee['travelling'] * $numberOfDaysInMonth;
      echo "<td><input type = \"number\" value = '0' id = \"travellingAmt" . $rowemployee['employeeid'] . "\"  readonly=\"readonly\" ></td>";
    }
    */

    //-- benefit display start
    $benefitsTotal = 0;
              foreach (array_filter($allowances) as $benefitid => $benefitname) {
                $sqlGetBenefit = "SELECT employee_benefits.benefitvalue AS benefitvalue,
                benefits.benefitslug AS benefitslug
                FROM employee_benefits
                INNER JOIN benefits
                ON employee_benefits.benefitid = benefits.benefitid
                  WHERE employee_benefits.employeeid = " . $rowemployee['employeeid'] . "
                  AND employee_benefits.benefitid = $benefitid";

                    $resultbenefitvalue = mysqli_query($db,$sqlGetBenefit);

                    $countbenefitvalue = mysqli_num_rows($resultbenefitvalue);

                    if ($countbenefitvalue !== 0) { 

                      while ($rowBenefitValue = mysqli_fetch_array($resultbenefitvalue)) {
                          if($rowBenefitValue['benefitslug'] == "exemptcarallowance" || $rowBenefitValue['benefitslug'] == "taxablecarallowance") {

                            echo "<input type = \"hidden\" value = ". $rowBenefitValue['benefitvalue'] . " id = \"" . $rowBenefitValue['benefitslug'] . $rowemployee['employeeid'] . "\" readonly=\"readonly\" >";
                          $benefitsTotal = $benefitsTotal + $rowBenefitValue['benefitvalue'];

                          } else {

                            echo "<td><input type = \"number\" value = ". $rowBenefitValue['benefitvalue'] . " id = \"" . $rowBenefitValue['benefitslug'] . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";
                          $benefitsTotal = $benefitsTotal + $rowBenefitValue['benefitvalue'];

                          }


                        }

                      } else {
                        echo "<td><input type = \"number\" value = \"0\" id = \"benefitVal\" readonly=\"readonly\" ></td>";
                      }

                } 
    // benefits end here
    echo "<input type = \"hidden\" value = " . $benefitsTotal . " style=\"background:#FCEC85;\" id = \"benefitsvaluehidden" . $rowemployee['employeeid'] . "\">";

    echo "<input type = \"hidden\" value = " . $rowemployee['payeRate'] . " style=\"background:#FCEC85;\" id = \"payeRate" . $rowemployee['employeeid'] . "\">";


    $edfAmount = "325000";

    $dqlGetEmployeeIETValues = "
        SELECT value
        FROM valuesbyemployee
        WHERE valuestartdate <= '$payrollStart' AND valueenddate >= '$payrollStart'
        AND employeeid = '" . $rowemployee['employeeid'] . "'
        LIMIT 1
        ";

      $resultValuesByEmployee = mysqli_query($db,$dqlGetEmployeeIETValues);

      $countValuesByEmployee = mysqli_num_rows($resultValuesByEmployee);

      if ($countValuesByEmployee != 0) { 

        while ($rowValuesByEmployee = mysqli_fetch_array($resultValuesByEmployee)) { 
         // $prgfValue = $basicSalary * ($rowValuesByCompany['value'] / 100); 
         echo "<td><input type = \"number\" readonly = \"readonly\" value = " . $rowValuesByEmployee['value'] . " style=\"background:#FCEC85;\" id = \"edfAmount" . $rowemployee['employeeid'] . "\"></td>";
 
        }  

      } else {
        echo "<td><input type = \"number\" readonly = \"readonly\" value = " . $rowemployee['edf_amount'] . " style=\"background:#FF0000;\" id = \"edfAmount" . $rowemployee['employeeid'] . "\"></td>";
 
      }



    //echo "<td><input type = \"number\" readonly = \"readonly\" value = " . $rowemployee['edf_amount'] . " style=\"background:#FCEC85;\" id = \"edfAmount" . $rowemployee['employeeid'] . "\"></td>";

    echo "<input type = \"hidden\" value = " . $rowemployee['edf_months_value']  . " style=\"background:#FCEC85;\" id = \"edfMonthsValue" . $rowemployee['employeeid'] . "\">";

    $sqlTotalCarAllowance = "SELECT
    benefits.benefitname AS benefitname,
    employee_benefits.employeeid AS employeeid,
    sum(employee_benefits.benefitvalue) AS benefitvalue
    FROM employee_benefits
    INNER JOIN benefits
    ON employee_benefits.benefitid = benefits.benefitid
    WHERE employee_benefits.employeeid = '" . $rowemployee['employeeid'] . "' 
    AND benefitname IN ('Taxable Car Allowance','Excempt Car Allowance');";

    $resultTotalCarAllowance = mysqli_query($db,$sqlTotalCarAllowance);

    $countTotalCarAllowance = mysqli_num_rows($resultTotalCarAllowance);

      if ($countTotalCarAllowance !== 0) { 

        while ($rowTotalCarAllowance = mysqli_fetch_array($resultTotalCarAllowance)) {
          echo "<td><input type = \"number\" value = \"" . $rowTotalCarAllowance['benefitvalue'] . "\" readonly = \"readonly\" id = \"totalcarallowance" . $rowemployee['employeeid'] . "\"></td>";

        }

       } else {
        echo "<td><input type = \"number\" value = '0' readonly = \"readonly\" id = \"totalcarallowance" . $rowemployee['employeeid'] . "\"></td>";

       }


// hidden allowance save house
           $sqlHouseAllowance = "SELECT
            benefits.benefitname AS benefitname,
            employee_benefits.employeeid AS employeeid,
            sum(employee_benefits.benefitvalue) AS benefitvalue
            FROM employee_benefits
            INNER JOIN benefits
            ON employee_benefits.benefitid = benefits.benefitid
            WHERE employee_benefits.employeeid = '" . $rowemployee['employeeid'] . "' 
            AND benefitname = 'House Allowance';";

    $resultHouseAllowance = mysqli_query($db,$sqlHouseAllowance);

    $countHouseAllowance = mysqli_num_rows($resultHouseAllowance);

      if ($countHouseAllowance !== 0) { 

        while ($rowHouseAllowance = mysqli_fetch_array($resultHouseAllowance)) {
          echo "<input type = \"hidden\" value = \"" . $rowHouseAllowance['benefitvalue'] . "\" readonly = \"readonly\" id = \"housingallowance" . $rowemployee['employeeid'] . "\">";

        }

       } else {
        echo "<input type = \"hidden\" value = '0' readonly = \"readonly\" id = \"housingallowance" . $rowemployee['employeeid'] . "\">";

       }

// hidden allowance save

       // hidden allowance save telephone
           $sqlTelephoneAllowance = "SELECT
            benefits.benefitname AS benefitname,
            employee_benefits.employeeid AS employeeid,
            sum(employee_benefits.benefitvalue) AS benefitvalue
            FROM employee_benefits
            INNER JOIN benefits
            ON employee_benefits.benefitid = benefits.benefitid
            WHERE employee_benefits.employeeid = '" . $rowemployee['employeeid'] . "' 
            AND benefitname = 'Telephone Allowance';";

    $resultTelephoneAllowance = mysqli_query($db,$sqlTelephoneAllowance);

    $countTelephoneAllowance = mysqli_num_rows($resultTelephoneAllowance);

      if ($countTelephoneAllowance !== 0) { 

        while ($rowTelephoneAllowance = mysqli_fetch_array($resultTelephoneAllowance)) {
          echo "<input type = \"hidden\" value = \"" . $rowTelephoneAllowance['benefitvalue'] . "\" readonly = \"readonly\" id = \"telephoneallowance" . $rowemployee['employeeid'] . "\">";

        }

       } else {
        echo "<input type = \"hidden\" value = '0' readonly = \"readonly\" id = \"telephoneallowance" . $rowemployee['employeeid'] . "\">";

       }

// hidden allowance save

       // hidden allowance save driver
           $sqlDriverAllowance = "SELECT
            benefits.benefitname AS benefitname,
            employee_benefits.employeeid AS employeeid,
            sum(employee_benefits.benefitvalue) AS benefitvalue
            FROM employee_benefits
            INNER JOIN benefits
            ON employee_benefits.benefitid = benefits.benefitid
            WHERE employee_benefits.employeeid = '" . $rowemployee['employeeid'] . "' 
            AND benefitname = 'Driver Allowance';";

    $resultDriverAllowance = mysqli_query($db,$sqlDriverAllowance);

    $countDriverAllowance = mysqli_num_rows($resultDriverAllowance);

      if ($countDriverAllowance !== 0) { 

        while ($rowDriverAllowance = mysqli_fetch_array($resultDriverAllowance)) {
          echo "<input type = \"hidden\" value = \"" . $rowDriverAllowance['benefitvalue'] . "\" readonly = \"readonly\" id = \"driverallowance" . $rowemployee['employeeid'] . "\">";

        }

       } else {
        echo "<input type = \"hidden\" value = '0' readonly = \"readonly\" id = \"driverallowance" . $rowemployee['employeeid'] . "\">";

       }

// hidden allowance save

       // hidden allowance save other
           $sqlOtherAllowance = "SELECT
            benefits.benefitname AS benefitname,
            employee_benefits.employeeid AS employeeid,
            sum(employee_benefits.benefitvalue) AS benefitvalue
            FROM employee_benefits
            INNER JOIN benefits
            ON employee_benefits.benefitid = benefits.benefitid
            WHERE employee_benefits.employeeid = '" . $rowemployee['employeeid'] . "' 
            AND benefitname = 'Other Allowance';";

    $resultOtherAllowance = mysqli_query($db,$sqlOtherAllowance);

    $countOtherAllowance = mysqli_num_rows($resultOtherAllowance);

      if ($countOtherAllowance !== 0) { 

        while ($rowOtherAllowance = mysqli_fetch_array($resultOtherAllowance)) {
          echo "<input type = \"hidden\" value = \"" . $rowOtherAllowance['benefitvalue'] . "\" readonly = \"readonly\" id = \"otherallowance" . $rowemployee['employeeid'] . "\">";

        }

       } else {
        echo "<input type = \"hidden\" value = '0' readonly = \"readonly\" id = \"otherallowance" . $rowemployee['employeeid'] . "\">";

       }

// hidden allowance save


    if ($count101Check !== 0) { 
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['specialBonus'] . " id = \"specialBonus" . $rowemployee['employeeid'] . "\"></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\" id = \"specialBonus" . $rowemployee['employeeid'] . "\"></td>";
    }

    if ($count101Check !== 0) { 
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['taxableAllowance'] . " id = \"taxableAllowance" . $rowemployee['employeeid'] . "\"></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\" id = \"taxableAllowance" . $rowemployee['employeeid'] . "\"></td>";
    }

    if ($count101Check !== 0) { 
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['nonTaxableAllowance'] . " id = \"nonTaxableAllowance" . $rowemployee['employeeid'] . "\"></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\" id = \"nonTaxableAllowance" . $rowemployee['employeeid'] . "\"></td>";
    }

    if ($count101Check !== 0) { 
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['commission'] . " id = \"commission" . $rowemployee['employeeid'] . "\"></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\"  id = \"commission" . $rowemployee['employeeid'] . "\"></td>";
    }

    


    $getOvertime = "SELECT * FROM overtimes WHERE employeeid = " . $rowemployee['employeeid'] . " AND periodid = " . $periodSelectID . ";";

    $resultOvertime = mysqli_query($db,$getOvertime);

    $numRowsOvertime = mysqli_num_rows($resultOvertime);

    if ($numRowsOvertime == 0) {

      echo "<td><input type = \"number\" value = \"0\" id = \"overtime" . $rowemployee['employeeid'] . "\"></td>";

    } else {

        while ($rowOvertime = mysqli_fetch_array($resultOvertime)) {

            echo "<td><input type = \"number\" value = " . $rowOvertime['totalovertime'] . " id = \"overtime" . $rowemployee['employeeid'] . "\"></td>";
         }
      

    }

    ///

    $getCarBenefitValue = "SELECT * FROM carbenefits WHERE carbenefitid = '" . $rowemployee['carbenefitlinkid'] .  "';";

    $resultCarBenefitValue = mysqli_query($db,$getCarBenefitValue);

    $numCarBenefitValue = mysqli_num_rows($resultCarBenefitValue);

    while ($rowCarBenefitValue = mysqli_fetch_array($resultCarBenefitValue)) {

            echo "<input type = \"hidden\" value = " . $rowCarBenefitValue['tiervalue'] . " id = \"carbenefitvalue" . $rowemployee['employeeid'] . "\">";
         }


    ///

    

    $totalPackage = $rowemployee['basic'] + $rowemployee['travelling'] + $benefitsTotal;
    
    if ($booleanDecember == 1) {
      
      if (array_key_exists($rowemployee['employeeid'], $employeeBonusArray)) {
        echo "<td><input type = \"number\" style=\"background:#fd48f9;\" value='" . $employeeBonusArray[$rowemployee['employeeid']][0] . "' id = \"eoybonus" . $rowemployee['employeeid'] . "\"></td>";

      } else {
        echo "<td><input type = \"number\" style=\"background:#fd48f9;\" value='0' id = \"eoybonus" . $rowemployee['employeeid'] . "\"></td>";
   
      }
        
        
    } else {
      echo "<input type = \"hidden\" style=\"background:#fd48f9;\" value='0' id = \"eoybonus" . $rowemployee['employeeid'] . "\">";
    
    }



     if ($count101Check !== 0) { 
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['totalPackage'] . " id = \"totalPackage" . $rowemployee['employeeid'] . "\" readonly=\"readonly\"></td>";
    } else {

      echo "<td><input type = \"number\" id = \"totalPackage" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";
    }

    // unauth absence days starts here
    if ($count101Check !== 0) { 
      //echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['absencesInput'] . " id = \"absencesInput" . $rowemployee['employeeid'] . "\" ></td>";

      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['absencesValue'] . " id = \"absencesValue" . $rowemployee['employeeid'] . "\" readonly=\"readonly\"></td>";
    } else {

      //echo "<td><input type=\"number\" name=\"absences\" style=\"background:#FCEC85;\" id=\"absencesInput" . $rowemployee['employeeid'] . "\"></td>"; //Absences
    echo "<td><input type=\"number\" name=\"absencesValue\" id=\"absencesValue" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";
    }
    // unauth absence days ends here


    

      echo "<script type=\"text/javascript\">
        $(document).ready(function() {
            $('#absencesInput" . $rowemployee['employeeid'] . "').keyup(function() {
                $('#absencesValue" . $rowemployee['employeeid'] . "').val( ($(this).val() * ( $('#basicSal" . $rowemployee['employeeid'] . "').val() / $('#workingDaysValue" . $rowemployee['employeeid'] . "').val() )).toFixed(2) );
            });
        });     
      </script>";


        echo "<td><input type = \"number\"  value = ". getNSFEmployee(intval($rowemployee['basic']),$db) . " id = \"nsfEmp" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";

        if ($count101Check !== 0) { 
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['payeEmp'] . " id = \"payeEmp" . $rowemployee['employeeid'] . "\" readonly=\"readonly\"></td>";
    } else {

      echo "<td><input type = \"number\"  id = \"payeEmp" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";
    }

    if ($booleanDecember == 1) {
      
      if (array_key_exists($rowemployee['employeeid'], $employeeBonusArray)) {
        echo "<td><input type = \"number\" style=\"background:#fd48f9;\" value='" . $employeeBonusArray[$rowemployee['employeeid']][1] . "' id = \"payeonbonus" . $rowemployee['employeeid'] . "\"></td>";

      } else {
        echo "<td><input type = \"number\" style=\"background:#fd48f9;\" value='0' id = \"payeonbonus" . $rowemployee['employeeid'] . "\"></td>";
   
      }



    } else {
      echo "<input type = \"hidden\" style=\"background:#fd48f9;\" value='0' id = \"payeonbonus" . $rowemployee['employeeid'] . "\">";
    
    }

    if ($count101Check !== 0) {
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['solidaritylevy'] . " id = \"solidaritylevy" . $rowemployee['employeeid'] . "\" ></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\" id = \"solidaritylevy" . $rowemployee['employeeid'] . "\" ></td>";
    }

    if ($booleanDecember == 1) {
      
      if (array_key_exists($rowemployee['employeeid'], $employeeBonusArray)) {
        echo "<td><input type = \"number\" style=\"background:#fd48f9;\" value='" . $employeeBonusArray[$rowemployee['employeeid']][2] . "' id = \"csgbonus" . $rowemployee['employeeid'] . "\"></td>";

      } else {
        echo "<td><input type = \"number\" style=\"background:#fd48f9;\" value='0' id = \"csgbonus" . $rowemployee['employeeid'] . "\"></td>";
   
      }

    } else {
      echo "<input type = \"hidden\" style=\"background:#fd48f9;\" value='0' id = \"csgbonus" . $rowemployee['employeeid'] . "\">";
    
    }

    echo "<input type = \"hidden\"  value = ". getCSGEmployee(intval($rowemployee['basic']),$db) . " id = \"tempemployeeCSG" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" >";

    echo "<td><input type = \"number\"  value = ". getCSGEmployee(intval($rowemployee['basic']),$db) . " id = \"employeeCSG" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";


    // deductions display start
        $deductionsTotal = 0;
        foreach (array_filter($deductions1) as $deductionid => $deductionname) {
          $sqlGetDeduction = "SELECT deductionvalue
          FROM employee_deductions
            WHERE employeeid = " . $rowemployee['employeeid'] . "
            AND deductionid = $deductionid";

              $resultdeductionvalue = mysqli_query($db,$sqlGetDeduction);

              $countdeductionvalue = mysqli_num_rows($resultdeductionvalue);

              if ($countdeductionvalue !== 0) { 

                while ($rowDeductionValue = mysqli_fetch_array($resultdeductionvalue)) {
                    echo "<td><input type = \"number\" value = ". $rowDeductionValue['deductionvalue'] . " id = \"deductionVal\" readonly=\"readonly\" ></td>";
                    $deductionsTotal = $deductionsTotal + $rowDeductionValue['deductionvalue'];

                  }

                } else {
                  echo "<td><input type = \"number\"  value = \"0\" id = \"deductionVal\" readonly=\"readonly\" ></td>";
                }

          } 
    // deductions display ends here

                 // hidden deduction save loan
           $sqlLoanDeduction = "SELECT
            deductions.deductionname AS deductionname,
            employee_deductions.employeeid AS employeeid,
            sum(employee_deductions.deductionvalue) AS deductionvalue
            FROM employee_deductions
            INNER JOIN deductions
            ON employee_deductions.deductionid = deductions.deductionid
            WHERE employee_deductions.employeeid = '" . $rowemployee['employeeid'] . "' 
            AND deductionname = 'Loan';";

    $resultLoanDeduction = mysqli_query($db,$sqlLoanDeduction);

    $countLoanDeduction = mysqli_num_rows($resultLoanDeduction);

      if ($countLoanDeduction !== 0) { 

        while ($rowLoanDeduction = mysqli_fetch_array($resultLoanDeduction)) {
          echo "<input type = \"hidden\" value = \"" . $rowLoanDeduction['deductionvalue'] . "\" readonly = \"readonly\" id = \"loandeduction" . $rowemployee['employeeid'] . "\">";

        }

       } else {
        echo "<input type = \"hidden\" value = '0' readonly = \"readonly\" id = \"loandeduction" . $rowemployee['employeeid'] . "\">";

       }

// hidden deduction loan

                  // hidden deduction save medical
           $sqlMedicalDeduction = "SELECT
            deductions.deductionname AS deductionname,
            employee_deductions.employeeid AS employeeid,
            sum(employee_deductions.deductionvalue) AS deductionvalue
            FROM employee_deductions
            INNER JOIN deductions
            ON employee_deductions.deductionid = deductions.deductionid
            WHERE employee_deductions.employeeid = '" . $rowemployee['employeeid'] . "' 
            AND deductionname = 'Medical';";

    $resultMedicalDeduction = mysqli_query($db,$sqlMedicalDeduction);

    $countMedicalDeduction = mysqli_num_rows($resultMedicalDeduction);

      if ($countMedicalDeduction !== 0) { 

        while ($rowMedicalDeduction = mysqli_fetch_array($resultMedicalDeduction)) {
          echo "<input type = \"hidden\" value = \"" . $rowMedicalDeduction['deductionvalue'] . "\" readonly = \"readonly\" id = \"medicaldeduction" . $rowemployee['employeeid'] . "\">";

        }

       } else {
        echo "<input type = \"hidden\" value = '0' readonly = \"readonly\" id = \"medicaldeduction" . $rowemployee['employeeid'] . "\">";

       }

// hidden deduction loan

    if ($count101Check !== 0) { 
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = \"" . $rowSavedPayrollData['oneOffDeduction'] . "\" id = \"oneoffdeduction" . $rowemployee['employeeid'] . "\"></td>";
    } else {

      echo "<td><input type = \"number\" style=\"background:#FCEC85;\" value = \"0\" id = \"oneoffdeduction" . $rowemployee['employeeid'] . "\"></td>";
    }




          echo "<input type = \"hidden\" value = " . $deductionsTotal . " style=\"background:#FCEC85;\" id = \"SumListDeductions" . $rowemployee['employeeid'] . "\">";


    if ($booleanDecember == 1) {
      
      if (array_key_exists($rowemployee['employeeid'], $employeeBonusArray)) {
        echo "<td><input type = \"number\" style=\"background:#fd48f9;\" value='" . $employeeBonusArray[$rowemployee['employeeid']][3] . "' id = \"eoypaid" . $rowemployee['employeeid'] . "\"></td>";

      } else {
        echo "<td><input type = \"number\" style=\"background:#fd48f9;\" value='0' id = \"eoypaid" . $rowemployee['employeeid'] . "\"></td>";
   
      }

    } else {
      echo "<input type = \"hidden\" style=\"background:#fd48f9;\" value='0' id = \"eoypaid" . $rowemployee['employeeid'] . "\">";
    
    }


    $totalDeductions = getNPS(intval($rowemployee['basic'])) + getNSFEmployee(intval($rowemployee['basic']),$db) + getPAYE(intval($rowemployee['edf_amount']),$totalPackage) + $deductionsTotal;


    if ($count101Check !== 0) { 
      echo "<td><input type = \"number\" style=\"\" value = " . $rowSavedPayrollData['totalDed'] . " id = \"totalDed" . $rowemployee['employeeid'] . "\" readonly=\"readonly\"></td>";
    } else {

      echo "<td><input type = \"number\" id = \"totalDed" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";
    }
        


    $netSalary = $totalPackage - $totalDeductions;
    
    if ($count101Check !== 0) { 
      echo "<td><input type = \"number\" style=\"background:#99ffcc;\" value = " . $rowSavedPayrollData['netSalary'] . " id = \"netSalary" . $rowemployee['employeeid'] . "\" readonly=\"readonly\"></td>";
    } else {

      echo "<td><input type = \"number\" id = \"netSalary" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";
    }
        


    



    echo "<td><input type = \"number\"  value = ". getCSGEmployer(intval($rowemployee['basic']),$db) . " id = \"employerCSG" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";

    echo "<td><input type = \"number\"  value = ". getNSFEmployer(intval($rowemployee['basic']),$db) . " id = \"employerNSF" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";

    echo "<td><input type = \"number\"  value = ". getLevyEmployer(intval($rowemployee['basic']),$db) . " id = \"employerLEVY" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";
    

    // PRGF START

    $sqlGetTotalBenefitsPrgf = "SELECT sum(employee_benefits.benefitvalue) AS selbenefitsum 
    FROM `employee_benefits`
    INNER JOIN benefits ON employee_benefits.benefitid = benefits.benefitid
    WHERE employee_benefits.employeeid = '" . $rowemployee['employeeid'] . "' AND benefits.prgf_flag = '1' 
    ORDER BY employee_benefits.employeeid ASC;";

    $resultGetTotalBenefits = mysqli_query($db,$sqlGetTotalBenefitsPrgf);

    $countTBT = mysqli_num_rows($resultGetTotalBenefits);

    $benefitsToAdd = 0;

    if ($countTBT !== 0) { 

      while ($rowBTB = mysqli_fetch_array($resultGetTotalBenefits)) {
        $benefitsToAdd = $rowBTB['selbenefitsum'];
      }

    }

    // PRGF END

    $totalToCheckPRGF = intval($rowemployee['basic']) + $benefitsToAdd;

    echo "<td>";
    echo "<input type = \"hidden\"  value = ". $totalToCheckPRGF . " id = \"remuneration" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ><br>";
    echo "<input type = \"hidden\"  value = \"". $benefitsToAdd . "\" id = \"allowances" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ><br>";
    echo "</td>";

    if ($rowemployee['citizenboolean'] == 'Y') {

      if ($rowemployee['pensionboolean'] == 'N' || $rowemployee['pensionboolean'] == null ) {
        echo "<td><input type = \"number\"  value = ". getPRGFEmployer($totalToCheckPRGF,$payrollStart,$companyID,$db) . " id = \"employerPRGF" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";
      } else if ($rowemployee['pensionboolean'] == 'Y') {
        echo "<td><input type = \"number\"  value = \"0\" id = \"employerPRGF" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";
      }

    } else if ($rowemployee['citizenboolean'] == 'N') {
      echo "<td><input type = \"number\"  value = \"0\" id = \"employerPRGF" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";
    }

    

    

    echo "<td><input type = \"number\"  value = ". getCSGEmployee(intval($rowemployee['basic']),$db) . " id = \"employeeCSG" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";

    echo "<td><input type = \"number\"  value = ". getNSFEmployee(intval($rowemployee['basic']),$db) . " id = \"employeeNSF" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";

    $totalCSG = getCSGEmployer(intval($rowemployee['basic']),$db) + getCSGEmployee(intval($rowemployee['basic']),$db);
    $totalNSF = getNSFEmployer(intval($rowemployee['basic']),$db) + getNSFEmployee(intval($rowemployee['basic']),$db);

    echo "<td><input type = \"number\"  value = ". $totalCSG . " id = \"totalCSGVal" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";

    echo "<td><input type = \"number\"  value = ". $totalNSF . " id = \"totalNSFVal" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";

    echo "<td><input type = \"number\"  value = ". getLevyEmployer(intval($rowemployee['basic']),$db) . " id = \"totalLEVY" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";

    $totalMRA = $totalCSG + $totalNSF + getLevyEmployer(intval($rowemployee['basic']),$db) + getPRGFEmployer(intval($rowemployee['basic']),$payrollStart,$companyID,$db);

    echo "<input type = \"hidden\" value = " . $totalMRA  . " style=\"background:#FCEC85;\" id = \"totalMRAbeforePAYE" . $rowemployee['employeeid'] . "\">";

    echo "<td><input type = \"number\"  id = \"totalMRAVal" . $rowemployee['employeeid'] . "\" readonly=\"readonly\" ></td>";


    if ($payrollStatus == "open") {
            
     //   echo "<td><button type=\"button\" onclick=\"loadDoc" . $rowemployee['employeeid'] . "()\">Ok</button></td>";


   // echo "<td><input id=\"submit" . $rowemployee['employeeid'] . "\" class=\"submit\" onclick=\"formsubmit" . $rowemployee['employeeid'] . "()\" type=\"button\" value=\"Save\" disabled=\"1\"></td>";


      } else if ($payrollStatus == "closed") {}



    /*

    echo "    

    <script type=\"text/javascript\">
    
        function formsubmit" . $rowemployee['employeeid'] . "()
        {
         
         var payrollid =document.getElementById( \"payrollid" . $rowemployee['employeeid'] . "\" ).value;

         var employeeid =document.getElementById( \"employeeid" . $rowemployee['employeeid'] . "\" ).value;
         var basicSal =document.getElementById( \"basicSal" . $rowemployee['employeeid'] . "\" ).value;
         var travellingAmt =document.getElementById( \"travellingAmt" . $rowemployee['employeeid'] . "\" ).value;
         var specialBonus =document.getElementById( \"specialBonus" . $rowemployee['employeeid'] . "\" ).value;
         var carbenefitvalue =document.getElementById( \"carbenefitvalue" . $rowemployee['employeeid'] . "\" ).value;
         var totalcarallowance =document.getElementById( \"totalcarallowance" . $rowemployee['employeeid'] . "\" ).value;
         var housingallowance =document.getElementById( \"housingallowance" . $rowemployee['employeeid'] . "\" ).value;
         var telephoneallowance =document.getElementById( \"telephoneallowance" . $rowemployee['employeeid'] . "\" ).value;
         var driverallowance =document.getElementById( \"driverallowance" . $rowemployee['employeeid'] . "\" ).value;
         var otherallowance =document.getElementById( \"otherallowance" . $rowemployee['employeeid'] . "\" ).value;
         var commission =document.getElementById( \"commission" . $rowemployee['employeeid'] . "\" ).value;
         var overtime =document.getElementById( \"overtime" . $rowemployee['employeeid'] . "\" ).value;
         var totalPackage =document.getElementById( \"totalPackage" . $rowemployee['employeeid'] . "\" ).value;
         var WorkingDaysValue =document.getElementById( \"WorkingDaysValue" . $rowemployee['employeeid'] . "\" ).value;
         var absencesInput =document.getElementById( \"absencesInput" . $rowemployee['employeeid'] . "\" ).value;
         var absencesValue =document.getElementById( \"absencesValue" . $rowemployee['employeeid'] . "\" ).value;
         var nsfEmp =document.getElementById( \"nsfEmp" . $rowemployee['employeeid'] . "\" ).value;
         var payeEmp =document.getElementById( \"payeEmp" . $rowemployee['employeeid'] . "\" ).value;
         var solidaritylevy =document.getElementById( \"solidaritylevy" . $rowemployee['employeeid'] . "\" ).value;
         var loandeduction =document.getElementById( \"loandeduction" . $rowemployee['employeeid'] . "\" ).value;
         var medicaldeduction =document.getElementById( \"medicaldeduction" . $rowemployee['employeeid'] . "\" ).value;
         var oneoffdeduction =document.getElementById( \"oneoffdeduction" . $rowemployee['employeeid'] . "\" ).value;
         var totalDed =document.getElementById( \"totalDed" . $rowemployee['employeeid'] . "\" ).value;
         var netSalary =document.getElementById( \"netSalary" . $rowemployee['employeeid'] . "\" ).value;
         var employerCSG =document.getElementById( \"employerCSG" . $rowemployee['employeeid'] . "\" ).value;
         var employerNSF =document.getElementById( \"employerNSF" . $rowemployee['employeeid'] . "\" ).value;
         var employerLEVY =document.getElementById( \"employerLEVY" . $rowemployee['employeeid'] . "\" ).value;
         var employerPRGF =document.getElementById( \"employerPRGF" . $rowemployee['employeeid'] . "\" ).value;
         var employeeCSG =document.getElementById( \"employeeCSG" . $rowemployee['employeeid'] . "\" ).value;
         var employeeNSF =document.getElementById( \"employeeNSF" . $rowemployee['employeeid'] . "\" ).value;
         var totalCSGVal =document.getElementById( \"totalCSGVal" . $rowemployee['employeeid'] . "\" ).value;
         var totalNSFVal =document.getElementById( \"totalNSFVal" . $rowemployee['employeeid'] . "\" ).value;
         var totalMRAVal =document.getElementById( \"totalMRAVal" . $rowemployee['employeeid'] . "\" ).value;
    
          var formdata = 
              'payrollid=' + payrollid + 
              '&employeeid=' + employeeid + 
              '&basicSal=' + basicSal + 
              '&travellingAmt=' + travellingAmt + 
              '&specialBonus=' + specialBonus +
              '&carbenefitvalue=' + carbenefitvalue +
              '&totalcarallowance=' + totalcarallowance +              
              '&housingallowance=' + housingallowance +              
              '&telephoneallowance=' + telephoneallowance +              
              '&driverallowance=' + driverallowance +              
              '&otherallowance=' + otherallowance +              
              '&commission=' + commission + 
              '&overtime=' + overtime +
              '&totalPackage=' + totalPackage + 
              '&WorkingDaysValue=' + WorkingDaysValue + 
              '&absencesInput=' + absencesInput + 
              '&absencesValue=' + absencesValue + 
              '&nsfEmp=' + nsfEmp + 
              '&payeEmp=' + payeEmp + 
              '&solidaritylevy=' + solidaritylevy + 
              '&loandeduction=' + loandeduction + 
              '&medicaldeduction=' + medicaldeduction + 
              '&oneoffdeduction=' + oneoffdeduction + 
              '&totalDed=' + totalDed + 
              '&netSalary=' + netSalary + 
              '&employerCSG=' + employerCSG + 
              '&employerNSF=' + employerNSF + 
              '&employerLEVY=' + employerLEVY + 
              '&employerPRGF=' + employerPRGF + 
              '&employeeCSG=' + employeeCSG + 
              '&employeeNSF=' + employeeNSF + 
              '&totalCSGVal=' + totalCSGVal + 
              '&totalNSFVal=' + totalNSFVal + 
              '&totalMRAVal=' + totalMRAVal;

  
  // AJAX code to submit form.
  $.ajax({
     type: \"POST\",
     url: \"insertpayrolldata.php\", //call storeemdata.php to store form data
     data: formdata,
     cache: false,
     success: function(html) {
      alert(html);
     }
  });

  return false;
}
    
        </script>";
*/
    echo "</form>";

    echo "</tr>";


  } // FETCHING EMPLOYEE DATA END

  echo "</tbody>";
  echo "</table>";

  echo "
  <script>
    function myFunction() {
      // Declare variables
      var input, filter, table, tr, td, i, txtValue;
      input = document.getElementById(\"myInput\");
      filter = input.value.toUpperCase();
      table = document.getElementById(\"myTable\");
      tr = table.getElementsByTagName(\"tr\");

      // Loop through all table rows, and hide those who don't match the search query
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName(\"td\")[0];
        if (td) {
          txtValue = td.textContent || td.innerText;
          if (txtValue.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = \"\";
          } else {
            tr[i].style.display = \"none\";
          }
        }
      }
    }
  </script>  
  
  ";  
  
  
  // TABLE ENDS HERE




    } // COUNT EMPLOYEES END HERE

    echo "<script type=\"text/javascript\">
    
    var users =" . json_encode($employeearray) . ";

     function selectOkForAll(){

      

    users.forEach(item => testFunction(item));
  }


    function testFunction(j){

       
        var valueTotalPackage = Number($('#totalPackage'+j).val());
        var valueECA = Number($('#exemptcarallowance'+j).val());
        var valueEdfAmount = Number($('#edfAmount'+j).val());
        var valuePayeRate = Number($('#payeRate'+j).val());

        $('#totalPackage'+j).val( Number($('#basicSal'+j).val()) + Number($('#travellingAmt'+j).val()) + Number($('#taxableAllowance'+j).val()) + Number($('#nonTaxableAllowance'+j).val()) + Number($('#specialBonus'+j).val()) + Number($('#commission'+j).val()) + + Number($('#overtime'+j).val()) + Number($('#benefitsvaluehidden'+j).val()) + Number($('#eoybonus'+j).val()) ); 

        $('#payeEmp'+j).val( ( (Number($('#totalPackage'+j).val()) - Number($('#travellingAmt'+j).val()) + Number($('#carbenefitvalue'+j).val()) - Number($('#nonTaxableAllowance'+j).val()) - Number($('#exemptcarallowance'+j).val()) - Number($('#absencesValue'+j).val()) - (Number($('#edfAmount'+j).val()) / Number($('#edfMonthsValue'+j).val()) ) )  *  (Number($('#payeRate'+j).val())/100)  ).toFixed(0) );

          if ($('#payeEmp'+j).val() < 0) {
            $('#payeEmp'+j).val(0);
          }

          if (Number($('#employeeTravelling'+j).val()) == 0) {
            $('#travellingAmt'+j).val(Number($('#travellingAdjust'+j).val()));
          } else {
            $('#travellingAmt'+j).val( (Number($('#employeeTravelling'+j).val()) * Number($('#numWrkDays'+j).val()) ) + Number($('#travellingAdjust'+j).val()) );
          }

          

          if ($('#loandeduction'+j).val() == \"\") {
            $('#loandeduction'+j).val(Number(0));
          }

          if ($('#medicaldeduction'+j).val() == \"\") {
            $('#medicaldeduction'+j).val(Number(0));
          }
          
            
       
       // $('#payeEmp'+j).val(  Number(( valueTotalPackage - valueECA -  (valueEdfAmount / 13) ) * ( valuePayeRate / 100 )) );

       $('#employeeCSG'+j).val(  Number($('#csgbonus'+j).val()) + Number($('#tempemployeeCSG'+j).val()) );

        $('#totalDed'+j).val( Number($('#absencesValue'+j).val()) + Number($('#oneoffdeduction'+j).val()) + Number($('#SumListDeductions'+j).val()) + Number($('#nsfEmp'+j).val()) + Number($('#payeEmp'+j).val()) + Number($('#solidaritylevy'+j).val()) + Number($('#employeeCSG'+j).val()) + Number($('#eoypaid'+j).val()) + Number($('#csgbonus'+j).val()) + Number($('#payeonbonus'+j).val()) );

        $('#netSalary'+j).val( Number($('#totalPackage'+j).val()) + Number($('#SumListDeductions'+j).val()) - Number($('#totalDed'+j).val()) - Number($('#medicaldeduction'+j).val()) - Number($('#loandeduction'+j).val()) ); 

       // $('#totalMRAVal'+j).val( Number($('#totalMRAbeforePAYE'+j).val()) + Number($('#payeEmp'+j).val()) + Number($('#solidaritylevy'+j).val()) ); 

        $('#totalMRAVal'+j).val( Number($('#totalCSGVal'+j).val()) + Number($('#totalNSFVal'+j).val()) + Number($('#employerPRGF'+j).val()) + Number($('#employerLEVY'+j).val()) + Number($('#payeEmp'+j).val()) + Number($('#solidaritylevy'+j).val())); 


    $('#netSalary'+j).css('background-color', '#85FC89');

    $('#employeerow'+j).css('background-color', '#85FC89');

    $('#finalsavebutton').attr(\"disabled\", false);


    }


    let x = 0;
function selectSaveForAll(){

  
    users.forEach(item => saveFunction(item));
    //alert(x);
  }


function saveFunction(k)
        {
         
         var payrollid =document.getElementById( 'payrollid'+k ).value;

         var employeeid =document.getElementById( 'employeeid'+k ).value;
         var sickleavestaken =document.getElementById( 'sickleavestaken'+k ).value;
         var sickleavesbalance =document.getElementById( 'sickleavesbalance'+k ).value;
         var localleavestaken =document.getElementById( 'localleavestaken'+k ).value;
         var localleavesbalance =document.getElementById( 'localleavesbalance'+k ).value;
         var basicSal =document.getElementById( 'basicSal'+k ).value;
         var travellingAdjust =document.getElementById( 'travellingAdjust'+k ).value;
         var numWrkDays =document.getElementById( 'numWrkDays'+k ).value;
         var travellingAmt =document.getElementById( 'travellingAmt'+k ).value;
         var specialBonus =document.getElementById( 'specialBonus'+k ).value;
         var taxableAllowance =document.getElementById( 'taxableAllowance'+k ).value;
         var nonTaxableAllowance =document.getElementById( 'nonTaxableAllowance'+k ).value;
         var carbenefitvalue =document.getElementById( 'carbenefitvalue'+k ).value;
         var totalcarallowance =document.getElementById( 'totalcarallowance'+k ).value;
         var housingallowance =document.getElementById( 'housingallowance'+k ).value;
         var telephoneallowance =document.getElementById( 'telephoneallowance'+k ).value;
         var driverallowance =document.getElementById( 'driverallowance'+k ).value;
         var otherallowance =document.getElementById( 'otherallowance'+k ).value;
         var commission =document.getElementById( 'commission'+k ).value;
         var overtime =document.getElementById( 'overtime'+k ).value;
         var totalPackage =document.getElementById( 'totalPackage'+k ).value;
         var workingDaysValue =document.getElementById( 'workingDaysValue'+k ).value;
         var absencesInput =document.getElementById( 'absencesInput'+k ).value;
         var absencesValue =document.getElementById( 'absencesValue'+k ).value;
         var nsfEmp =document.getElementById( 'nsfEmp'+k ).value;
         var payeEmp =document.getElementById( 'payeEmp'+k ).value;
         var solidaritylevy =document.getElementById( 'solidaritylevy'+k ).value;
         var loandeduction =document.getElementById( 'loandeduction'+k ).value;
         var medicaldeduction =document.getElementById( 'medicaldeduction'+k ).value;
         var oneoffdeduction =document.getElementById( 'oneoffdeduction'+k ).value;
         var totalDed =document.getElementById( 'totalDed'+k ).value;
         var netSalary =document.getElementById( 'netSalary'+k ).value;
         var remuneration =document.getElementById( 'remuneration'+k ).value;
         var allowances =document.getElementById( 'allowances'+k ).value;
         var employerCSG =document.getElementById( 'employerCSG'+k ).value;
         var employerNSF =document.getElementById( 'employerNSF'+k ).value;
         var employerLEVY =document.getElementById( 'employerLEVY'+k ).value;
         var employerPRGF =document.getElementById( 'employerPRGF'+k ).value;
         var employeeCSG =document.getElementById( 'employeeCSG'+k ).value;
         var employeeNSF =document.getElementById( 'employeeNSF'+k ).value;
         var totalCSGVal =document.getElementById( 'totalCSGVal'+k ).value;
         var totalNSFVal =document.getElementById( 'totalNSFVal'+k ).value;
         var totalMRAVal =document.getElementById( 'totalMRAVal'+k ).value;
    
          var formdata = 
              'payrollid=' + payrollid +               
              '&employeeid=' + employeeid + 
              '&sickleavestaken=' + sickleavestaken +
              '&sickleavesbalance=' + sickleavesbalance +
              '&localleavestaken=' + localleavestaken +
              '&localleavesbalance=' + localleavesbalance +
              '&basicSal=' + basicSal + 
              '&travellingAdjust=' + travellingAdjust + 
              '&numWrkDays=' + numWrkDays + 
              '&travellingAmt=' + travellingAmt + 
              '&specialBonus=' + specialBonus +
              '&taxableAllowance=' + taxableAllowance +
              '&nonTaxableAllowance=' + nonTaxableAllowance +
              '&carbenefitvalue=' + carbenefitvalue +
              '&totalcarallowance=' + totalcarallowance +              
              '&housingallowance=' + housingallowance +              
              '&telephoneallowance=' + telephoneallowance +              
              '&driverallowance=' + driverallowance +              
              '&otherallowance=' + otherallowance +             
              '&commission=' + commission + 
              '&overtime=' + overtime +
              '&totalPackage=' + totalPackage + 
              '&WorkingDaysValue=' + workingDaysValue + 
              '&absencesInput=' + absencesInput + 
              '&absencesValue=' + absencesValue + 
              '&nsfEmp=' + nsfEmp + 
              '&payeEmp=' + payeEmp +  
              '&solidaritylevy=' + solidaritylevy +  
              '&loandeduction=' + loandeduction +  
              '&medicaldeduction=' + medicaldeduction +  
              '&oneoffdeduction=' + oneoffdeduction + 
              '&totalDed=' + totalDed + 
              '&netSalary=' + netSalary + 
              '&remuneration=' + remuneration + 
              '&allowances=' + allowances + 
              '&employerCSG=' + employerCSG + 
              '&employerNSF=' + employerNSF + 
              '&employerLEVY=' + employerLEVY + 
              '&employerPRGF=' + employerPRGF + 
              '&employeeCSG=' + employeeCSG + 
              '&employeeNSF=' + employeeNSF + 
              '&totalCSGVal=' + totalCSGVal + 
              '&totalNSFVal=' + totalNSFVal + 
              '&totalMRAVal=' + totalMRAVal;

  
  // AJAX code to submit form.
  $.ajax({
     type: \"POST\",
     url: \"insertpayrolldata.php\", //call storeemdata.php to store form data
     data: formdata,
     cache: false,
     success: function(html) {
      $('#employeerow'+k).css('background-color', '#90CCDE');
      x = x + 1;
      //alert(html);
     }
  });

  return false;
}
    

 

</script>";

if ($payrollStatus == "open") {
            
        echo "<p><button type=\"button\" onclick=\"selectOkForAll()\" class=\"btn btn-success\">Step 1: Compute all Numbers</button></p>";
        echo "<p><button id = \"finalsavebutton\" type=\"button\" onclick=\"selectSaveForAll()\" disabled='1' class=\"btn btn-danger\">Step 2: Save Payroll</button></p>";


      } else if ($payrollStatus == "closed") {}
    

} // GET ENDS HERE

include('footer1.php');

?>