<?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_comp = "SELECT *,
                TRIM(ic.iva_serie) AS iva_serie,
                TRIM(ic.iva_nit) AS iva_nit,
                TRIM(ic.iva_prov) AS iva_prov
            FROM iva_comp ic 
            WHERE ic.iva_emp='$empCod' AND year(ic.iva_rfec)=$numAno AND month(ic.iva_rfec)=$selMes AND ic.iva_afe='S' 
            ORDER BY ic.iva_emp,ic.iva_fec";

$sIvacResu = "SELECT *, 
            (SUM(iva_subb)+SUM(iva_subs)+SUM(iva_subco)) AS iva_svalor, 
            SUM(1) AS iva_sumdoc 
            FROM iva_comp ic WHERE ic.iva_emp='$empCod' AND year(ic.iva_rfec)=$numAno AND month(ic.iva_rfec)=$selMes AND ic.iva_afe='S'  GROUP BY ic.iva_emp,ic.iva_nit ORDER BY iva_svalor DESC";

# 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['compras']=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['compras'])
	->setCellValueByColumnAndRow($i,	$j++, utf8_encode($empNom))
    ->setCellValueByColumnAndRow($i,    $j++, "LIBRO DE COMPRAS Y SERVICIOS")
	->setCellValueByColumnAndRow($i,	$j++, "Mes ".trim($selMesNom)."  Año ".$numAno."                    Nit: ".$empNit);

$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':R'.$j)->applyFromArray($bordersThin);
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++,	$j, 'FECHA')
	->setCellValueByColumnAndRow($i++,	$j, 'SERIE')
	->setCellValueByColumnAndRow($i++,	$j, 'NUMERO')
	->setCellValueByColumnAndRow($i++,	$j, 'NIT')
	->setCellValueByColumnAndRow($i++,	$j, 'PROVEEDOR')
	->setCellValueByColumnAndRow($i++,	$j, 'COMBUSTIBLE')
	->setCellValueByColumnAndRow($i++,	$j, 'COMPRAS')
    ->setCellValueByColumnAndRow($i++,  $j, 'SERVICIOS')
    ->setCellValueByColumnAndRow($i++,  $j, 'MEDICINA')
    ->setCellValueByColumnAndRow($i++,  $j, 'VEHICULO')
    ->setCellValueByColumnAndRow($i++,  $j, 'NO AFECTO')
    ->setCellValueByColumnAndRow($i++,  $j, 'ACTIVO')
    ->setCellValueByColumnAndRow($i++,  $j, 'PEQUEÑO CONT.')
    ->setCellValueByColumnAndRow($i++,  $j, 'IMPORTACION C.A.')
    ->setCellValueByColumnAndRow($i++,  $j, 'IMPORTACION RESTO.')
    ->setCellValueByColumnAndRow($i++,  $j, 'IVA')
    ->setCellValueByColumnAndRow($i++,  $j, 'IMP.COMBUST. Y OTROS')
    ->setCellValueByColumnAndRow($i++,  $j, 'TOTAL');
$j++;



# CREA EL CICLO PARA EL LISTADO DE MOVIMIENTOS DE LA CUENTA
$rnc=0;
$rvalnc=0;
$select["iva_comp"] = $db->query($sIva_comp);
while ($rec = $db->fetchAssoc($select['iva_comp'])) {
    $i=$iIni;

    if ($rec["iva_sub"]<0){
       $rnc+=1;
       $rvalnc+=$rec["iva_sub"];
    }

    $objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, strftime("%d/%m/%Y", strtotime($rec["iva_fec"])))    
    ->setCellValueByColumnAndRow($i++,  $j, trim($rec["iva_serie"]))
    ->setCellValueByColumnAndRow($i++,  $j, $rec["iva_num"])
    ->setCellValueByColumnAndRow($i++,  $j, trim($rec["iva_nit"]))
    ->setCellValueByColumnAndRow($i++,  $j, utf8_encode($rec["iva_prov"]))
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_subco"],2) != 0) ? $rec["iva_subco"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_subb"],2) != 0) ? $rec["iva_subb"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_subs"],2) != 0) ? $rec["iva_subs"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_subme"],2) != 0) ? $rec["iva_subme"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_subve"],2) != 0) ? $rec["iva_subve"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_subna"],2) != 0) ? $rec["iva_subna"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_subac"],2) != 0) ? $rec["iva_subac"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_subpe"],2) != 0) ? $rec["iva_subpe"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_subi"],2) != 0) ? $rec["iva_subi"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_subir"],2) != 0) ? $rec["iva_subir"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_iva"],2) != 0) ? $rec["iva_iva"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["iva_dedu"]+$rec["iva_tasam"],2) != 0) ? $rec["iva_dedu"]+$rec["iva_tasam"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round(($rec["iva_tot"]+$rec["iva_dedu"]),2) != 0) ? ($rec["iva_tot"]+$rec["iva_dedu"]) : "");
    $j++;

    $linea=2;
}


// TOTALES DEL MOVIMIENTO
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':R'.$j)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':R'.$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).')')
    ->setCellValueByColumnAndRow(11, $j, '=SUM(L5:L'.($j-1).')')
    ->setCellValueByColumnAndRow(12, $j, '=SUM(M5:M'.($j-1).')')
    ->setCellValueByColumnAndRow(13, $j, '=SUM(N5:N'.($j-1).')')
    ->setCellValueByColumnAndRow(14, $j, '=SUM(O5:O'.($j-1).')')
    ->setCellValueByColumnAndRow(15, $j, '=SUM(P5:P'.($j-1).')')
    ->setCellValueByColumnAndRow(16, $j, '=SUM(Q5:Q'.($j-1).')')
    ->setCellValueByColumnAndRow(17, $j, '=SUM(R5:R'.($j-1).')');
$j++;
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':D'.$j)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':D'.$j)->applyFromArray($borderBottomDouble);
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(1, $j, "CANT N/C: ")
    ->setCellValueByColumnAndRow(2, $j, $rnc)
    ->setCellValueByColumnAndRow(3, $j, "VALOR NC:")
    ->setCellValueByColumnAndRow(4, $j, $rvalnc);

# 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.':R'.$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(40);
$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);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(15);

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

$j+=2;
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(4,  $j, 'RESUMEN DE LOS 10 MAYORES PROVEEDORES');
$j++;
$jr=$j;
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(3,  $j, 'NIT')
    ->setCellValueByColumnAndRow(4,  $j, 'PROVEEDOR')
    ->setCellValueByColumnAndRow(5,  $j, 'CANT/DOCTOS')
    ->setCellValueByColumnAndRow(6,  $j, 'VALOR AFECTO');
$j++;
$nlinea=1;
$select["iva_compr"] = $db->query($sIvacResu);
while ($recr = $db->fetchAssoc($select['iva_compr'])) {
    if ($recr["iva_svalor"] <= 0) {
        continue;
    }    
    
    if ($nlinea <= 10) {
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow(3,  $j, trim($recr["iva_nit"]))
            ->setCellValueByColumnAndRow(4,  $j, utf8_encode(trim($recr["iva_prov"])))
            ->setCellValueByColumnAndRow(5,  $j, $recr["iva_sumdoc"])
            ->setCellValueByColumnAndRow(6,  $j, $recr["iva_svalor"]);
            $j++;
    }
    $nlinea += 1;
}
$objPHPExcel->getActiveSheet()->getStyle('D'.$jr.':G'.($j-1))->applyFromArray($bordersThin);
//$j++;
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(4, $j, "                  TOTAL ")
    ->setCellValueByColumnAndRow(6, $j, '=SUM(G'.($jr+1).':G'.($j-1).')');

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

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

# 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 Compras.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;
?>