<?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');

$empCod=utf8_decode($_SESSION["empCod"]);
$empNom=utf8_decode($_SESSION["empNom"]);
$usuCod = utf8_decode($_SESSION['usuCod']);
$usuNom = utf8_decode($_SESSION['usuNom']);

$numAno=$_GET["numAno"];
$selMes=$_GET["selMes"];
$Mesnom=$_GET["Mesnom"];

# QUERYS
$sMaestro = "SELECT mae.*, TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape,
            TRIM(tpu.tpu_nom) AS tpu_nom, TRIM(gru.gru_nom) AS gru_nom, TRIM(dep.dep_nom) AS dep_nom
            FROM maestro mae
            LEFT JOIN grupo gru ON mae.mae_gru=gru.gru_cod LEFT JOIN dep dep ON mae.mae_dep=dep.dep_cod 
            LEFT JOIN tpuesto tpu ON mae.mae_tpue = tpu.tpu_cod 
            WHERE mae_emp='$empCod' AND mae_stat!='B' AND year(mae_fing)<$numAno AND month(mae_fing)=$selMes GROUP BY mae_cod ORDER BY mae_emp,mae_gru,mae_dep,mae_cod";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["maestro"] = $db->query($sMaestro);
$db->close();

/** 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['maestro']=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=3;
$objPHPExcel->setActiveSheetIndex($sheet['maestro'])
			->setCellValueByColumnAndRow($i, 1, utf8_decode($empNom))
			->setCellValueByColumnAndRow($i, 2, utf8_decode("LISTADO DE EMPLEADOS CON DERECHO A VACACIONES : ".$Mesnom."/".$numAno))
			->setCellValueByColumnAndRow($i++, $j, 'Grupo')
			->setCellValueByColumnAndRow($i++, $j, 'Departamento')
			->setCellValueByColumnAndRow($i++, $j, 'Codigo')
            ->setCellValueByColumnAndRow($i++, $j, 'Nombre Empleado')
            ->setCellValueByColumnAndRow($i++, $j, 'Puesto')
            ->setCellValueByColumnAndRow($i++, $j, 'Fecha/Ingreso');

# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'bold' => true,
        'size' => 13,
    ),
    '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' => 12,
    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    ),
	'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styTotales = array(
    'font' => array(
        'bold' => true,
        'size' => 12,
    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);


//foreach(range('A','F') as $colID) { 
//    $objPHPExcel->getActiveSheet()->getColumnDimension($colID)->setAutoSize(true); 
//} 

$objPHPExcel->getActiveSheet()->mergeCells('A1:F1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:F2')->getStyle('A2')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->getStyle('A3:F3')->applyFromArray($styEncabezado);

# VALORES PRIMER HOJA
$i=$iIni;
for ($j=4; $rec = $db->fetchAssoc($select['maestro']); $j++) {
	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, utf8_encode($rec['gru_nom']))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode($rec['dep_nom']))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode($rec['mae_cod']))
                ->setCellValueByColumnAndRow($i++, $j, utf8_encode($rec['mae_nom']." ".$rec['mae_ape']))
                ->setCellValueByColumnAndRow($i++, $j, utf8_encode($rec['tpu_nom']))
                ->setCellValueByColumnAndRow($i++, $j, strftime("%d/%m/%Y", strtotime($rec["mae_fing"])));
	$i=$iIni;
}
$i=$iIni;

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(17);

$objPHPExcel->getActiveSheet()->getStyle('A4'.':E'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

# ESTABLECER TITULOS
$objPHPExcel->setActiveSheetIndex($sheet['maestro'])->setTitle('ListadoVaca');

# 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="LisVaca.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;

?>