<?php
/**
 * PHPExcel
 *
 * Copyright (c) 2006 - 2015 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 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
 * @version    ##VERSION##, ##DATE##
 */

include_once("../../../php/sessionStart.php");
include_once("../../../php/db/dbExec.php");
include_once('../../../php/maxExecTime.php');
include_once('../../../php/functions.php');
include_once("../../../php/fpdf/functions.php");

$empCod=utf8_decode($_SESSION["empCod"]);
$empNom=utf8_decode($_SESSION["empNom"]);
$empMoneda=utf8_decode($_SESSION["empMoneda"]);
$empTcam=utf8_decode($_SESSION["pTcam"]);

$numNum=$_GET["numNum"];
$dtDel=$_GET["dtDel"];
$dtAl=$_GET["dtAl"];

# QUERYS
$sAnti = "SELECT *, TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape,
                TRIM(gru.gru_nom) AS gru_nom, TRIM(dep.dep_nom) AS dep_nom
                FROM antipla ant
                LEFT JOIN maestro mae ON ant.ant_emp=mae.mae_emp AND ant.ant_cod = mae.mae_cod 
                LEFT JOIN tpuesto tpu ON mae.mae_tpue = tpu.tpu_cod 
                LEFT JOIN grupo gru ON mae.mae_emp=gru.gru_emp AND mae.mae_gru = gru.gru_cod 
                LEFT JOIN dep dep ON mae.mae_emp=dep.dep_emp AND mae.mae_dep = dep.dep_cod 
                WHERE ant_emp='$empCod' AND ant_numpla='$numNum' ORDER BY ant_emp,mae_gru,mae_dep,ant_cod";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["antipla"] = $db->query($sAnti);

$func = new functions();

/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');

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

require_once dirname(__FILE__) . '/../../../php/PHPExcel/Classes/PHPExcel.php';

$iIni=0;
$objPHPExcel = new PHPExcel();

# CREAR HOJAS
for ($i=0; $i < 1; $i++) { 
	$objPHPExcel->createSheet();
}

# HOJAS
$sheet['antipla']=0;

# ESTABLECER PROPIEDADES DEL DOCUMENTO
$objPHPExcel->getProperties()->setCreator("Asesoría en Sistemas, S.A.")
						->setLastModifiedBy("Asesoría en Sistemas, S.A.")
						->setTitle("Office 2007 XLSX Test Document")
						->setSubject("Office 2007 XLSX Test Document")
						->setDescription("")
						->setKeywords("office 2007 openxml php")
						->setCategory("Contabilidad General");

# ENCABEZADO PRIMER HOJA
$i=$iIni;
$j=5;
$objPHPExcel->setActiveSheetIndex($sheet['antipla'])
			->setCellValueByColumnAndRow($i, 1, $empNom)
			->setCellValueByColumnAndRow($i, 2, utf8_decode("Reporte de Anticipos a planilla"))
			->setCellValueByColumnAndRow($i, 3, utf8_decode("Correpondiente a la planilla No. ".$numNum."  Del ".strftime("%d/%m/%Y", strtotime($dtDel))." al ".strftime("%d/%m/%Y", strtotime($dtAl))))
			->setCellValueByColumnAndRow($i++, $j, 'CODIGO')
			->setCellValueByColumnAndRow($i++, $j, 'NOMBRE DEL EMPLEADO')
			->setCellValueByColumnAndRow($i++, $j, 'DIAS TRAB')
			->setCellValueByColumnAndRow($i++, $j, 'ANTICIPO');

# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'bold' => true,
        'size' => 12,
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styFec = array(
	'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styEncabezado = array(
    'font' => array(
        'bold' => true,
        'size' => 9,
        //'color' => array('rgb' => '001a57')
    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),
	'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
);

$styLineas = array(
    'font' => array(
        'bold' => false,
        'size' => 9,
    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);
//foreach(range('A','I') as $colID) { 
//    $objPHPExcel->getActiveSheet()->getColumnDimension($colID)->setAutoSize(true); 
//}

$objPHPExcel->getActiveSheet()->mergeCells('A1:D1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:D2')->getStyle('A2')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A3:D3')->getStyle('A3')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->getStyle('A5:D5')->applyFromArray($styEncabezado);

$grupop=99999;
$depp=99999;
$t_lini=1;
$inigru=1;
$initot=6;
# VALORES PRIMER HOJA
$i=$iIni;
$j=6;
$inigru=6;
while ($rec = $db->fetchAssoc($select["antipla"])) {
    if (($rec["mae_gru"].$rec["mae_dep"]) != ($grupop.$depp)) {
        if ($t_lini > 1) {
        	$i=$iIni;
			$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, "")
				->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE DEPARTAMENTO")
			    ->setCellValueByColumnAndRow($i++, $j, "")
			    ->setCellValueByColumnAndRow($i++, $j, '=SUM(D'.$inigru.':D'.($j-1).')');
		    $objPHPExcel->getActiveSheet()->getStyle('C'.$j.':D'.$j)->applyFromArray($styEncabezado);
            $j+=2;
        }
       	$i=$iIni;
		$objPHPExcel->getActiveSheet()
			->setCellValueByColumnAndRow($i++, $j, "GRUPO Y DEPARTAMENTO: ".$rec["gru_nom"].", ".$rec["dep_nom"]);

       $grupop=$rec["mae_gru"];
       $depp=$rec["mae_dep"];
       $j+=1;
       $t_lini=2;
       $inigru=$j;
    }
    $nomp=$rec["mae_nom"]." ".$rec["mae_ape"];

   	$i=$iIni;
	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, $rec["ant_cod"])
				->setCellValueByColumnAndRow($i++, $j, $nomp)
				->setCellValueByColumnAndRow($i++, $j, $rec['ant_dtra'])
				->setCellValueByColumnAndRow($i++, $j, $rec['ant_sord']);
    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':D'.$j)->applyFromArray($styLineas);
	$i=$iIni;
	$j+=1;
}
$i=$iIni;
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE DEPARTAMENTO")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(D'.$inigru.':D'.($j-1).')');
$objPHPExcel->getActiveSheet()->getStyle('C'.$j.':D'.$j)->applyFromArray($styEncabezado);

$i=$iIni;
$j+=1;
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++, $j, "")
	->setCellValueByColumnAndRow($i++, $j, "    TOTAL GENERAL")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B6:B'.($j-1).',"    SUBTOTAL DE ESTE DEPARTAMENTO",D6:D'.($j-1).')');
$objPHPExcel->getActiveSheet()->getStyle('D'.$j.':D'.$j)->applyFromArray($styEncabezado);


$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);

$objPHPExcel->getActiveSheet()->getStyle('C6'.':D'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A6'.':B'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

# ESTABLECER TITULOS
$objPHPExcel->setActiveSheetIndex($sheet['antipla'])->setTitle('Anticipos Planilla');

# AL ABRIR EL DOCUMENTO ABRIR EN PRIMERA HOJA
$objPHPExcel->setActiveSheetIndex(0);


// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Anticipospla.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

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