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

$selMes=$_GET["selMes"];
$numAno=$_GET["numAno"];
$txtFecl=$_GET["txtFecl"];
$txtTitulo=$_GET["txtTitulo"];
$selNiv=$_GET["selNiv"];
$numHoja=$_GET["numHoja"];
$crMoneda=$_GET["crMoneda"];
$textoMoneda=$_GET["textoMoneda"];
$cbSinPol=$_GET["cbSinPol"];
$cbFecsn=$_GET["cbFecsn"];
$cbNoFol=$_GET["cbNoFol"];
$txtLeyenda=$_GET["txtLeyenda"];

$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,
                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<=$selMes
            GROUP BY c.cie_cta, cie_mes=$selMes";

$sPoliDet = "SELECT 
                TRIM(p.pold_cta) AS pold_cta,
                pold_debe,
                pold_haber
            FROM poli_det p
            INNER JOIN cuentas cta ON p.pold_emp=cta.cta_emp AND p.pold_cta=cta.cta
            WHERE pold_emp='$empCod' AND YEAR(pold_fec)=$numAno AND pold_tipo='$tipoCierre'
            GROUP BY p.pold_cta";

function sCuentas($cta) { 
    global $empCod;
    return "SELECT TRIM(cta_acta) AS cta_acta FROM cuentas WHERE cta_emp='$empCod' AND cta='$cta'";
}

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

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

$func = new functions();
// RESTAR POLIZA DE CIERRE
if ($func->stringToBool($cbSinPol) && $selMes==12) {
    while ($rec = $db->fetchAssoc($select['poli_det'])) {
        $cta = $rec["pold_cta"];
        while (!empty($cta)) {
            $fetchAssoc["cuentas"] = $db->sFetchAssoc(sCuentas($cta));
            $ctaActa = trim($fetchAssoc["cuentas"]["cta_acta"]);
            
            $i = $func->multiSearch($arrayCie, array('cie_cta' => $cta, 'cie_mes' => $selMes));
            $arrayCie[$i]["cie_mdebe"]-=$rec["pold_debe"];
            $arrayCie[$i]["cie_mhaber"]-=$rec["pold_haber"];
            $arrayCie[$i]["salMes"]=$arrayCie[$i]["cie_mdebe"]-$arrayCie[$i]["cie_mhaber"];

            $cta = $ctaActa;
        }
    }
}

/** 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['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++, utf8_encode($txtTitulo))
	->setCellValueByColumnAndRow($i,	$j++, utf8_encode("Al ".$txtFecl))
	->setCellValueByColumnAndRow($i,	$j++, "Cifras Expresadas en ".$textoMoneda);

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

$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++,	$j, 'Cuenta')
	->setCellValueByColumnAndRow($i++,	$j, 'Nombre de Cuenta')
	->setCellValueByColumnAndRow($i++,	$j, 'Saldo Inicial')
	->setCellValueByColumnAndRow($i++,	$j, 'Debe Mes')
	->setCellValueByColumnAndRow($i++,	$j, 'Haber Mes')
	->setCellValueByColumnAndRow($i++,	$j, 'Saldo Mes')
	->setCellValueByColumnAndRow($i++,	$j, 'Saldo Actual');


# VALORES PRIMER HOJA
$totCta = "";
$totSalIni = 0;
$totDebe = 0;
$totHaber = 0;
$totSalMes = 0;
$totSalAct = 0;

$totDebeMov = 0;
$totHaberMov = 0;

$ctaPrinAnt=1;
$ctaNivAnt=1;

$salIni=0;

$j++;
$k=0;
$k=0;
foreach ($arrayCie as $rec) {
    $rec["salIni"]=$salIni;
    $k++;
    if ($rec["cie_mes"]!=$selMes) {
        $salIni=$rec["salMes"];

        if ($k<sizeof($arrayCie)) {
            if ($arrayCie[$k]["cie_cta"]==$rec["cie_cta"]){
                continue;
            }
        }
        $rec["salIni"]=$salIni;
    }
    if ($rec["salIni"]!=0 || $rec["cie_mdebe"]!=0 || $rec["cie_mhaber"]!=0) {

        // MES NO TRABAJADO
        if ($rec["cie_mes"]!=$selMes) {
            $rec["cie_mdebe"]=0;
            $rec["cie_mhaber"]=0;
            $rec["salMes"]=0;
        }

        $salAct=($rec["salIni"]+$rec["cie_mdebe"])-$rec["cie_mhaber"];

        // PARA INVERTIR SIGNOS
        if ($rec["cie_cta"][0] == "2" || $rec["cie_cta"][0] == "3" || $rec["cie_cta"][0] == "4") {
            $rec["salIni"]*=(-1);
            $rec["salMes"]*=(-1);
            $salAct*=(-1);
        }

        // TASA DE CAMBIO
        if ($crMoneda != "L") {
            $rec["salIni"]/=$pTcam;
            $rec["cie_mdebe"]/=$pTcam;
            $rec["cie_mhaber"]/=$pTcam;
            $rec["salMes"]/=$pTcam;
            $salAct/=$pTcam;
        }

        // AGREGA FILA TOTALES
        if ($rec["cie_cta"][0] != $ctaPrinAnt && $rec["cta_niv"]==1) {
        	$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($borderTopThin);
        	$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($borderBottomDouble);
            $i=$iIni+1;
			$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++,	$j, "TOTAL DE ".$totCta)
				->setCellValueByColumnAndRow($i++,	$j, (round($totSalIni, 2) != 0) ? $totSalIni : "")
				->setCellValueByColumnAndRow($i++,	$j, (round($totDebe, 2) != 0) ? $totDebe : "")
				->setCellValueByColumnAndRow($i++,	$j, (round($totHaber, 2) != 0) ? $totHaber : "")
				->setCellValueByColumnAndRow($i++,	$j, (round($totSalMes, 2) != 0) ? $totSalMes : "")
				->setCellValueByColumnAndRow($i++,	$j, (round($totSalAct, 2) != 0) ? $totSalAct : "");
			$j++;
        }

        // ACUMULAR TOTALES DEL MOVIMIENTO
        if ($rec["cta_con"] == "N") {
            $totDebeMov += $rec["cie_mdebe"];
            $totHaberMov += $rec["cie_mhaber"];
        }

        // AGREGA FILA CUENTAS
        if ($rec["cta_niv"]<=$selNiv) {
			$i=$iIni;
			$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++,	$j, $rec["cie_cta"])
				->setCellValueByColumnAndRow($i++,	$j, utf8_encode($rec["cta_nom"]))
				->setCellValueByColumnAndRow($i++,	$j, (round($rec["salIni"], 2) != 0) ? $rec["salIni"] : "")
				->setCellValueByColumnAndRow($i++,	$j, (round($rec["cie_mdebe"], 2) != 0) ? $rec["cie_mdebe"] : "")
				->setCellValueByColumnAndRow($i++,	$j, (round($rec["cie_mhaber"], 2) != 0) ? $rec["cie_mhaber"] : "")
				->setCellValueByColumnAndRow($i++,	$j, (round($rec["salMes"], 2) != 0) ? $rec["salMes"] : "")
				->setCellValueByColumnAndRow($i++,	$j, (round($salAct, 2) != 0) ? $salAct : "");
			$j++;
            $salIni=0;
        }

        // VALORES PARA TOTALES
        if ($rec["cta_niv"]==1) {
            $totCta = utf8_encode($rec["cta_nom"]);
            $totSalIni = $rec["salIni"];
            $totDebe = $rec["cie_mdebe"];
            $totHaber = $rec["cie_mhaber"];
            $totSalMes = $rec["salMes"];
            $totSalAct = $salAct;
        }

        $ctaPrinAnt=$rec["cie_cta"][0];
        $ctaNivAnt=$rec["cta_niv"];
    }
}

// AGREGA FILA TOTALES
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($borderBottomDouble);
$i=$iIni+1;
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++,	$j, "TOTAL DE ".$totCta)
	->setCellValueByColumnAndRow($i++,	$j, (round($totSalIni, 2) != 0) ? $totSalIni : "")
	->setCellValueByColumnAndRow($i++,	$j, (round($totDebe, 2) != 0) ? $totDebe : "")
	->setCellValueByColumnAndRow($i++,	$j, (round($totHaber, 2) != 0) ? $totHaber : "")
	->setCellValueByColumnAndRow($i++,	$j, (round($totSalMes, 2) != 0) ? $totSalMes : "")
	->setCellValueByColumnAndRow($i++,	$j, (round($totSalAct, 2) != 0) ? $totSalAct : "");
$j+=2;

// TOTALES DEL MOVIMIENTO
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($borderBottomDouble);
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow(1,	$j, "SUMA DEL MOVIMIENTO")
	->setCellValueByColumnAndRow(3,	$j, (round($totDebeMov, 2) != 0) ? $totDebeMov : "")
	->setCellValueByColumnAndRow(4,	$j, (round($totHaberMov, 2) != 0) ? $totHaberMov : "");

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

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

# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('C6'.':G'.$j)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A6'.':A'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

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

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

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