<?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 = $_SESSION['empCod'];
$empNom = $_SESSION['empNom'];

$crStat=$_GET["crStat"];
if ($crStat=='T') {
	$statnom='Todos';
}
if ($crStat=='A') {
	$statnom='Solo de Alta';
}
if ($crStat=='B') {
	$statnom='Solo de Baja';
}

# QUERYS
if ($crStat=='T') {
    $sMaestro = "SELECT *,
                TRIM(m.mae_nom) AS mae_nom,
                TRIM(m.mae_ape) AS mae_ape,
                trim(gru.gru_nom) AS gru_nom,
                trim(dep.dep_nom) AS dep_nom,
                trim(tt.tt_nom) AS tt_nom
                FROM maestro m 
                LEFT JOIN grupo gru ON m.mae_gru=gru.gru_cod 
                LEFT JOIN dep dep ON m.mae_dep=dep.dep_cod 
                LEFT JOIN tpuesto tp ON m.mae_tpue=tp.tpu_cod 
                LEFT JOIN ecivil ec ON m.mae_ecivil=ec.ec_cod 
                LEFT JOIN ttransp tt ON m.mae_transp=tt.tt_cod 
                LEFT JOIN motbaja mtb ON m.mae_mbaja=mtb.mtb_cod WHERE mae_emp='$empCod' ORDER BY mae_emp,mae_gru,mae_dep,mae_cod";
}
if ($crStat=='A') {
    $sMaestro = "SELECT *,
                TRIM(m.mae_nom) AS mae_nom,
                TRIM(m.mae_ape) AS mae_ape,
                trim(gru.gru_nom) AS gru_nom,
                trim(dep.dep_nom) AS dep_nom,
                trim(tt.tt_nom) AS tt_nom
                FROM maestro m 
                LEFT JOIN grupo gru ON m.mae_gru=gru.gru_cod 
                LEFT JOIN dep dep ON m.mae_dep=dep.dep_cod 
                LEFT JOIN tpuesto tp ON m.mae_tpue=tp.tpu_cod 
                LEFT JOIN ecivil ec ON m.mae_ecivil=ec.ec_cod 
                LEFT JOIN ttransp tt ON m.mae_transp=tt.tt_cod 
                LEFT JOIN motbaja mtb ON m.mae_mbaja=mtb.mtb_cod WHERE mae_emp='$empCod' AND mae_stat!='B' ORDER BY mae_emp,mae_gru,mae_dep,mae_cod";
}
if ($crStat=='B') {
    $sMaestro = "SELECT *,
                TRIM(m.mae_nom) AS mae_nom,
                TRIM(m.mae_ape) AS mae_ape,
                trim(gru.gru_nom) AS gru_nom,
                trim(dep.dep_nom) AS dep_nom,
                trim(tt.tt_nom) AS tt_nom
                FROM maestro m 
                LEFT JOIN grupo gru ON m.mae_gru=gru.gru_cod 
                LEFT JOIN dep dep ON m.mae_dep=dep.dep_cod 
                LEFT JOIN tpuesto tp ON m.mae_tpue=tp.tpu_cod 
                LEFT JOIN ecivil ec ON m.mae_ecivil=ec.ec_cod 
                LEFT JOIN ttransp tt ON m.mae_transp=tt.tt_cod 
                LEFT JOIN motbaja mtb ON m.mae_mbaja=mtb.mtb_cod WHERE mae_emp='$empCod' AND mae_stat='B' 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=4;
$objPHPExcel->setActiveSheetIndex($sheet['maestro'])
			->setCellValueByColumnAndRow($i, 1, "Listado de Empleados al ".strftime("%d/%m/%Y"))
			->setCellValueByColumnAndRow($i, 2, "Estatus: ".$statnom)
			->setCellValueByColumnAndRow($i++, $j, 'Codigo')
			->setCellValueByColumnAndRow($i++, $j, 'Grupo')
			->setCellValueByColumnAndRow($i++, $j, 'Departamento')
			->setCellValueByColumnAndRow($i++, $j, 'Nombre')
			->setCellValueByColumnAndRow($i++, $j, 'Apellido')
			->setCellValueByColumnAndRow($i++, $j, 'Apellido Casada')
			->setCellValueByColumnAndRow($i++, $j, 'Puesto')
			->setCellValueByColumnAndRow($i++, $j, 'Nombre para Cheque')
			->setCellValueByColumnAndRow($i++, $j, 'Sexo')
			->setCellValueByColumnAndRow($i++, $j, 'Direccion Actual')
			->setCellValueByColumnAndRow($i++, $j, 'Zona')
			->setCellValueByColumnAndRow($i++, $j, 'Lugar Nacimiento')
			->setCellValueByColumnAndRow($i++, $j, 'Nacionalidad')
			->setCellValueByColumnAndRow($i++, $j, 'Estado Civil')
			->setCellValueByColumnAndRow($i++, $j, 'Tipo Sangre')
			->setCellValueByColumnAndRow($i++, $j, 'No.Hijos')
			->setCellValueByColumnAndRow($i++, $j, 'Transporte')
			->setCellValueByColumnAndRow($i++, $j, 'Fecha Nacio')
			->setCellValueByColumnAndRow($i++, $j, 'Fecha Ingreso')
			->setCellValueByColumnAndRow($i++, $j, 'No.Seguro Social')
			->setCellValueByColumnAndRow($i++, $j, 'NIT')
			->setCellValueByColumnAndRow($i++, $j, 'DPI')
			->setCellValueByColumnAndRow($i++, $j, 'Municipio Extendio')
			->setCellValueByColumnAndRow($i++, $j, 'Departamento Extendio')
			->setCellValueByColumnAndRow($i++, $j, 'Telefono')
			->setCellValueByColumnAndRow($i++, $j, 'Telefono Emergencia')
			->setCellValueByColumnAndRow($i++, $j, 'Profesion')
			->setCellValueByColumnAndRow($i++, $j, 'Correo Electronica')
			->setCellValueByColumnAndRow($i++, $j, 'Escolaridad')
			->setCellValueByColumnAndRow($i++, $j, 'Cuenta Bancaria')
			->setCellValueByColumnAndRow($i++, $j, 'Forma Pago')
			->setCellValueByColumnAndRow($i++, $j, 'Seguro Social')
			->setCellValueByColumnAndRow($i++, $j, 'Sueldo Base')
			->setCellValueByColumnAndRow($i++, $j, 'Boni/Ley')
			->setCellValueByColumnAndRow($i++, $j, 'Boni. Incentivo')
			->setCellValueByColumnAndRow($i++, $j, 'Bono Extra')
			->setCellValueByColumnAndRow($i++, $j, 'Deprec.Vehiculo')
			->setCellValueByColumnAndRow($i++, $j, 'Viaticos')
			->setCellValueByColumnAndRow($i++, $j, 'Status')
			->setCellValueByColumnAndRow($i++, $j, 'Fecha Baja')
			->setCellValueByColumnAndRow($i++, $j, 'Motivo Baja');

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

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

$styEncabezado = array(
    '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:I1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:I2')->getStyle('A2')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->getStyle('A4:AO4')->applyFromArray($styEncabezado);

# VALORES PRIMER HOJA
$i=$iIni;
for ($j=5; $rec = $db->fetchAssoc($select['maestro']); $j++) {
	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, $rec['mae_cod'])
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['gru_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['dep_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_ape'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_apec'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['tpu_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_nomch'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_sexo'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_dir'])))
				->setCellValueByColumnAndRow($i++, $j, $rec['mae_zondir'])
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_lnac'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_nacio'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['ec_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_tsang'])))
				->setCellValueByColumnAndRow($i++, $j, $rec['mae_hijos'])
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['tt_nom'])))
				->setCellValueByColumnAndRow($i++, $j, strftime("%d/%m/%Y", strtotime($rec["mae_fecnac"])))
				->setCellValueByColumnAndRow($i++, $j, strftime("%d/%m/%Y", strtotime($rec["mae_fing"])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_nigss'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_nit'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_dpi'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_exten'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_depexten'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_tel'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_tele'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_profe'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_email'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_escola'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_ctab'])))
				->setCellValueByColumnAndRow($i++, $j, strftime("%d/%m/%Y", strtotime($rec["mae_fpago"])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_igsssn'])))
				->setCellValueByColumnAndRow($i++, $j, $rec['mae_sueldo'])
				->setCellValueByColumnAndRow($i++, $j, $rec['mae_bonil'])
				->setCellValueByColumnAndRow($i++, $j, $rec['mae_bonii'])
				->setCellValueByColumnAndRow($i++, $j, $rec['mae_bonoe'])
				->setCellValueByColumnAndRow($i++, $j, $rec['mae_depre'])
				->setCellValueByColumnAndRow($i++, $j, $rec['mae_viati'])
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_stat'])));
		if ($rec['mae_stat']=='B') {
			$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, strftime("%d/%m/%Y", strtotime($rec["mae_fsal"])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mtb_nom'])));
		}
        $objPHPExcel->getActiveSheet()->setCellValueExplicit('T'.$j, $rec['mae_nigss'], PHPExcel_Cell_DataType::TYPE_STRING);
        $objPHPExcel->getActiveSheet()->setCellValueExplicit('U'.$j, $rec['mae_nit'], PHPExcel_Cell_DataType::TYPE_STRING);
        $objPHPExcel->getActiveSheet()->setCellValueExplicit('V'.$j, $rec['mae_dpi'], PHPExcel_Cell_DataType::TYPE_STRING);		
	$i=$iIni;
}

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('V')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('W')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('X')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('Y')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('Z')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AA')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AB')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AC')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AD')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AE')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AF')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AG')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AH')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AI')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AJ')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AK')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AL')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AM')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AN')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('AO')->setWidth(15);


$objPHPExcel->getActiveSheet()->getStyle('A5'.':BC'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
$objPHPExcel->getActiveSheet()->getStyle('P5'.':P'.$j)->getNumberFormat()->setFormatCode('#,##0');
$objPHPExcel->getActiveSheet()->getStyle('AG5'.':AL'.$j)->getNumberFormat()->setFormatCode('#,###,##0.00');

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

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

?>