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


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

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

  $payrollid = $_GET['payrollID'];

  $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.employeefileno AS employeefileno,
          employees.employeename AS employeename,
          employees.employeesurname AS employeesurname,
          employees.employeenic AS employeenic,
          employees.employee_tan_number AS employee_tan_number,
          employees.employee_join_date AS joining_date,
          employees.employee_termination_date AS termination_date,
          departments.departmentname AS departmentname,
          positions.positionname AS positionname,
          payrollbasicdetails.s_taken AS sickTaken,
          payrollbasicdetails.s_balance AS sickBalance,
          payrollbasicdetails.l_taken AS localTaken,
          payrollbasicdetails.l_balance AS localBalance,
          payrollbasicdetails.netSalary AS netSalary,
          payrollbasicdetails.basicSal AS basicSal,
          payrollbasicdetails.travellingAmt AS travellingAmt,
          payrollbasicdetails.specialBonus AS specialBonus,
          payrollbasicdetails.taxableAllowance AS taxableAllowance,
          payrollbasicdetails.nonTaxableAllowance AS nonTaxableAllowance,
          payrollbasicdetails.housingAllowance AS housingAllowance,
          payrollbasicdetails.telephoneAllowance AS telephoneAllowance,
          payrollbasicdetails.driverAllowance AS driverAllowance,
          payrollbasicdetails.totalcarallowance AS totalcarallowance,
          payrollbasicdetails.otherAllowance AS otherAllowance,
          payrollbasicdetails.commission AS commission,
          payrollbasicdetails.overtime AS overtime,
          payrollbasicdetails.totalPackage AS totalPackage,
          payrollbasicdetails.absencesInput AS absencesInput,
          payrollbasicdetails.absencesValue AS absencesValue,
          payrollbasicdetails.nsfEmp AS nsfEmp,
          payrollbasicdetails.payeEmp AS payeEmp,
          payrollbasicdetails.solidaritylevy AS solidaritylevy,
          payrollbasicdetails.loan AS loan,
          payrollbasicdetails.medical AS medical,
          payrollbasicdetails.totalDed AS totalDed,
          payrollbasicdetails.oneOffDeduction AS oneOffDeduction,
          payrollbasicdetails.employerCSG AS employerCSG,
          payrollbasicdetails.employerNSF AS employerNSF,
          payrollbasicdetails.employerLEVY AS employerLEVY,
          payrollbasicdetails.employeeCSG AS employeeCSG,
          payrollbasicdetails.employeeNSF AS employeeNSF,
          payrollbasicdetails.totalCSGVal AS totalCSGVal,
          payrollbasicdetails.totalNSFVal AS totalNSFVal,
          payrollbasicdetails.totalMRAVal AS totalMRAVal,
          periods.periodName AS monthName
          FROM payrollbasicdetails
          LEFT JOIN employees
          ON payrollbasicdetails.employeeid = employees.employeeid
          LEFT JOIN employee_job
          ON employee_job.employeeid = employees.employeeid
          LEFT JOIN positions
          ON employee_job.positionid = positions.positionid
          LEFT JOIN departments
          ON employee_job.departmentid = departments.departmentid
          LEFT JOIN periods
          ON payrollbasicdetails.payrollid = periods.periodid
          WHERE payrollbasicdetails.payrollid = $payrollid";

  
    $result = mysqli_query($db,$sqlView);

    $count = mysqli_num_rows($result);

    

    

    echo "<main role=\"main\" class=\"\">";

    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\">Payslips - " . $rowperiods['startDate'] . " - " . $rowperiods['endDate'] . "</h1>";
        
          $payrollStart = $rowperiods['startDate'];
          $payrollEnd = $rowperiods['endDate'];
      
        }

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

          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

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

    $employeeJoin = $rowpaysheet['joining_date'];
    $employeeTermination = $rowpaysheet['termination_date'];

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

  echo "<div class=\"card pagebreak\">" ;
        echo "<div class=\"card-body\">";    

      echo "<table class = \"table\" border=\"1\">";



      $getCompanyName = "SELECT * FROM companyfile WHERE companyid = $companyID";

        $resultCompanyName = mysqli_query($db,$getCompanyName);

        $numCompanyName = mysqli_num_rows($resultCompanyName);

        while ($rowCompanyName = mysqli_fetch_array($resultCompanyName)) { 
            echo "<tr><td colspan=\"2\">";

            if ($rowCompanyName['companyName'] == "Intellect Design") {
              echo "<center>";
              echo "<img src = \"logo-intellect-design.png\" style=\"width:50px;\">";
              echo "</center><br>";
            }

            /*

                          // Check if file already exists
            if (file_exists("logo.png")) {
              echo "<center>";
              //echo "<img src = \"logo.png\" style=\"width:50px;height:50px;\">";
              echo "</center><br>";
              $uploadOk = 0;
            } else {
              echo "";
            }
            */

            echo "<center><h3>" . $rowCompanyName['companyName'] . "</h3>";
            echo "<center><h5>PAYE Registration No." . $rowCompanyName['companyERN'] . "</h5>";


        }

      
      echo "<h4>Payslip for " . $rowpaysheet['monthName'] . "</h4></td></tr>";

      echo "
      <script>
        document.title = \"Payslips - " . $rowpaysheet['monthName'] . "\";
      </script>
    ";

      echo "<tr>";
      echo "<td>";
        echo "<p>Employee ID:&#9;<b>" . $rowpaysheet['employeefileno'] . "</b></p>";
        echo "<p>Employee Name:&#9;<b>" . $rowpaysheet['employeename'] . ", " . $rowpaysheet['employeesurname'] . "</b></p>";
        echo "<p>Employee NIC:&#9;<b>" . $rowpaysheet['employeenic'] . "</b></p>";
        echo "<p>Employee Joining Date:&#9;<b>" . $rowpaysheet['joining_date'] . "</b></p>";

        if ($rowpaysheet['employee_tan_number'] != "") {
          echo "<p>Employee TAN Number:&#9;<b>" . $rowpaysheet['employee_tan_number'] . "</b></p>";
        }
        

        echo "<p>Posting:&#9;<b>" . $rowpaysheet['positionname'] . "," . $rowpaysheet['departmentname'] .  "</b></p>";
          
        
        echo "<style>
        .griser {
          color: grey;
          font-weight: bold;
          text-align: center;
        }
        
        </style>";      
      
        

      echo "</td>";
      echo "<td>";
      echo "<h6 class=\"griser\">Leaves Management</h6>";
      echo "<table class=\"table-borderless\">
      <tr><td>Sick Leaves Taken: <b>" . $rowpaysheet['sickTaken'] . "</b></td><td>Balance: <b>" . $rowpaysheet['sickBalance'] . "</b></td>
      <tr><td>Local Leaves Taken: <b>" . $rowpaysheet['localTaken'] . "</b></td><td>Balance: <b>" . $rowpaysheet['localBalance'] . "</b></td>
      </table>";
      echo "</td>";

      echo "</tr>";

      echo "<tr>";

      echo "<td>";
      echo "<center><h6 class=\"griser\">Earnings</h6></center>";

      $totalEarnings = 0;

      echo "<p>Basic Salary:&#9;<b>" . number_format($rowpaysheet['basicSal'], 0, '.', ',') . "</b></p>";     

      $totalEarnings += $rowpaysheet['basicSal'];


      if ($rowpaysheet['taxableAllowance'] != 0) {    
        $totalEarnings += $rowpaysheet['taxableAllowance'];    
       echo "<p>Taxable Allowance: <b>" . number_format($rowpaysheet['taxableAllowance'], 0, '.', ',') . "</b></p>";
      } 

      if ($rowpaysheet['nonTaxableAllowance'] != 0) {   
        $totalEarnings += $rowpaysheet['nonTaxableAllowance'];        
       echo "<p>Non Taxable Allowance: <b>" . number_format($rowpaysheet['nonTaxableAllowance'], 0, '.', ',') . "</b></p>";
      } 

 
      if ($rowpaysheet['housingAllowance'] != 0) {      
        $totalEarnings += $rowpaysheet['housingAllowance'];     
       echo "<p>Housing Allowance: <b>" . number_format($rowpaysheet['housingAllowance'], 0, '.', ',') . "</b></p>";
      } 

      if ($rowpaysheet['telephoneAllowance'] != 0) { 
        $totalEarnings += $rowpaysheet['telephoneAllowance'];          
       echo "<p>Telephone Allowance: <b>" . number_format($rowpaysheet['telephoneAllowance'], 0, '.', ',') . "</b></p>";
      } 

      if ($rowpaysheet['driverAllowance'] != 0) {   
        $totalEarnings += $rowpaysheet['driverAllowance'];        
       echo "<p>Driver Allowance: <b>" . number_format($rowpaysheet['driverAllowance'], 0, '.', ',') . "</b></p>";
      } 

      if ($rowpaysheet['otherAllowance'] != 0) {  
        $totalEarnings += $rowpaysheet['otherAllowance'];         
       echo "<p>Other Allowance: <b>" . number_format($rowpaysheet['otherAllowance'], 0, '.', ',') . "</b></p>";
      } 

      if ($rowpaysheet['totalcarallowance'] != 0) {   
        $totalEarnings += $rowpaysheet['totalcarallowance'];        
       echo "<p>Car Allowance: <b>" . number_format($rowpaysheet['totalcarallowance'], 0, '.', ',') . "</b></p>";
      } 


  
             if ($rowpaysheet['travellingAmt'] != 0) {
              $totalEarnings += $rowpaysheet['travellingAmt'];   
          echo "<p>Bus Fare:&#9;<b>" . number_format($rowpaysheet['travellingAmt'], 0, '.', ',') . "</b></p>";
        }

            if ($rowpaysheet['specialBonus'] != 0) { 
              $totalEarnings += $rowpaysheet['specialBonus'];   
              echo "<p>Special Bonus:&#9;<b>" . number_format($rowpaysheet['specialBonus'], 0, '.', ',') . "</b></p>";
            }

            if ($rowpaysheet['commission'] != 0) {
              $totalEarnings += $rowpaysheet['commission'];   
              echo "<p>Commission:&#9;<b>" . number_format($rowpaysheet['commission'], 0, '.', ',') . "</b></p>";
            }

      
      

      if ($rowpaysheet['overtime'] == 0) {

      } else {

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

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

        $numRowsOvertime = mysqli_num_rows($resultOvertime);

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

          $basicsalary = $rowpaysheet['basicSal'];

          $hourlyrate = $basicsalary / 26 / 8;

          echo "<h5>Overtime: </h5>";

          echo "<table><thead><td>Rate</td><td>Units</td><td>Subtotal</td></thead>";

          echo "<tbody>";

          if ($rowOvertime['1_5_units'] != 0) {
          echo "<tr><td>1.5</td><td><b>" . $rowOvertime['1_5_units'] . "</b></td><td>" . round($hourlyrate * $rowOvertime['1_5_units'] * 1.5,0) . "</td></tr>";
        }


          if ($rowOvertime['2_0_units'] != 0) {
          echo "<tr><td>2.0</td><td><b>" . $rowOvertime['2_0_units'] . "</b></td><td>" . round($hourlyrate * $rowOvertime['2_0_units'] * 2.0,0) . "</td></tr>";
        }



            if ($rowOvertime['3_0_units'] != 0) {
              echo "<tr><td>3.0</td><td><b>" . $rowOvertime['3_0_units'] . "</b></td><td>" . round($hourlyrate * $rowOvertime['3_0_units'] * 3.0,0) . "</td></tr>";
            }


          
          echo "<tr><td>TOTAL OVERTIME</td><td></td><td><b>" . number_format($rowOvertime['totalovertime'], 0, '.', ',') . "</b></td></tr>";
          $totalEarnings += $rowOvertime['totalovertime'];   
          echo "</tbody>";

          echo "</table>";

        }


      }

      echo "<br><b>Total Earnings: " . number_format($totalEarnings, 0, '.', ',') . "</b>";      

      echo "</td>";
      //
      echo "<td>";
      echo "<center><h6 class=\"griser\">Deductions</h6></center>";

      $totalDeductions = 0;

          if ($rowpaysheet['loan'] != 0) {        
            $totalDeductions += $rowpaysheet['loan'];
       echo "<p>Loan: <b>" . number_format($rowpaysheet['loan'], 0, '.', ',') . "</b></p>";
      } 

      if ($rowpaysheet['medical'] != 0) {    
        $totalDeductions += $rowpaysheet['medical'];    
       echo "<p>Medical: <b>" . number_format($rowpaysheet['medical'], 0, '.', ',') . "</b></p>";
      } 

          if ($rowpaysheet['oneOffDeduction'] != 0) { 
            $totalDeductions += $rowpaysheet['oneOffDeduction'];       
       echo "<p>One Off Deduction: <b>" . number_format($rowpaysheet['oneOffDeduction'], 0, '.', ',') . "</b></p>";
      } 

      echo "<p>Absences:&#9;<b>" . number_format($rowpaysheet['absencesValue'], 0, '.', ',') . " (" . $rowpaysheet['absencesInput'] . " Absences)" . "</b></p>";
      echo "<p>NSF:&#9;<b>" . number_format($rowpaysheet['nsfEmp'], 0, '.', ',') . "</b></p>";
      echo "<p>PAYE:&#9;<b>" . number_format($rowpaysheet['payeEmp'], 0, '.', ',') . "</b></p>";

      if ($rowpaysheet['solidaritylevy'] != 0) {    
        $totalDeductions += $rowpaysheet['solidaritylevy'];    
       echo "<p>Solidarity Levy: <b>" . number_format($rowpaysheet['solidaritylevy'], 0, '.', ',') . "</b></p>";
      }

      echo "<p>CSG:&#9;<b>" . number_format($rowpaysheet['employeeCSG'], 0, '.', ',') . "</b></p>";

      //$totalDeductions = $rowpaysheet['absencesValue'] + $rowpaysheet['nsfEmp'] + $rowpaysheet['payeEmp'] + $rowpaysheet['solidaritylevy'] + $rowpaysheet['employeeCSG'];

      echo "<br><b>Total Deductions: " . number_format($rowpaysheet['totalDed'], 0, '.', ',') . "</b>";

      echo "</td>";
      //
      echo "</<tr>";

      echo "<tr>";
      echo "<td colspan=\"3\">";
      echo "<h4>Net Salary (MUR):&#9;<b>" . number_format($rowpaysheet['netSalary'], 0, '.', ',') . "</b>  <i>" . numberTowords($rowpaysheet['netSalary']) . " only</i></h4>";
      echo "<center><p><i>This payslip is computer generated and requires no signature</i></p></center>";
      echo "</tr>";
      echo "</td>";

      echo "</table>";

  echo "</div>";
  echo "</div>"; //end cards



    


  } // FETCHING EMPLOYEE DATA END


    } // COUNT EMPLOYEES END HERE

} // GET ENDS HERE

include('footer1.php');

?>