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

$empCod=utf8_decode($_SESSION["empCod"]);
$empNom=utf8_decode($_SESSION["empNom"]);
$empNomc=utf8_decode($_SESSION["empNomc"]);
$pTcam=$_SESSION["pTcam"];
$empNit=utf8_decode($_SESSION['empNit']);

$selMes=$_GET["selMes"];
$selMesNom=$_GET["selMesNom"];
$numAno=$_GET["numAno"];
$numHoja=$_GET["numHoja"];
$cbFecsn=$_GET["cbFecsn"];
$cbNoFol=$_GET["cbNoFol"];


# QUERYS
$sIva_ven = "SELECT *,
                TRIM(iv.ivav_serie) AS ivav_serie,
                MIN(iv.ivav_num) AS ivav_menor,
                MAX(iv.ivav_num) AS ivav_mayor, 
                (SUM(iv.ivav_subb)+SUM(iv.ivav_subme)+SUM(iv.ivav_subve)+SUM(iv.ivav_subco)) AS ivav_sumsubb,
                (SUM(iv.ivav_subna)+SUM(iv.ivav_exen)) AS ivav_sumexen, 
                SUM(iv.ivav_subs) AS ivav_sumsubs,
                (SUM(iv.ivav_sube)+SUM(iv.ivav_suber)) AS ivav_sumsube, 
                SUM(iv.ivav_iva) AS ivav_sumiva,
                SUM(iv.ivav_tot) AS ivav_sumtot,
                SUM(1) AS ivav_cantf 
            FROM iva_ven iv LEFT JOIN tipov tv ON tv.tv_cod=iv.ivav_tipo
            WHERE iv.ivav_emp='$empCod' AND year(iv.ivav_fec)=$numAno AND month(iv.ivav_fec)=$selMes AND iv.ivav_afe='S' 
            GROUP BY iv.ivav_fec,iv.ivav_serie,iv.ivav_venrango ORDER BY ivav_emp,ivav_fec";

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

/** 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['ventas']=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("Iva");

# ENCABEZADO PRIMER HOJA
$i=$iIni;
$j=$jIni+1;
$objPHPExcel->setActiveSheetIndex($sheet['ventas'])
	->setCellValueByColumnAndRow($i,	$j++, utf8_encode($empNom))
    ->setCellValueByColumnAndRow($i,    $j++, "LIBRO DE VENTAS Y SERVICIOS (RESUMIDO)")
	->setCellValueByColumnAndRow($i,	$j++, "Mes ".trim($selMesNom)."  Año ".$numAno."                    Nit: ".$empNit);

$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':K'.$j)->applyFromArray($bordersThin);
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++,	$j, 'FECHA')
	->setCellValueByColumnAndRow($i++,	$j, 'SERIE')
	->setCellValueByColumnAndRow($i++,	$j, '   DEL')
	->setCellValueByColumnAndRow($i++,	$j, '   AL')
	->setCellValueByColumnAndRow($i++,	$j, 'CLIENTE')
	->setCellValueByColumnAndRow($i++,	$j, 'VENTAS')
	->setCellValueByColumnAndRow($i++,	$j, 'EXENTO')
    ->setCellValueByColumnAndRow($i++,  $j, 'SERVICIOS')
    ->setCellValueByColumnAndRow($i++,  $j, 'EXPORTACION')
    ->setCellValueByColumnAndRow($i++,  $j, 'IVA')
    ->setCellValueByColumnAndRow($i++,  $j, 'TOTAL');
$j++;



# CREA EL CICLO PARA EL LISTADO DE MOVIMIENTOS DE LA CUENTA

$select["iva_ven"] = $db->query($sIva_ven);
while ($rec = $db->fetchAssoc($select['iva_ven'])) {
    $i=$iIni;

    if ($rec["ivav_serie"]=="") {
        $serie=$rec["tv_nom"];
    } else {
        $serie=$serie=$rec["ivav_serie"];
    }

    $objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, strftime("%d/%m/%Y", strtotime($rec["ivav_fec"])))    
    ->setCellValueByColumnAndRow($i++,  $j, trim($serie))
    ->setCellValueByColumnAndRow($i++,  $j, ($rec["ivav_menor"]))
    ->setCellValueByColumnAndRow($i++,  $j, ($rec["ivav_venrango"]!='S') ? $rec["ivav_mayor"] : $rec["ivav_numf"])
    ->setCellValueByColumnAndRow($i++,  $j, utf8_encode("CLIENTES VARIOS"))
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["ivav_sumsubb"],2) != 0) ? $rec["ivav_sumsubb"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["ivav_sumexen"],2) != 0) ? $rec["ivav_sumexen"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["ivav_sumsubs"],2) != 0) ? $rec["ivav_sumsubs"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["ivav_sumsube"],2) != 0) ? $rec["ivav_sumsube"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["ivav_sumiva"],2) != 0) ? $rec["ivav_sumiva"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["ivav_sumtot"],2) != 0) ? $rec["ivav_sumtot"] : "");
    $j++;

    $linea=2;
}


// TOTALES DEL MOVIMIENTO
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':K'.$j)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':K'.$j)->applyFromArray($borderBottomDouble);
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow(4,	$j, "TOTALES ")
    ->setCellValueByColumnAndRow(5, $j, '=SUM(F5:F'.($j-1).')')
    ->setCellValueByColumnAndRow(6, $j, '=SUM(G5:G'.($j-1).')')
    ->setCellValueByColumnAndRow(7, $j, '=SUM(H5:H'.($j-1).')')
    ->setCellValueByColumnAndRow(8, $j, '=SUM(I5:I'.($j-1).')')
    ->setCellValueByColumnAndRow(9, $j, '=SUM(J5:J'.($j-1).')')
    ->setCellValueByColumnAndRow(10, $j, '=SUM(K5:K'.($j-1).')');

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

for ($q=1; $q < 4; $q++) { 
	$objPHPExcel->getActiveSheet()->mergeCells('A'.$q.':K'.$q)->getStyle('A'.$q)->applyFromArray($xCenter);
}

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(15);

# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('F5'.':K'.$j)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A5'.':E'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);


# ESTABLECER TITULOS
$objPHPExcel->setActiveSheetIndex($sheet['ventas'])->setTitle('Libro de Ventas');

# 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="Libro de Ventas Resumido.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;
?>