<?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"];
$dtDel=$_GET["dtDel"];
$dtAl=$_GET["dtAl"];

# QUERYS
$sNomper = "SELECT np.*, TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape,
            TRIM(mae.mae_nomch) AS mae_nomch, TRIM(mae.mae_ctab) AS mae_ctab, 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 
            WHERE np_emp='$empCod' AND np_numpla='$numNum' AND mae_fpago<3 ORDER BY np_emp,np_gru,np_dep,CAST(np_cod AS UNSIGNED)";

# 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=1;
/*
$objPHPExcel->setActiveSheetIndex($sheet['maestro'])
			->setCellValueByColumnAndRow($i++, $j, 'Agencia')
            ->setCellValueByColumnAndRow($i++, $j, 'Correlativo')
            ->setCellValueByColumnAndRow($i++, $j, 'Digito')
			->setCellValueByColumnAndRow($i++, $j, 'Concepto')
			->setCellValueByColumnAndRow($i++, $j, 'Valor Q.');
*/
# 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()->getStyle('A1:E1')->applyFromArray($styEncabezado);

$concepto=utf8_decode("PAGO CORRESPONDIENTE DEL ".strftime("%d/%m/%Y", strtotime($dtDel))." AL ".strftime("%d/%m/%Y", strtotime($dtAl)));

# VALORES PRIMER HOJA
$i=$iIni;
for ($j=1; $rec = $db->fetchAssoc($select['nomper']); $j++) {
    $lcant=strlen(TRIM($rec["mae_ctab"]));
    $t_ctab=TRIM($rec["mae_ctab"]);
    $t_guion=1;
    $t_agen=1;
    $t_corr="";
    $t_digi="";
/*    
    for ($k=0; $k<=$lcant; $k++) {
      $t_car=SUBSTR($t_ctab,$k,1);
      IF ($t_guion==1 && $t_car!="-") {
        $t_agen=$t_agen.TRIM($t_car);
      }
      IF ($t_guion==1 && $t_car=="-") {
        //$k++;
        $t_guion=2;
        continue;
      }
      IF ($t_guion==2 && $t_car!="-") {
        $t_corr=$t_corr.TRIM($t_car);
      }
      IF ($t_guion==2 && $t_car=="-") {
        //$k++;
        $t_guion=3;
        continue;
      }
      IF ($t_guion==3 && $t_car!="-") {
        $t_digi=$t_digi.TRIM($t_car);
      }
    }
*/    
	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, trim($t_agen))
                ->setCellValueByColumnAndRow($i++, $j, trim($t_ctab))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_nomch'])))
				->setCellValueByColumnAndRow($i++, $j, $rec['np_liqrec'])
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($concepto))); 
	$i=$iIni;
}
$i=$iIni;
/*
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "        TOTAL A ACREDITAR")
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(E2:E'.($j-1).')');
$objPHPExcel->getActiveSheet()->getStyle('D'.$j.':E'.$j)->applyFromArray($styTotales); 
*/

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(50);


$objPHPExcel->getActiveSheet()->getStyle('B1'.':C'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
$objPHPExcel->getActiveSheet()->getStyle('D1'.':D'.$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="Acreditaciones.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;

?>