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

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

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

  include('header2.php');

          $startdate=$_POST['startdate'];
          $enddate=$_POST['enddate'];
          if (isset($_POST['getallemployees'])) {

            $getallemployees=$_POST['getallemployees'];
          }
          
          $getemployeeid=$_POST['getemployeeid'];


          $sqlView = "SELECT 
                  employees.employeename AS employeename,
                  employees.employeesurname AS employeesurname,
                  employees.employeeid AS employeeid,
                  employees.employeefileno AS employeefileno,
                  employees.employeenic AS employeenic,
                  employees.employee_tan_number AS employee_tan_number,
                  employees.employee_join_date AS joining_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,
                  periods.periodName AS monthName,
                  payrollbasicdetails.payrollid AS payrollid,
                  payrollbasicdetails.netSalary AS netSalary,
                  payrollbasicdetails.basicSal AS basicSal,
                  payrollbasicdetails.travellingAmt AS travellingAmt,
                  payrollbasicdetails.specialBonus AS specialBonus,
                  payrollbasicdetails.commission AS commission,
                  payrollbasicdetails.taxableAllowance AS taxableAllowance,
                  payrollbasicdetails.nonTaxableAllowance AS nonTaxableAllowance,
                  payrollbasicdetails.housingallowance AS housingAllowance,
                  payrollbasicdetails.telephoneallowance AS telephoneAllowance,
                  payrollbasicdetails.driverallowance AS driverAllowance,
                  payrollbasicdetails.otherallowance AS otherAllowance,
                  payrollbasicdetails.totalcarallowance AS totalcarallowance,
                  payrollbasicdetails.loan AS loan,
                  payrollbasicdetails.medical AS medical,
                  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.oneOffDeduction AS oneOffDeduction,
                  payrollbasicdetails.totalDed AS totalDed,
                  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
                  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
                  RIGHT JOIN periods
                  ON payrollbasicdetails.payrollid = periods.periodid
                  WHERE periods.startDate BETWEEN '$startdate' AND '$enddate'
                  AND periods.bonusBoolean = 0
                  AND employees.companyid = $companyID";

                  if (isset($getallemployees)) {

                  } else {
                    $sqlAddonEmployee = " AND payrollbasicdetails.employeeid = '$getemployeeid';";
                    $sqlView = $sqlView . $sqlAddonEmployee;                    
                  }

                  $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 START HERE
              
                  echo "<h1 class=\"h2\">Payslip Report - " . $startdate . " - " . $enddate . "
                  <a href = \"report-payslipByPeriod.php\">< Back</a>
                  </h1>";

                  if (isset($getallemployees)) {

                  } else {
                    echo " Single Employee ";
                  }


                  echo "</h1>";
             
              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

  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-intellect-design.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 "<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 = " . $rowpaysheet['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>";
      echo "<p>CSG:&#9;<b>" . number_format($rowpaysheet['employeeCSG'], 0, '.', ',') . "</b></p>";

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

      echo "<br><b>Total Deductions: " . number_format($totalDeductions, 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




    }


            } // COUNT EMPLOYEES END HERE


      }  else { ///////////////////

        include('header1.php');

  $sqlGetEmployee = "SELECT * FROM employees WHERE companyid = $companyID";

  $resultEmployee = mysqli_query($db,$sqlGetEmployee);

  $countEmployee = mysqli_num_rows($resultEmployee);

  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\">";


    	echo "<h1 class=\"h2\">Payslip by Period</h1>";
 
    
    	echo "</div>";

    	echo "<form method = \"POST\" action=\"report-payslipByPeriod.php\">";

      echo "<p>Start Date:<input type = \"date\" class=\"form-control\" name = \"startdate\"></p>";

      echo "<p>End Date:</p><input type = \"date\" class=\"form-control\" name = \"enddate\"></p>";

      echo "<p>All Employees <input type = \"checkbox\" name = \"getallemployees\"></p>";

      echo "<p>If Single Employee, Choose here:";

  if ($countEmployee !== 0) { 

    echo "<select name=\"getemployeeid\" id=\"getemployeeid\" class=\"form-control\">";

    while ($rowemployee = mysqli_fetch_array($resultEmployee)) {

      echo "<option value ='" . $rowemployee['employeeid'] . "'>" . $rowemployee['employeesurname'] . ", " . $rowemployee['employeename']  . "</option>";

    }

      echo "</select></p>";
} else {
  echo "<p>No employee on system..</p>";
}

    echo "<input type=\"submit\"> </form>";

   }



include('footer1.php');
?>