<?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"];
$numHoja=$_GET["numHoja"];
$crMoneda=$_GET["crMoneda"];
$textoMoneda=$_GET["textoMoneda"];
$cbFecsn=$_GET["cbFecsn"];
$cbNoFol=$_GET["cbNoFol"];


# 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";

function sPoliDet($cta) { 
    global $empCod,$selMes,$numAno;
    return "SELECT *,
            TRIM(pd.pold_cta) AS pold_cta,
            TRIM(pd.pold_ctan) AS pold_ctan,
            TRIM(p.pol_con) AS pol_con,
            SUM(pold_debe) AS pold_debe,
            SUM(pold_haber) AS pold_haber
            FROM poli_det pd LEFT JOIN polizas p ON pd.pold_emp=p.pol_emp AND pd.pold_ban=p.pol_ban AND pd.pold_tipo=p.pol_tipo AND pd.pold_fec=p.pol_fec AND pd.pold_num=p.pol_num AND pd.pold_tipoi=p.pol_tipoi AND pd.pold_nit=p.pol_nit WHERE pd.pold_emp='$empCod' AND pd.pold_cta='$cta' AND YEAR(pd.pold_fec)='$numAno' AND MONTH(pd.pold_fec)='$selMes' GROUP BY pd.pold_tipo, pd.pold_cta";
}


# 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
        )
    )
);

$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++, utf8_encode("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');
$j++;

$i=$iIni;
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($bordersThin);
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, 'No. Docto')
    ->setCellValueByColumnAndRow($i++,  $j, 'Concepto')
    ->setCellValueByColumnAndRow($i++,  $j, 'Tipo')
    ->setCellValueByColumnAndRow($i++,  $j, 'Fecha')
    ->setCellValueByColumnAndRow($i++,  $j, 'Debe')
    ->setCellValueByColumnAndRow($i++,  $j, 'Haber')
    ->setCellValueByColumnAndRow($i++,  $j, 'Saldo');


# 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;
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;
    }

    $cta=$rec["cie_cta"];
    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"];

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

        // AGREGA FILA CUENTAS
		$i=$iIni;
        if ($rec["cta_con"]=="N") {
            $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($bordersThin);
        }
		$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++;

        if ($rec["cta_con"]=="N") {
          } else {
            $j++;
        }

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

        $debe = 0;
        $haber = 0;
        $Saldo = $salIni;
        if ($crMoneda != "L") {
            $Saldo/=$pTcam;
        }
        $linea=1;

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

        $select["poli_det"] = $db->query(sPoliDet($cta));


        while ($recPd = $db->fetchAssoc($select['poli_det'])) {
            // TASA DE CAMBIO
            if ($crMoneda != "L") {
                $recPd["pold_debe"]/=$pTcam;
                $recPd["pold_haber"]/=$pTcam;
            }
            $debe += $recPd["pold_debe"];
            $haber += $recPd["pold_haber"];
            $totDebe += $recPd["pold_debe"];
            $totHaber += $recPd["pold_haber"];
            $Saldo = ($Saldo+$recPd["pold_debe"])-$recPd["pold_haber"];

            $i=$iIni;

            $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow($i++,  $j, "9999999")
            ->setCellValueByColumnAndRow($i++,  $j, RTRIM(utf8_encode("MOVIMIENTO DEL MES")))
            ->setCellValueByColumnAndRow($i++,  $j, $recPd["pold_tipo"])
            ->setCellValueByColumnAndRow($i++,  $j, strftime("%d/%m/%Y", strtotime($recPd["pold_fec"])))
            ->setCellValueByColumnAndRow($i++,  $j, (round($recPd["pold_debe"],2) != 0) ? $recPd["pold_debe"] : "")
            ->setCellValueByColumnAndRow($i++,  $j, (round($recPd["pold_haber"],2) != 0) ? $recPd["pold_haber"] : "")
            ->setCellValueByColumnAndRow($i++,  $j, $Saldo);

            $j++;

            $linea=2;
        }

        if ($linea!=1) {
            $j++;
        }

        $salIni=0;
    }
}


$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(4,	$j, (round($totDebe, 2) != 0) ? $totDebe : "")
	->setCellValueByColumnAndRow(5
        ,	$j, (round($totHaber, 2) != 0) ? $totHaber : "");

# 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);
}

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(80);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(17);

# 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('Diario Mayor');

# 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="Diario Mayor General 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;
?>