<?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/fpdf/functions.php");
include_once('../../../php/timezone.php');
include_once('../../../php/maxExecTime.php');

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

$selTipoCod = $_GET["selTipoCod"];
$dtFecIni = $_GET["dtFecIni"];
$dtFecFin = $_GET["dtFecFin"];
$crAnu = $_GET["crAnu"];
$crFpag = $_GET["crFpag"];

$condiciones = "";
$condiciones .= ($crAnu!='T') ? "AND fact_tot=0" : "";
$condiciones .= ($crFpag!='T') ? " AND fact_fpag=$crFpag" : "";

# QUERYS
$where = "WHERE fact_emp='$empCod' AND fact_fec>='$dtFecIni' AND fact_fec<='$dtFecFin' AND fact_tipo='$selTipoCod' $condiciones ORDER BY fact_idinterno ASC";
$sFacturas = "SELECT * FROM facturas $where";
$sNotas = "SELECT * FROM notas $where";

$sTipov = "SELECT TRIM(tv_nom) AS tv_nom FROM tipov WHERE tv_cod='$selTipoCod'";

# EJECUCION DE QUERYS
$db = new dbExec();

$s = $sFacturas;
$cr["documentos"] = utf8_decode("DOCUMENTOS: {$_GET["crAnuNom"]}");
$cr["formaPago"] = utf8_decode("FORMA DE PAGO: {$_GET["crFpagNom"]}");
/*$cr["documentos"] = "";
$cr["formaPago"] = "";
switch ($selTipoCod[0]) {
    case 'F':
        $s = $sFacturas;
        $cr["documentos"] = ("DOCUMENTOS: {$_GET["crAnuNom"]}");
        $cr["formaPago"] = ("FORMA DE PAGO: {$_GET["crFpagNom"]}");
        break;
    
    default:
        $s = $sNotas;
        break;
}*/
$select["documentos"] = $db->query($s);
$fa["tipov"] = $db->sFetchAssoc($sTipov);

$dtFecIni = date('d/m/Y', strtotime($_GET["dtFecIni"]));
$dtFecFin = date('d/m/Y', strtotime($_GET["dtFecFin"]));

/** 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;
$jIni=0;
$objPHPExcel = new PHPExcel();

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

$bordersThin = array(
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);

$borderBottomDouble = array(
    'borders' => array(
        'bottom' => array(
            'style' => PHPExcel_Style_Border::BORDER_DOUBLE
        )
    )
);

$borderTopThin = array(
    'borders' => array(
        'top' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);

# HOJAS
$sheet['documentos']=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=$jIni+1;
$objPHPExcel->setActiveSheetIndex($sheet['documentos'])
    ->setCellValueByColumnAndRow($i, $j++, utf8_encode($empNom))
    ->setCellValueByColumnAndRow($i, $j, "LISTADO DE DOCUMENTOS DEL $dtFecIni AL $dtFecFin")
    ->setCellValueByColumnAndRow(6,  $j++, $cr["documentos"])
    ->setCellValueByColumnAndRow($i, $j, utf8_encode("TIPO: {$fa["tipov"]["tv_nom"]}"))
    ->setCellValueByColumnAndRow(6,  $j++, $cr["formaPago"]);

$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':I'.$j)->applyFromArray($bordersThin);

$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++,	$j, 'Serie')
	->setCellValueByColumnAndRow($i++,	$j, 'Número')
	->setCellValueByColumnAndRow($i++,	$j, 'Fecha')
    ->setCellValueByColumnAndRow($i++,  $j, 'NIT')
    ->setCellValueByColumnAndRow($i++,  $j, 'Código')
	->setCellValueByColumnAndRow($i++,	$j, 'Nombre en el Documento')
	->setCellValueByColumnAndRow($i++,	$j, 'Quetzales')
    ->setCellValueByColumnAndRow($i++,  $j, 'Dólares')
    ->setCellValueByColumnAndRow($i++,  $j, 'Tasa de Cambio');


# VALORES PRIMER HOJA
$j++;

while ($rec = $db->fetchAssoc($select["documentos"])) {
    $i=$iIni;
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow($i++,  $j, trim($rec["fact_serie"]))
        ->setCellValueByColumnAndRow($i++,  $j, $rec["fact_num"])
        ->setCellValueByColumnAndRow($i++,  $j, date('d/m/Y', strtotime($rec["fact_fec"])))
        ->setCellValueByColumnAndRow($i++,  $j, trim($rec["fact_nit"]))
        ->setCellValueByColumnAndRow($i++,  $j, trim($rec["fact_codp"]))
        ->setCellValueByColumnAndRow($i++,  $j, trim(utf8_encode($rec["fact_nom"])))
        ->setCellValueByColumnAndRow($i++,  $j, ($rec["fact_tcam"]==1) ? $rec["fact_tot"] : 0)
        ->setCellValueByColumnAndRow($i++,  $j, ($rec["fact_tcam"]>1) ? $rec["fact_tot"] : 0)
        ->setCellValueByColumnAndRow($i++,  $j, $rec["fact_tcam"]);
    $j++;
}

// TOTALES
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':I'.$j)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('G'.$j.':H'.$j)->applyFromArray($borderBottomDouble);
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow(5,	$j, "TOTAL")
	->setCellValueByColumnAndRow(6,	$j, '=SUM(G5:G'.($j-1).')')
	->setCellValueByColumnAndRow(7,	$j, '=SUM(H5:H'.($j-1).')');

# ESTILO HOJA
$xCenter = array(
    'font' => array(
        'bold' => true,
    ),
	'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$objPHPExcel->getActiveSheet()->mergeCells('A1:H1')->getStyle('A1')->applyFromArray($xCenter);
for ($q=2; $q <= 3; $q++) { 
    $objPHPExcel->getActiveSheet()->mergeCells('A'.$q.':F'.$q);
    $objPHPExcel->getActiveSheet()->mergeCells('G'.$q.':H'.$q);
}

# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('G5'.':H'.$j)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('I5'.':I'.$j)->getNumberFormat()->setFormatCode('#,##0.00000');
$objPHPExcel->getActiveSheet()->getStyle('E5'.':E'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
$objPHPExcel->getActiveSheet()->getStyle('A5'.':A'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

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

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

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

$filename = utf8_decode("Documentos $selTipoCod");
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment;filename=\"{$filename}.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;
?>