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

$dtFecIni = $_GET["dtFecIni"];
$dtFecFin = $_GET["dtFecFin"];


# QUERYS
$sFacturas = "SELECT fac.*, iv.ivav_sub, iv.ivav_iva, iv.ivav_tot
              FROM facturas fac
              LEFT JOIN iva_ven iv ON fac.fact_emp=iv.ivav_emp AND fac.fact_tipo=iv.ivav_tipo AND fac.fact_serie=iv.ivav_serie AND fac.fact_num=iv.ivav_num 
              WHERE fact_emp='$empCod' AND fact_caja='$pCaja' AND fact_fec>='$dtFecIni' AND fact_fec<='$dtFecFin' ORDER BY fact_emp,fact_fec,fact_serie,fact_num";

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

$select["documentos"] = $db->query($sFacturas);

$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['facturas']=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['facturas'])
    ->setCellValueByColumnAndRow($i, $j++, utf8_encode($empNom))
    ->setCellValueByColumnAndRow($i, $j++, "REPORTE DE FACTURAS")
    ->setCellValueByColumnAndRow($i, $j++, "CORRESPONDIENTES DEL $dtFecIni AL $dtFecFin");  

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

$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++,	$j, 'Fecha')
	->setCellValueByColumnAndRow($i++,	$j, 'Serie')
	->setCellValueByColumnAndRow($i++,	$j, 'Factura')
    ->setCellValueByColumnAndRow($i++,  $j, 'NIT')
    ->setCellValueByColumnAndRow($i++,  $j, 'Nombre')
	->setCellValueByColumnAndRow($i++,	$j, 'Direccion')
	->setCellValueByColumnAndRow($i++,	$j, 'Sub-total')
    ->setCellValueByColumnAndRow($i++,  $j, 'Iva')
    ->setCellValueByColumnAndRow($i++,  $j, 'Total'); 


# VALORES PRIMER HOJA
$j++;

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

// TOTALES
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':I'.$j)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('G'.$j.':I'.$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).')')
    ->setCellValueByColumnAndRow(8, $j, '=SUM(I5:I'.($j-1).')');

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

//$objPHPExcel->getActiveSheet()->mergeCells('A1:I1')->getStyle('A1')->applyFromArray($xCenter);

for ($q=2; $q <= 3; $q++) { 
    $objPHPExcel->getActiveSheet()->mergeCells('A'.$q.':F'.$q);
    $objPHPExcel->getActiveSheet()->mergeCells('G'.$q.':I'.$q);
}

# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('G5'.':I'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('B5'.':B'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
$objPHPExcel->getActiveSheet()->getStyle('D5'.':D'.$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['facturas'])->setTitle("Facturas Emitidas");

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

$filename = utf8_decode("Documentos");
// 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;
?>