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

$dtFecI=$_GET["dtFecI"];
$dtFecF=$_GET["dtFecF"];

# QUERYS
function sMovAcu0($selBan) {
    global $empCod,$dtFecI,$dtFecF;
    return "SELECT ma_emp,ma_ban,
            SUM(ma_debe) AS ma_sdebe, 
            SUM(ma_haber) AS ma_shaber 
            FROM mov_acu WHERE ma_emp='$empCod' AND ma_ban='$selBan' AND ma_fec>='$dtFecI' GROUP BY '$empCod','$selBan'";
}            
function sMovAcu($selBan) {
    global $empCod,$dtFecI,$dtFecF;
    return "SELECT ma_emp,ma_ban,
            SUM(ma_debe) AS ma_sdebe, 
            SUM(ma_haber) AS ma_shaber 
            FROM mov_acu WHERE ma_emp='$empCod' AND ma_ban='$selBan' AND ma_fec>='$dtFecI' AND ma_fec<='$dtFecF' GROUP BY '$empCod','$selBan'";
}            

    
function sSaldob($selBan) {
    global $empCod,$dtFecI,$dtFecF;
    return "SELECT * FROM saldob WHERE salb_emp='$empCod' AND salb_num=$selBan";
}

$sBancos = "SELECT *,
            TRIM(ban_nom) AS ban_nom,
            TRIM(ban_ctab) AS ban_ctab 
            FROM bancos WHERE ban_emp='$empCod'";

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

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

$bold17 = array(
    'font' => array(
        'bold' => true,
        'size' => 13,
    ),
);

# HOJAS
$sheet['consolidado']=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['consolidado'])
	->setCellValueByColumnAndRow($i,	$j++, utf8_encode($empNom))
    ->setCellValueByColumnAndRow($i, $j++, utf8_encode("CONSOLIDADO DE SALDOS DEL ".strftime("%d/%m/%Y", strtotime($dtFecI))." AL ".strftime("%d/%m/%Y", strtotime($dtFecF))));
    $objPHPExcel->getActiveSheet()->getStyle('A1:F4')->applyFromArray($bold17);

$j++;

$i=$iIni;
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':F'.$j)->applyFromArray($bordersThin);
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, 'Codigo')
    ->setCellValueByColumnAndRow($i++,  $j, 'Descripcion')
    ->setCellValueByColumnAndRow($i++,  $j, 'Saldo Inicial')
    ->setCellValueByColumnAndRow($i++,  $j, 'Ingresos')
    ->setCellValueByColumnAndRow($i++,  $j, 'Egresos')
    ->setCellValueByColumnAndRow($i++,  $j, 'Saldo Actual');


# VALORES PRIMER HOJA
$totsini = 0;
$totdebe = 0;
$tothaber = 0;
$totsact = 0;

$j++;

# CREA EL CICLO PARA EL LISTADO DE MOVIMIENTOS

$select["bancos"] = $db->query($sBancos);
while ($rec = $db->fetchAssoc($select['bancos'])) {
    $selBan = $rec["ban_num"];
    $banNom = $rec["ban_nom"];

    $select["mov_acu"] = $db->query(sMovAcu0($selBan));
    $recma0 = $db->fetchAssoc($select['mov_acu']);
    $sDebemov=$recma0["ma_sdebe"];
    $sHabermov=$recma0["ma_shaber"];

    $select["mov_acu"] = $db->query(sMovAcu($selBan));
    $recma = $db->fetchAssoc($select['mov_acu']);
    $sDebemova=$recma["ma_sdebe"];
    $sHabermova=$recma["ma_shaber"];

    $select["saldob"]=$db->query(sSaldob($selBan));
    $recsal = $db->fetchAssoc($select['saldob']);
    $Saldo=$recsal["salb_saldo"];
    $salIni=($Saldo-$sDebemov)+$sHabermov;
    $salAct=($salIni+$sDebemova)-$sHabermova;

    $totsini += $salIni;
    $totdebe += $sDebemova;
    $tothaber += $sHabermova;
    $totsact += $salAct;

    $i=$iIni;

    $objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, $selBan)
    ->setCellValueByColumnAndRow($i++,  $j, utf8_encode($banNom))
    ->setCellValueByColumnAndRow($i++,  $j, round($salIni,2))
    ->setCellValueByColumnAndRow($i++,  $j, (round($sDebemova,2) != 0) ? $sDebemova : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($sHabermova,2) != 0) ? $sHabermova : "")
    ->setCellValueByColumnAndRow($i++,  $j, round($salAct,2));

    $j++;

    $linea=2;
}


$j++;

// TOTALES DEL MOVIMIENTO
$objPHPExcel->getActiveSheet()->getStyle('C'.$j.':F'.$j)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('C'.$j.':F'.$j)->applyFromArray($borderBottomDouble);

$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(1, $j, 'Totales')
    ->setCellValueByColumnAndRow(2, $j, '=SUM(C5:C'.($j-1).')')
    ->setCellValueByColumnAndRow(3, $j, '=SUM(D5:D'.($j-1).')') 
    ->setCellValueByColumnAndRow(4, $j, '=SUM(E5:E'.($j-1).')')
    ->setCellValueByColumnAndRow(5, $j, '=SUM(F5:F'.($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.':F'.$q)->getStyle('A'.$q)->applyFromArray($xCenter);
}

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(8);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(17);

# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('C5'.':F'.$j)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A5'.':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['consolidado'])->setTitle('Consolidado 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="Consolidado 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;
?>