<?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"];

$numAno=$_GET["numAno"];
$crMoneda=$_GET["crMoneda"];
$textoMoneda=$_GET["textoMoneda"];
$crSaldo=$_GET["crSaldo"];
$textoSaldo=$_GET["textoSaldo"];
$cbFecsn=$_GET["cbFecsn"];

$tipoCierre="099";

# QUERYS
$sCierres = "SELECT
                c.cie_mes,
                cta.cta_niv,
                cta.cta_con,
                TRIM(c.cie_cta) AS cie_cta,
                TRIM(cta.cta_nom) AS cta_nom,
                TRIM(cta.cta_acta) AS cta_acta,
                (0) AS salIni,
                SUM(cie_mdebe) AS cie_mdebe,
                SUM(cie_mhaber) AS cie_mhaber,
                (SUM(cie_mdebe)-SUM(cie_mhaber)) AS salMes
            FROM empresas emp 
            LEFT JOIN cierres c ON c.cie_emp=emp.emp_cod
            INNER JOIN cuentas cta ON c.cie_emp=cta.cta_emp AND c.cie_cta=cta.cta
            WHERE emp.emp_conso='$empConso' AND c.cie_ano=$numAno AND c.cie_mes<=12 AND LEFT(c.cie_cta, 1)<4
            GROUP BY c.cie_cta, cie_mes";
/*
$sCierres = "SELECT
                c.cie_mes,
                cta.cta_niv,
                cta.cta_con,
                TRIM(c.cie_cta) AS cie_cta,
                TRIM(cta.cta_nom) AS cta_nom,
                TRIM(cta.cta_acta) AS cta_acta,
                (0) AS salIni,
                c.cie_mdebe,
                c.cie_mhaber,
                (SUM(cie_mdebe)-SUM(cie_mhaber)) AS salMes
            FROM cierres c 
            INNER JOIN cuentas cta ON c.cie_emp=cta.cta_emp AND c.cie_cta=cta.cta
            WHERE c.cie_emp='$empCod' AND c.cie_ano=$numAno AND c.cie_mes<=12 AND LEFT(c.cie_cta, 1)<4
            GROUP BY c.cie_cta, cie_mes";
*/

# EJECUCION DE QUERYS
$db = new dbExec();
$select["cierres"] = $db->query($sCierres);

$arrayCie=$db->fetchAll($select["cierres"]);

/** 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
        )
    )
);

# HOJAS
$sheet['cierres']=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['cierres'])
	->setCellValueByColumnAndRow($i,	$j++, utf8_encode($empNom))
	->setCellValueByColumnAndRow($i,	$j++, utf8_encode($empNomc))
	->setCellValueByColumnAndRow($i,	$j++, "Cuadro Anual Cuentas de Balance")
	->setCellValueByColumnAndRow($i,	$j++, "Correspondiente a ".$numAno)
    ->setCellValueByColumnAndRow($i,    $j++, "Cifras Expresadas en ".$textoMoneda)
    ->setCellValueByColumnAndRow($i,    $j++, $textoSaldo);

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

$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++,	$j, 'Cuenta')
	->setCellValueByColumnAndRow($i++,	$j, 'Nombre de Cuenta')
	->setCellValueByColumnAndRow($i++,	$j, 'Enero')
	->setCellValueByColumnAndRow($i++,	$j, 'Febrero')
	->setCellValueByColumnAndRow($i++,	$j, 'Marzo')
	->setCellValueByColumnAndRow($i++,	$j, 'Abril')
    ->setCellValueByColumnAndRow($i++,  $j, 'Mayo')
    ->setCellValueByColumnAndRow($i++,  $j, 'Junio')
    ->setCellValueByColumnAndRow($i++,  $j, 'Julio')
    ->setCellValueByColumnAndRow($i++,  $j, 'Agosto')
    ->setCellValueByColumnAndRow($i++,  $j, 'Septiembre')
    ->setCellValueByColumnAndRow($i++,  $j, 'Octubre')
    ->setCellValueByColumnAndRow($i++,  $j, 'Noviembre')
    ->setCellValueByColumnAndRow($i++,  $j, 'Diciembre')
    ->setCellValueByColumnAndRow($i++,  $j, 'Acumulado');


# VALORES PRIMER HOJA
$ctaAnt=1;
$ctaNomAnt=1;
$ctaNivAnt=1;

$salIni=0;
$body = array(0,0,0,0,0,0,0,0,0,0,0,0);

$j++;
foreach ($arrayCie as $rec) {
    if ($ctaAnt!=$rec["cie_cta"]) {
        if ($body[0]=="0.00" && $body[1]=="0.00" && $body[2]=="0.00" && $body[3]=="0.00" && $body[4]=="0.00" && $body[5]=="0.00" && $body[6]=="0.00" && $body[7]=="0.00" && $body[8]=="0.00" && $body[9]=="0.00" && $body[10]=="0.00" && $body[11]=="0.00") {
            if ($crSaldo != "M") {
                $saldo=($salIni+$rec["cie_mdebe"])-$rec["cie_mhaber"];
                $salIni+=$rec["salMes"];
            } else {
                $saldo=$rec["salMes"];
            }

            // TASA DE CAMBIO
            if ($crMoneda != "L") {
                $saldo/=$pTcam;
            }
            $body[$rec["cie_mes"]-1] = number_format($saldo, 2, '.', ',');
            $ctaAnt=$rec["cie_cta"];
            $ctaNomAnt=$rec["cta_nom"];
            $ctaNivAnt=$rec["cta_niv"];
            continue;
        }        
        
        $i=$iIni;
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow($i++,  $j, $ctaAnt)
            ->setCellValueByColumnAndRow($i,  $j, utf8_encode($ctaNomAnt));

        foreach ($body as $key => $value) {
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($key+2,  $j, $value);
        }
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow(14, $j, '=SUM(C'.($j).':N'.($j).')');
        
        $salIni=0;
        $body = array(0,0,0,0,0,0,0,0,0,0,0,0);
        $j++;

        if ($rec["cta_niv"]!=$ctaNivAnt) {
            $j++;
        }
    }

    if ($crSaldo != "M") {
        $saldo=($salIni+$rec["cie_mdebe"])-$rec["cie_mhaber"];
        $salIni+=$rec["salMes"];
    } else {
        $saldo=$rec["salMes"];
    }

    // TASA DE CAMBIO
    if ($crMoneda != "L") {
        $saldo/=$pTcam;
    }

    if (substr($rec["cie_cta"],0,1)>'19999999999' && $saldo<0) {
        $saldo=$saldo*-1;
    }

    $i=$iIni+2;
    $body[$rec["cie_mes"]-1] = $saldo;

    $ctaAnt=$rec["cie_cta"];
    $ctaNomAnt=$rec["cta_nom"];
    $ctaNivAnt=$rec["cta_niv"];
}
if ($body[0]!="0.00" || $body[1]!="0.00" || $body[2]!="0.00" || $body[3]!="0.00" || $body[4]!="0.00" || $body[5]!="0.00" || $body[6]!="0.00" || $body[7]!="0.00" || $body[8]!="0.00" || $body[9]!="0.00" || $body[10]!="0.00" || $body[11]!="0.00") {
    $i=$iIni;
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow($i++,  $j, $ctaAnt)
        ->setCellValueByColumnAndRow($i,  $j, utf8_encode($ctaNomAnt));

    foreach ($body as $key => $value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($key+2,  $j, $value);
    }
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow(14, $j, '=SUM(C'.($j).':N'.($j).')');
}
# ESTILO HOJA
$xCenter = array(
    'font' => array(
        'bold' => true,
    ),
	'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

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

# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('C7'.':O'.$j)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A7'.':A'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

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

# ESTABLECER TITULOS
$objPHPExcel->setActiveSheetIndex($sheet['cierres'])->setTitle('Cuadro Anual Cuentas de Balance');

# 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="Cuadro Anual Cuentas de Balance.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;
?>