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

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

  include('connect.php');
  
  $companyID = $_SESSION['companyselect'];

  $periodid = $_POST['periodid'];

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

  $yearOfPeriod = "0000";
  $monthOfPeriod = "00";
  $periodDateData = "";

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

  $countPayroll = mysqli_num_rows($resultPayroll);

  if ($countPayroll != 0) {

    while ($rowPayrollData = mysqli_fetch_array($resultPayroll)) {

      $dateextract = strtotime($rowPayrollData['endDate']);
      $yearOfPeriod = date("Y",$dateextract);
      $monthOfPeriod = date("m",$dateextract);
      $periodDateData = $yearOfPeriod . $monthOfPeriod;

    }

}

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

    $updated = $_GET['updated'];

  }

  $sqlView = "SELECT 
  employees.employeename AS employeename,
  employees.employeesurname AS employeesurname,
  employees.employeenic AS employeenic,
  employees.employee_fulltime_boolean AS employeefulltime,
  employees.employee_contribution_code AS employeeccode,          
  employees.employee_join_date AS joinDate,
  employees.employee_termination_date AS terminationDate,
  payrollbasicdetails.basicSal AS basicSal,
  payrollbasicdetails.netSalary AS netSalary,
  payrollbasicdetails.employerLEVY AS employerLEVY,
  periods.startDate AS startDate,
  periods.endDate AS endDate
  FROM payrollbasicdetails
  LEFT JOIN employees
  ON payrollbasicdetails.employeeid = employees.employeeid
  LEFT JOIN periods
  ON payrollbasicdetails.payrollid = periods.periodid
  WHERE payrollbasicdetails.payrollid = $periodid";

  /*
    $sqlView = "SELECT 
          employees.employeename AS employeename,
          employees.employeesurname AS employeesurname,
          employees.employeenic AS employeenic,
          employees.employee_fulltime_boolean AS employeefulltime,
          employees.employee_contribution_code AS employeeccode,
          payrollbasicdetails.basicSal AS basicSal
          FROM payrollbasicdetails
          LEFT JOIN employees
          ON payrollbasicdetails.employeeid = employees.employeeid
          WHERE payrollbasicdetails.payrollid = $periodid
          AND employees.companyid = $companyID";
  */
  
    $result = mysqli_query($db,$sqlView);

    $count = mysqli_num_rows($result);

    if ($count != 0) {

      //The name of the CSV file that will be downloaded by the user.
    $fileName = 'csg-return.csv';
     
    //Set the Content-Type and Content-Disposition headers.
    header('Content-Type: application/excel');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');

    $data = array();
    $data1 = array();

    $sqlViewCompanyFile = "SELECT *
      FROM companyfile WHERE companyid = $companyID";
  
      $resultCompanyFile = mysqli_query($db,$sqlViewCompanyFile);

      $totalBasic = 0;
      $totalEmployerLevy = 0;
// total emoluments loop starts

while ($rowpayroll = mysqli_fetch_array($result)) { 

  $startDateForPeriod = $rowpayroll['startDate'];
  $endDateForPeriod = $rowpayroll['endDate'];

  $employeeJoin = $rowpayroll['joinDate'];
$employeeTermination = $rowpayroll['terminationDate'];

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

$totalBasic += $rowpayroll['basicSal'];
$totalEmployerLevy += $rowpayroll['employerLEVY'];

$csgEmployee = getCSGEmployee(intval($rowpayroll['basicSal']),$db);
  $csgEmployer = getCSGEmployer(intval($rowpayroll['basicSal']),$db);
   array_push($data, 
    array(
      $rowpayroll['employeenic'], 
      $rowpayroll['employeename'], 
      $rowpayroll['employeesurname'],
      number_format($rowpayroll['basicSal'], 0, '.', ''),
      number_format($rowpayroll['basicSal'], 0, '.', ''),
      $rowpayroll['employeeccode'],"M","1","Y","0"));

}

// total emoluments loop ends

while ($rowCompanyFile = mysqli_fetch_array($resultCompanyFile)) {

  array_push($data1, array("CSGINFO",$rowCompanyFile['companyERN'],$rowCompanyFile['companyName'],$periodDateData,number_format($totalBasic, 0, '.', ''),number_format($totalEmployerLevy, 0, '.', ''),$rowCompanyFile['accountantEmail'],$rowCompanyFile['accountantPNumber'],$rowCompanyFile['accountantMNumber'],$rowCompanyFile['accountantName'],"Accountant"));
 }

       
    //Open up a PHP output stream using the function fopen.
		$fp = fopen('php://output', 'w');
    foreach ($data1 as $row1) {
      //fputcsv formats the array into a CSV format.
      //It then writes the result to our output stream.
      fputcsv($fp, $row1);
  }
		//Loop through the array containing our CSV data.
		foreach ($data as $row) {
		    //fputcsv formats the array into a CSV format.
		    //It then writes the result to our output stream.
		    fputcsv($fp, $row);
		}
		 
		//Close the file handle.
		fclose($fp);
    }


 

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

   include('header1.php');
   include('ietpartial.php');

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

  $sqlGetPeriods = "SELECT * FROM periods WHERE companyid = $companyID";

  $resultPeriods = mysqli_query($db,$sqlGetPeriods);

  $countPeriods = mysqli_num_rows($resultPeriods);

  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\">Get CSG csv file for Specific Period</h1>";
 
    
    	echo "</div>";

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

      echo "<p>Select Period:";

        if ($countPeriods !== 0) { 

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

    while ($rowperiod = mysqli_fetch_array($resultPeriods)) {

      echo "<option value ='" . $rowperiod['periodid'] . "'>" . $rowperiod['periodName'] . "</option>";

    }

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

     

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

    include('footer1.php');

   }




?>