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

$numNum=$_GET["numNum"];
$selBan=$_GET["selBan"];
$selBodegapro=$_GET['selBodegapro'];
$selDep=$_GET['selDep'];
$selPuesto=$_GET['selPuesto'];
$Banctab=$_GET["Banctab"];
$Banctac=$_GET["Banctac"];
$dtFec=$_GET["dtFec"];

# QUERYS
if ($selDep=="000") {
    if ($selPuesto=="000") {
        $sNomper = "SELECT np.*, gru.*, dep.*, mae.mae_gru, mae.mae_dep, mae.mae_tpue,  TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape, mae_igsssn, TRIM(mae.mae_nomch) AS mae_nomch, mae_fpago, mae_ctab,
                    TRIM(gru_nom) AS gru_nom, TRIM(dep_nom) AS dep_nom, mae.mae_fpago, TRIM(tpu.tpu_nom) AS tpu_nom 
                    FROM nomper np
                    LEFT JOIN maestro mae ON np.np_emp=mae.mae_emp AND np.np_cod = mae.mae_cod 
                    LEFT JOIN tpuesto tpu ON mae.mae_tpue = tpu.tpu_cod 
                    LEFT JOIN grupo gru ON np.np_emp=gru.gru_emp AND np.np_gru = gru.gru_cod 
                    LEFT JOIN dep dep ON np.np_emp=dep.dep_emp AND np.np_dep = dep.dep_cod 
                    WHERE np_emp='$empCod' AND np_numpla='$numNum' and mae.mae_bodega='$selBodegapro' AND mae.mae_fpago=5 ORDER BY np_dep, mae.mae_tpue,mae.mae_nom,mae.mae_ape";
    } else {
        $sNomper = "SELECT np.*, gru.*, dep.*, mae.mae_gru, mae.mae_dep, mae.mae_tpue,  TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape, mae_igsssn, TRIM(mae.mae_nomch) AS mae_nomch, mae_fpago, mae_ctab, 
                    TRIM(gru_nom) AS gru_nom, TRIM(dep_nom) AS dep_nom, mae.mae_fpago, TRIM(tpu.tpu_nom) AS tpu_nom 
                    FROM nomper np
                    LEFT JOIN maestro mae ON np.np_emp=mae.mae_emp AND np.np_cod = mae.mae_cod 
                    LEFT JOIN tpuesto tpu ON mae.mae_tpue = tpu.tpu_cod 
                    LEFT JOIN grupo gru ON np.np_emp=gru.gru_emp AND np.np_gru = gru.gru_cod 
                    LEFT JOIN dep dep ON np.np_emp=dep.dep_emp AND np.np_dep = dep.dep_cod 
                    WHERE np_emp='$empCod' AND np_numpla='$numNum' and mae.mae_bodega='$selBodegapro' and mae.mae_tpue='$selPuesto' AND mae.mae_fpago=5 ORDER BY np_dep, mae.mae_tpue,mae.mae_nom,mae.mae_ape";
    }       
} else {
    if ($selPuesto=="000") {
        $sNomper = "SELECT np.*, gru.*, dep.*, mae.mae_gru, mae.mae_dep, mae.mae_tpue,  TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape, mae_igsssn, TRIM(mae.mae_nomch) AS mae_nomch, mae_fpago, mae_ctab, 
                    TRIM(gru_nom) AS gru_nom, TRIM(dep_nom) AS dep_nom, mae.mae_fpago, TRIM(tpu.tpu_nom) AS tpu_nom 
                    FROM nomper np
                    LEFT JOIN maestro mae ON np.np_emp=mae.mae_emp AND np.np_cod = mae.mae_cod 
                    LEFT JOIN tpuesto tpu ON mae.mae_tpue = tpu.tpu_cod 
                    LEFT JOIN grupo gru ON np.np_emp=gru.gru_emp AND np.np_gru = gru.gru_cod 
                    LEFT JOIN dep dep ON np.np_emp=dep.dep_emp AND np.np_dep = dep.dep_cod 
                    WHERE np_emp='$empCod' AND np_numpla='$numNum' and mae.mae_bodega='$selBodegapro' and np_dep='$selDep' AND mae.mae_fpago=5 ORDER BY np_dep, mae.mae_tpue,mae.mae_nom,mae.mae_ape";
    } else {
        $sNomper = "SELECT np.*, gru.*, dep.*, mae.mae_gru, mae.mae_dep, mae.mae_tpue,  TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape, mae_igsssn, TRIM(mae.mae_nomch) AS mae_nomch, mae_fpago, mae_ctab, 
                    TRIM(gru_nom) AS gru_nom, TRIM(dep_nom) AS dep_nom, mae.mae_fpago, TRIM(tpu.tpu_nom) AS tpu_nom 
                    FROM nomper np
                    LEFT JOIN maestro mae ON np.np_emp=mae.mae_emp AND np.np_cod = mae.mae_cod 
                    LEFT JOIN tpuesto tpu ON mae.mae_tpue = tpu.tpu_cod 
                    LEFT JOIN grupo gru ON np.np_emp=gru.gru_emp AND np.np_gru = gru.gru_cod 
                    LEFT JOIN dep dep ON np.np_emp=dep.dep_emp AND np.np_dep = dep.dep_cod 
                    WHERE np_emp='$empCod' AND np_numpla='$numNum' and mae.mae_bodega='$selBodegapro' and np_dep='$selDep' and mae.mae_tpue='$selPuesto' AND mae.mae_fpago=5 ORDER BY np_dep, mae.mae_tpue,mae.mae_nom,mae.mae_ape";
    }       
}       

# EJECUCION DE QUERYS
$db = new dbExec();
$select["nomper"] = $db->query($sNomper);
$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=5;
$objPHPExcel->setActiveSheetIndex($sheet['maestro'])
			->setCellValueByColumnAndRow($i, 1, utf8_decode($empNom))
			->setCellValueByColumnAndRow($i, 2, utf8_decode("LISTADO PARA PAGO EN EFECTIVO FECHA DEL REPORTE: ".strftime("%d/%m/%Y", strtotime($dtFec))))
			->setCellValueByColumnAndRow($i, 3, "PLANILLA No. : ".$numNum)
			->setCellValueByColumnAndRow($i, 4, "CUENTA BANCARIA: ".$Banctab)
			->setCellValueByColumnAndRow($i++, $j, 'Cuenta')
			->setCellValueByColumnAndRow($i++, $j, 'Nombre')
			->setCellValueByColumnAndRow($i++, $j, 'Monto');

# 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','I') as $colID) { 
    $objPHPExcel->getActiveSheet()->getColumnDimension($colID)->setAutoSize(true); 
} */

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:C2')->getStyle('A2')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A3:C3')->getStyle('A3')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A4:C4')->getStyle('A4')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->getStyle('A5:C5')->applyFromArray($styEncabezado);

# VALORES PRIMER HOJA
$i=$iIni;
for ($j=6; $rec = $db->fetchAssoc($select['nomper']); $j++) {
    $otrosing=($rec["np_bonii"]+$rec["np_bonoe"]+$rec["np_depre"]+$rec["np_viati"]+$rec["np_comi"]+$rec["np_otrp"]);
    $devengado=($rec["np_sord"]+$rec["np_boni"]+$rec["np_sferi"]+$rec["np_sexts"]+$rec["np_sextd"]+$rec["np_ssept"]+$rec["np_bonii"]+$rec["np_bonoe"]+$rec["np_depre"]+$rec["np_viati"]+$rec["np_comi"]+$rec["np_otrp"]);
    $otrosdesc=($rec["np_isr"]+$rec["np_anti"]+$rec["np_unif"]+$rec["np_lent"]+$rec["np_preb"]+$rec["np_pree"]+$rec["np_desj"]+$rec["np_otrd"]);
    $totdesc=($rec["np_igss"]+$rec["np_isr"]+$rec["np_anti"]+$rec["np_unif"]+$rec["np_lent"]+$rec["np_preb"]+$rec["np_pree"]+$rec["np_desj"]+$rec["np_otrd"]);
    $liquido=($devengado-$totdesc);

    $cod=$rec["np_cod"];
    $nomch=$rec["mae_nomch"];
    if ($nomch=="") {
        $nomch=$rec["mae_nom"]." ".$rec["mae_ape"];
    }
    if ($liquido == 0){
        continue;
    }

	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_ctab'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($nomch)))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($liquido))); 
	$i=$iIni;
}
$i=$iIni;
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "        TOTAL A ACREDITAR")
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(C6:C'.($j-1).')');
$objPHPExcel->getActiveSheet()->getStyle('B'.$j.':C'.$j)->applyFromArray($styTotales); 

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


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

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

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

?>