<?php
/**
 * PHPExcel
 *
 * Copyright (C) 2006 - 2013 PHPExcel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category   PHPExcel
 * @package    PHPExcel
 * @copyright  Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
 * @version    1.7.9, 2013-06-02
 */

/** Error reporting */

$keyword=$_REQUEST['keyword'];
$cl=new MY_HTML();

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Asia/Tokyo');

if (PHP_SAPI == 'cli')
	die('This example should only be run from a Web Browser');

/** Include PHPExcel */

require_once 'Classes/PHPExcel.php';
if(preg_match("/^windows/i",strtolower(php_uname()))){PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);}

// === Init Vars
$ismonthly=$_REQUEST['ismonthly'];
$month=$_REQUEST['month'];
$period=$_REQUEST['period'];
$idemployee=$_REQUEST['idemployee'];
$idsubunit=$_REQUEST['idsubunit'];
            
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();

// My data
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1','Employee Leave Reporting')
            ->setCellValue('A2','Human Capital '.$_SESSION['employeename'])
            ->setCellValue('A3','Date Reporting : '.date("d/m/Y H:i:s"))
            ->setCellValue('A4','Periode : '.$period);


if($idsubunit)
{
    $subunitname=$cl->fn_get_fieldvalue("subunitname","select subunitname from ".DB_APORTIL.".tbl_employee_subunit where id='$idsubunit'");
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A5','Sub Unit : '.$subunitname);
}
            

//  set format cell
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);


// Print Header
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A7','No')
            ->setCellValue('B7','Nik')
            ->setCellValue('C7','Employee Name')
            ->setCellValue('D7','Subunit')
            ;
$style = array(
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
    )
);
            
$objPHPExcel->getActiveSheet()->mergeCells('A7:A8');
$objPHPExcel->getActiveSheet()->getStyle('A7:A8')->applyFromArray($style);
$objPHPExcel->getActiveSheet()->mergeCells('B7:B8');
$objPHPExcel->getActiveSheet()->getStyle('B7:B8')->applyFromArray($style);
$objPHPExcel->getActiveSheet()->mergeCells('C7:C8');
$objPHPExcel->getActiveSheet()->getStyle('C7:C8')->applyFromArray($style);
$objPHPExcel->getActiveSheet()->mergeCells('D7:D8');
$objPHPExcel->getActiveSheet()->getStyle('D7:D8')->applyFromArray($style);

$arrheader=array();$qryheader="";$qrydetail="";
$qry="select distinct leavetype from tbl_hcm_leavetype where isdeleted=0";
$rs=$cl->selectquery($qry);
if($rs)
{
    $i=0;$startcol=69;$endcol=71;
    while($rw=$cl->data_row_object($rs))
    {
        //$html.="<th colspan='3' valign='top' width='90px' style='text-align:center;border-bottom:1px dotted black;border-right:1px dotted black'>".$rw->leavetype."</th>";
        $objPHPExcel->getActiveSheet()->mergeCells(chr($startcol).'7:'.chr($endcol).'7');
        $objPHPExcel->getActiveSheet()->getStyle(chr($startcol).'7:'.chr($endcol).'7')->applyFromArray($style);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue(chr($startcol).'7',$rw->leavetype);

        $arrheader[$i]=$rw->leavetype;
        $i+=1;$startcol+=3;$endcol+=3;
    }
}
$x1=69;$x2=70;$x3=71;$j=0;
for($i=0;$i<count($arrheader);$i++)
{
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue(chr($x1).'8','Tot');
    $objPHPExcel->getActiveSheet()->getStyle(chr($x1).'8:'.chr($x1).'8')->applyFromArray($style);
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue(chr($x2).'8','LV');
    $objPHPExcel->getActiveSheet()->getStyle(chr($x2).'8:'.chr($x2).'8')->applyFromArray($style);
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue(chr($x3).'8','Cr');
    $objPHPExcel->getActiveSheet()->getStyle(chr($x3).'8:'.chr($x3).'8')->applyFromArray($style);
    $objPHPExcel->cellColor(chr($x1).'8:'.chr($x3).'8',"bdc3c7");
    $x1+=3;$x2+=3;$x3+=3;
    // === // qry detail
    $qrydetail.="case when l.leavetype='".$arrheader[$i]."' then l.leave_total else 0 end tt$j,";
    //$qrydetail.="case when l.leavetype='".$arrheader[$i]."' and not(d.hcmdurationdays is null) then sum(d.hcmdurationdays) else 0 end t$j,";
    
    //$qryheader.="sum(x.tt$j) tt$j,sum(x.t$j) t$j,";
    $qryheader.="sum(x.tt$j) tt$j,";
    $j+=1;
} 
$qryheader=substr($qryheader,0,strlen($qryheader)-1);
$qrydetail=substr($qrydetail,0,strlen($qrydetail)-1);                          

// === Merge Cells
$objPHPExcel->getActiveSheet()->getStyle('E7:'.chr($endcol-3).'7')->getFont()->getColor()->setRGB('ffffff');
// Worksheet Name
$objPHPExcel->getActiveSheet()->setTitle('LEAVEINFO_'.date("Ym"));

// === Set Background Cell
$objPHPExcel->cellColor("E7:".chr($endcol-3)."7","938e8e");

// === set Column Width A
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(6);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);
$objPHPExcel->setActiveSheetIndex(0);

// === Data
$swhere="";
if($idemployee){$swhere="e.id='$idemployee' and ";}
if($idsubunit){$swhere.="e.idsubunit='$idsubunit' and ";}
$qry="select id,nik,fullname,idempgroup,subunitname,idgender 
     from ".DB_APORTIL.".tbl_employee where $swhere isdeleted=0 
     order by bandposition,objidposition asc";  
$qry="select x.id idemployee,x.nik,x.fullname,x.subunitname,x.idgender,x.bandposition,x.objidposition,
            $qryheader
      from
      (
          select e.id,e.nik,e.fullname,e.subunitname,e.bandposition,e.objidposition,e.idgender,$qrydetail
          from (tbl_employee e inner join tbl_hcm_leavetype l on e.idempgroup=l.idempgroup)     
          where $swhere e.isdeleted=0
          order by e.bandposition,e.objidposition asc
      ) x group by x.id,x.nik,x.fullname
      order by x.bandposition,x.objidposition asc";

$rsrpt=$cl->selectquery($qry);
if($rsrpt)
{
    $j=1;$n=9;
    while($rw=$cl->data_row_array($rsrpt))
    {
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$n,$j)
                                    ->setCellValue('B'.$n,$rw["nik"])
                                    ->setCellValue('C'.$n,$rw["fullname"])
                                    ->setCellValue('D'.$n,$rw["subunitname"]);
        $x1=69;$x2=70;$x3=71;
        for($i=0;$i<count($arrheader);$i++)
        {
            //echo $arrheader[$i];
            //echo $rw->id
            $total=$rw["tt".$i];
            $swheremonth="";
            if($month){$swheremonth="and month(startdate)=$month";}

            $qrytake="select sum(hcmdurationdays) take 
                      from ".DB_APORTIL.".tbl_hcm_leavedata
                      where idemployee='".$rw['idemployee']."' and leavetype='".$arrheader[$i]."'
                            and period='$period' and isdeleted=0 and status>=-1 $swheremonth";
            //echo $qrytake."</br>";
            $take=$cl->fn_get_fieldvalue("take",$qrytake);
            if(!$take){$take=0;}
            //$take=$rw1["t".$i];
            $credit=$total-$take;
            //$credit=$rw1["tt".$i]-$rw1["t".$i];
            if($arrheader[$i]=="Maternity"&&$rw['idgender']==1){
                $total=0;$take=0;$credit=0;    
            }
            $color="black";
            if($credit<0){$color="red";}

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue(chr($x1).$n,$total)
                                                ->setCellValue(chr($x2).$n,$take)
                                                ->setCellValue(chr($x3).$n,$credit);
            $colors="000000";
            if($credit<0){$colors="FF0000";}
            $phpColor = new PHPExcel_Style_Color();
            $phpColor->setRGB($colors);

            $objPHPExcel->getActiveSheet()->getStyle(chr($x3).$n)->getFont()->setColor($phpColor);
            $x1+=3;$x2+=3;$x3+=3;

        }
        $j+=1;
        $n+=1;
    }
                        
}
// Redirect output to a web browser (Excel2007)
//header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="HCM_LEAVEINFO.xls"');
header('Cache-Control: max-age=0');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>
