<?php 
session_start();
error_reporting(1);

require_once('includes/functions.php');

$DB_HOST = "localhost";
  $DB_USER = "oscotech_onlineo";
  $DB_PASS = "onlineoscotechpayroll";
  $DB_NAME = "oscotech_onlineoscotechpayroll";
  
  $conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
  
if ($conn){
//echo "Connected to remote DB";   
}else{
    
    echo "Not Connected".mysqli_error();
}
//echo "Full Time";

 if (($_POST['month']=='') or ($_POST['year']=='')){
     redirect_to('https://payslip.oscotechesaoke.edu.ng/home.php?error=1');
 }
  $month =  $_POST['month'];
   $year =  $_POST['year'];
   $staffid=$_SESSION['staffid'];

require_once('tcpdf/config/tcpdf_config.php');
require_once('tcpdf/tcpdf.php');
   //echo "test";
   // create new PDF document

class pdf extends TCPDF
{
    public function Header()
    {
     $imageFile='images/icon.jpg'; 
     $this->Image($imageFile,30,6,17,'','','','T',false,300,'',false,false,0,false,false,false);
     $this->SetFont('helvetica','B',14);
     $this->Cell(0,10,'OSUN STATE COLLEGE OF TECHNOLOGY, ESA-OKE',0,1,'C');
     $this->SetFont('helvetica','',12);
     $this->Cell(0,6,'P.M.B 1011, ESA-OKE',0,1,'C');
     $this->Cell(0,6,'OSUN STATE',0,1,'C');
    
    }
}

// //$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
   
   $pdf = new pdf('p', 'mm', 'A4', true, 'UTF-8', false);
   
//   // set document information
  $pdf->SetCreator(PDF_CREATOR);
  $pdf->SetAuthor('Bamigbola Adeyemi');
  $pdf->SetTitle('OSCOTECH Staff Epayslip');
  $pdf->SetSubject('');
  $pdf->SetKeywords('');
   
  // set default header data
  $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
   
  // set header and footer fonts
  $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
   
  // set default monospaced font
  $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
   
  // set margins
  $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
  $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
  $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
   
  // set auto page breaks
  $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
   
//   // set image scale factor
//   //  $pdf->Image('../images/icon.png',20,60,180,20,'JPG');
   $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// //    $pdf->Image('../images/osco.png',20,60,180,20,'PNG');
// //    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
   
   
//   // set some language-dependent strings (optional)
  if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
      require_once(dirname(__FILE__).'/lang/eng.php');
      $pdf->setLanguageArray($l);
  }
   
//   // ---------------------------------------------------------
   
//   // set font
  $pdf->SetFont('helvetica', 'B', 12);
  
  global $conn;
  global $staffid;
  global $month;
  global $year; 
  
  
  $pdf->AddPage();

  $x=60; $y=10;

   
  $pdf->setColor(0,0,0);
  $pdf->Write(0, 'MONTHLY PAYSLIP', '', 0, 'C', true, 0, false, false, 0);
  $pdf->ln(5);
  $pdf->SetFont('helvetica', '', 8);
   
   
//   //$tbl='';
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }else{
    // echo "Connected successfully";

    // $month=date("m",strtotime($date));
  //$year=date("Y",strtotime($date));


  mysqli_select_db($conn, 'onlineoscotechpayroll');
  
  $paygrade='';
  $basic='';
  $rent='';
  $gross='';
  $sql=$conn->query("SELECT * FROM stbiodata WHERE staffid='$staffid' LIMIT 1");
    while($row=mysqli_fetch_array($sql))
    {

     $bid=$row['id'];
     
     $name = str_replace(' ', '', $row['fullname']);

     if ((($row['poorate'])!=0) AND ($month==date("m",strtotime($row['dpoorate']))) AND ($year==date("Y",strtotime($row['dpoorate'])))){

          $poo=$conn->query("SELECT * FROM poorate WHERE stbiodataid=$bid AND month(date)=$month AND year(date)=$year LIMIT 1");

          if (mysqli_num_rows($poo)<=0){

             //  echo "go to stbiodata";




          }else{
           
              while($rpoo=mysqli_fetch_array($poo)){
                    
                  $basic=$rpoo['basic'];
                 $rent=$rpoo['rent'];
                 $paygrade=$row['paygrade'];
     
                 $formattedbasic=number_format($basic,2,'.',',');

                $formattedrent=number_format($rent,2,'.',',');
              }
              
     }

    }
    

    
    // else if ($row['promotion']==1){

    // $pro=$conn->query("SELECT * FROM prevpromotion WHERE staffid='$staffid' AND month(date)=$month AND year(date)=$year LIMIT 1");

    //  if (mysqli_num_rows($pro)<=0){
         
     

    // }else{

    //  while($promo=mysqli_fetch_array($pro)){

    //     $paygrade=$promo['paygrade'];
    //     }
   
    //   }
        
    // }
         
  else{
     $prom=$conn->query("SELECT * FROM staff_history WHERE staffid='$staffid' AND month(date)=$month AND year(date)=$year LIMIT 1");

     if (mysqli_num_rows($prom)<=0){

    }else{

     while($promo=mysqli_fetch_array($prom)){

        $paygrade=$promo['paygrade'];
        $staffdesignation=$promo['designation'];
     }
    }

    }
    
    }
    
  } 
    
    
  
   $sql=$conn->query("SELECT s.staffid,s.fullname,s.paygrade,s.deptid,s.status,s.retired, p.designation,p.id,  d.department, b.bankname,b.accountnumber,b.pfa,b.pennumber 
   FROM staff_history s INNER JOIN departments d ON s.deptid=d.id INNER JOIN fin b 
   ON s.staffid=b.holdername INNER JOIN stbiodata p ON s.staffid=p.staffid WHERE s.staffid='$staffid' LIMIT 1");

  if (!$sql){
    //echo "Invalid inputs, try again";
  }else{

//     // global $date;

  // $month=date("m",strtotime($date));
  //$year=date("Y",strtotime($date));
   // $month=trim($month);
if ($month=='01'){
    $monthinwords ='JANUARY';
}else if ($month=='02'){
    
     $monthinwords ='FEBRUARY';
}else if ($month=='03'){
    
     $monthinwords ='MARCH';
}else if ($month=='04'){
     $monthinwords ='APRIL';
}else if ($month=='05'){
     $monthinwords ='MAY';
}else if ($month=='06'){
     $monthinwords ='JUNE';
}else if ($month=='07'){
     $monthinwords ='JULY';
}else if ($month=='08'){
     $monthinwords ='AUGUST';
}else if ($month=='09'){
     $monthinwords ='SEPTEMBER';
}else if ($month=='10'){
     $monthinwords ='OCTOBER';
}else if ($month=='11'){
     $monthinwords ='NOVEMBER';
}else if ($month=='12'){
     $monthinwords ='DECEMBER';
}






    
    //echo $monthinwords;

 // echo "LK".$mt = short_month_converter($month);

     $d= $monthinwords.' / '.$year;
    
 $name=$name.$monthinwords.$year.'Epayslip';

  if (mysqli_num_rows($sql)<=0){

     header("Location: https://payslip.oscotechesaoke.edu.ng/home.php");
     exit;
    
  }else{



   
    while($row=mysqli_fetch_array($sql))
    {
         $row['phone'];
        $fullname=strtoupper($row['fullname']);
      
       
         $dept=strtoupper($row['department']);
         if (!empty($staffdesignation)){
        
            $designation=strtoupper($staffdesignation);
            }else{
                $designation='';

               
                          }
     $status=$row['status'];

     if ($paygrade==''){
          $paygrade=$row['paygrade'];
     }
    
      $bank=strtoupper($row['bankname']);
      $acct=$row['accountnumber'];

      $pfa=strtoupper($row['pfa']);
      $pennumber=strtoupper($row['pennumber']);

      $biodataid=$row['id'];
          }
      
          }
  


$pdf->SetFont('helvetica', '', 11);

// // -----------------------------------------------------------------------------


$tbl=<<<EOD
         <table cellspacing="0" cellpadding="1" border="1" background-image="images/oscoimg.jpg"  style="width:100%;">
            
              <tr >
                 <td background="http://localhost/oscotechpayroll/images/oscoimg.png">
                      <table cellspacing="0" cellpadding="1" border="0" style="width:100%">
                          <tr style="height:20; font-size:14px; font-weight:bolder">
                                <td style="width:30%">NAME</td>
                                <td style="width:70%">$fullname</td>
                          </tr>
                          <tr style="height:20; font-size:12px">
                                <td style="width:30%">STAFF ID</td>
                                <td style="width:25%">:{$staffid}</td>
                                <td style="width:30%">GRADE LEVEL: </td>
                                <td style="width:15%">{$paygrade} </td>
                          </tr>
                          <tr style="height:20; font-size:12px">
                                <td style="width:30%">POST HELD</td>
                                <td style="width:70%">:{$designation}</td>
                          </tr>
                          <tr style="height:20; font-size:12px">
                          <td style="width:30%">BANK NAME</td>
                                <td style="width:70%">:{$bank}</td>
                         </tr>


                                <tr style="height:20; font-size:12px">
                                <td style="width:30%">PFA</td>
                                     <td style="width:70%">:{$pfa}</td>
                          </tr>
                    </table>
                </td>
                <td>
                      <table cellspacing="0" cellpadding="1" border="0" style="width:100%">
                          <tr style="line-height:22px; font-size:12px">
                                <td style="width:30%">DEPT</td>
                                <td style="width:70%">:{$dept}</td>
                          </tr>
                          <tr  style="line-height:22px; font-size:12px">
                                <td style="width:30%">MONTH/YEAR</td>
                                <td style="width:70%">:{$d}</td> 
                          </tr>
                          <tr  style="line-height:22px; font-size:12px">
                                <td style="width:30%">ACCT NUMBER</td>
                                <td style="width:70%">:{$acct}</td>
                          </tr>

                          <tr  style="line-height:22px; font-size:12px">
                          <td style="width:30%">PEN NUMBER</td>
                          <td style="width:70%">:{$pennumber}</td>
                         </tr>
                    </table>
                </td>
            </tr>
            <tr>
            <td style="line-height:20px;">
            <table cellspacing="0" cellpadding="1" border="0" style="position:relative"> 
            <tr style="border-top:2px solid black; line-height:10px;">
            <td  align="left" style="width:50%;background-color:white; position:absolute;top:10px;color:black; font-weight:bolder">EARNING DETAILS</td>
            <td  align="right"style="background-color:white; color:black; font-weight:bolder">AMOUNT (N)</td>
            </tr>
            <hr>
       
EOD;

$totalearnings=0; 

if (($basic=='') and ($rent=='')){
$bas=$conn->query("SELECT s.* from conpcass_contediss s INNER JOIN staff_history d ON s.gl=d.paygrade WHERE s.status=$status AND s.gl=$paygrade LIMIT 1"); 
if ($gl=mysqli_fetch_array($bas))
{
     $basic=$gl['basic'];
     $rent=$gl['rent'];
     
     $formattedbasic=number_format($basic,2,'.',',');

     $formattedrent=number_format($rent,2,'.',',');
  
}

}

$tbl.=<<<EOD
      <tr>
       <td align="left" style="background-color:white;line-height:10px; color:black;">BASIC</td>  <td  align="right">{$formattedbasic}</td>
      </tr>   

      <tr>
      <td align="left" style="background-color:white;line-height:10px; color:black;">RENT</td>  <td  align="right">{$formattedrent}</td>
     </tr>   
EOD;

$pdf->SetFont('helvetica', '', 9);
$sq=$conn->query("SELECT * from earnings");
$totalamount=0;
while($ear=mysqli_fetch_array($sq)){
  
    $nam= strtoupper($ear['name']);
    $id=$ear['id'];
   // echo $staffid;
     $earninid=$conn->query("SELECT *  FROM addedearnings  WHERE stbiodataid=$biodataid AND earningsid= $id AND month(date)=$month AND year(date)=$year "); 
     while($addedearnings=mysqli_fetch_array($earninid)){ 
          if (isset($addedearnings['id'])){
             
               $amount=$addedearnings['amount'];
               $totalamount+=$amount;

          }else {
               
               $amount=0.00;
          }
     //$nam= ucwords($row['name']);
     $formattedamount=number_format($amount,2,'.',',');
     
     $tbl.=<<<EOD
     <tr >
      <td align="left" style="background-color:white;line-height:20px; color:black;">{$nam}</td>  <td  align="right">{$formattedamount}</td>
     </tr>   
EOD;
        
     }
}
$totalearnings=$totalamount+$basic+$rent;
$formattedtotalearnings=number_format($totalearnings,2,'.',',');
$tbl.=<<<EOD
</table>

 </td>
            
            <td style="background-color:white;line-height:20px; color:black">
            <table cellspacing="0" cellpadding="1" border="0" style=" margin-left:0">
            <tr style="font-weight:bolder; margin-top:10px;line-height:10px;">
            <td align="left" width:"200px" >DEDUCTIONS</td>
            <td  align="right width:30%">AMOUNT (N)</td>
            
            </tr>  
            <hr>
                
EOD;
$pdf->SetFont('helvetica', '', 9);

   $totalamount=0;

   $earninid=$conn->query("SELECT *  FROM addeddeduction  WHERE stbiodataid=$biodataid AND month(date)=$month AND year(date)=$year order by status"); 
  while ($addedearnings = mysqli_fetch_array($earninid)){ 

          if (isset($addedearnings['id'])){
               $dnam= strtoupper($addedearnings['dname']);
               $amount=$addedearnings['amount'];
               $totaldeduct+=$amount;
               $disp_amount=number_format($amount,2,'.',',');

          }else {
               
               // $amount=0.00;
          }
          
 $tbl.=<<<EOD
          <tr >
         <td align="left" style="background-color:white;line-height:20px; color:black;">{$dnam}</td>  <td  align="right">{$disp_amount}</td>
        </tr>   
EOD;
    
        } 
     
     
 $net=0;
$net=$totalearnings-$totaldeduct;


$formattedtotaldeduct=number_format($totaldeduct,2,'.',',');
$formattednet=number_format($net,2,'.',',');


$tbl.=<<<EOD
            </table>
            </td>
            </tr>
          
          <tr>
          <td>
          <table border="0" cellspacing="0" cellpadding="1" style="font-weight:bolder;line-height:20px">
          <tr>
          <td>GROSSPAY</td>
          <td align="right">{$formattedtotalearnings}</td>
          </tr>
          </table>
          </td>

          <td>
          <table border="0" cellspacing="0" cellpadding="1" style="font-weight:bolder; line-height:20px">
          <tr>
          <td  align="left" style"float left">TOTAL DEDUCTIONS</td>
          <td align="right">{$formattedtotaldeduct}</td>
          </tr>
          </table>
          </td>
          </tr>



          <tr>
          <td>
          <table border="0" cellspacing="0" cellpadding="1" style="font-weight:bolder;line-height:20px">
          <tr>
          <td></td>
          <td align="right"></td>
          </tr>
          </table>
          </td>

          <td>
          <table border="0" cellspacing="0" cellpadding="1" style="font-weight:bolder; line-height:20px">
          <tr>
          <td  align="left" style"border:2px solid black; float left">NET/PAYABLE</td>
          <td align="right">{$formattednet}</td>
          </tr>
          </table>
          </td>
          </tr>
          <tr>
          <td colspan="2" align="center">Any alteration on this payslip rendered it invalid</td>
          </tr>
            

          
        
            
         </table>  
EOD;
 
      
    // $number=90;    
   
 $pdf->writeHTML($tbl, true, false, false, false, '');
 


  
      
    
         
 }

//}

$pdf->Output($name.'.pdf', 'I');
   
//============================================================+
// END OF FILE
//============================================================+ 
 	
?>