<?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"];
$selBan=$_GET["selBan"];

# QUERYS
$sMovAcu0 = "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'";

$sMovAcu = "SELECT *,
            TRIM(ma_bene) AS ma_bene,
            TRIM(ma_con) AS ma_con 
            FROM mov_acu LEFT JOIN tipopol ON mov_acu.ma_tipo=tipopol.tp_cod WHERE ma_emp='$empCod' AND ma_ban='$selBan' AND ma_fec>='$dtFecI' AND ma_fec<='$dtFecF' ORDER BY ma_fec,ma_tipo";
    
$sSaldob = "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' AND ban_num=$selBan";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["mov_acu"] = $db->query($sMovAcu0);
$recma0 = $db->fetchAssoc($select['mov_acu']);
$sDebemov=$recma0["ma_sdebe"];
$sHabermov=$recma0["ma_shaber"];

$select["bancos"]=$db->query($sBancos);
$recban = $db->fetchAssoc($select['bancos']);
$banNom=$recban["ban_nom"];
$banCtab=$recban["ban_ctab"];

$select["saldob"]=$db->query($sSaldob);
$recsal = $db->fetchAssoc($select['saldob']);
$Saldo=$recsal["salb_saldo"];

$salIni=($Saldo-$sDebemov)+$sHabermov;
$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['saldos']=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['saldos'])
	->setCellValueByColumnAndRow($i,	$j++, utf8_encode($empNom))
    ->setCellValueByColumnAndRow($i, $j++, utf8_encode("MOVIMIENTOS BANCARIOS DEL ".strftime("%d/%m/%Y", strtotime($dtFecI))." AL ".strftime("%d/%m/%Y", strtotime($dtFecF))))
	->setCellValueByColumnAndRow($i,   $j++, utf8_encode("BANCO: ".$banNom."  CUENTA BANCARIA: ".$banCtab))
        ->setCellValueByColumnAndRow(6, 4, "Saldo Inicial: ")
        ->setCellValueByColumnAndRow(7, 4, $salIni);
    $objPHPExcel->getActiveSheet()->getStyle('A4:I5')->applyFromArray($bold17);

$j++;

$i=$iIni;
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':H'.$j)->applyFromArray($bordersThin);
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, 'Tipo')
    ->setCellValueByColumnAndRow($i++,  $j, 'Numero')
    ->setCellValueByColumnAndRow($i++,  $j, 'Fecha')
    ->setCellValueByColumnAndRow($i++,  $j, 'Beneficiario')
    ->setCellValueByColumnAndRow($i++,  $j, 'Concepto')
    ->setCellValueByColumnAndRow($i++,  $j, 'Ingresos')
    ->setCellValueByColumnAndRow($i++,  $j, 'Egresos')
    ->setCellValueByColumnAndRow($i++,  $j, 'Saldo');


# VALORES PRIMER HOJA
$debe = 0;
$haber = 0;
$Saldo = $salIni;

$j++;

# CREA EL CICLO PARA EL LISTADO DE MOVIMIENTOS

$select["mov_acu"] = $db->query($sMovAcu);
while ($rec = $db->fetchAssoc($select['mov_acu'])) {
    $debe += $rec["ma_debe"];
    $haber += $rec["ma_haber"];
    $Saldo = ($Saldo+$rec["ma_debe"])-$rec["ma_haber"];

    $i=$iIni;

    $objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, $rec["tp_abrev"])
    ->setCellValueByColumnAndRow($i++,  $j, $rec["ma_num"])
    ->setCellValueByColumnAndRow($i++,  $j, strftime("%d/%m/%Y", strtotime($rec["ma_fec"])))
    ->setCellValueByColumnAndRow($i++,  $j, TRIM(utf8_encode($rec["ma_bene"])))
    ->setCellValueByColumnAndRow($i++,  $j, TRIM(utf8_encode($rec["ma_con"])))
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["ma_debe"],2) != 0) ? $rec["ma_debe"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($rec["ma_haber"],2) != 0) ? $rec["ma_haber"] : "")
    ->setCellValueByColumnAndRow($i++,  $j, $Saldo);

    $j++;

    $linea=2;
}


$j++;

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

$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(4, $j, 'Totales')
    ->setCellValueByColumnAndRow(5, $j, '=SUM(F6:F'.($j-1).')')
    ->setCellValueByColumnAndRow(6, $j, '=SUM(G6:G'.($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.':G'.$q)->getStyle('A'.$q)->applyFromArray($xCenter);
}

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(8);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(14);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(60);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(17);

# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('F6'.':H'.$j)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('B6'.':B'.$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['saldos'])->setTitle('Saldo');

# 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="Saldos al dia.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;
?>