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

# QUERYS
$sMovAcu= "SELECT *,
           TRIM(ma.ma_bene) AS ma_bene,
           TRIM(ma.ma_con) AS ma_con,
           TRIM(ban.ban_nom) AS ban_nom,
           TRIM(tp.tp_nom) AS tp_nom,
           TRIM(tp.tp_abrev) AS tp_abrev 
           FROM mov_acu AS ma 
           LEFT JOIN bancos AS ban ON ma.ma_emp=ban.ban_emp AND ma.ma_ban=ban.ban_num
           LEFT JOIN tipopol AS tp ON ma.ma_tipo=tp.tp_cod 
           WHERE ma_emp='$empCod' AND ma_tipo='004' AND ma_bene LIKE '%$txtBene%' AND ma_fec>='$dtFecI' AND ma_fec<='$dtFecF' ORDER BY ma_emp,ma_ban,ma_fec,ma_tipo";

# 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['listado']=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['listado'])
	->setCellValueByColumnAndRow($i,	$j++, utf8_encode($empNom))
    ->setCellValueByColumnAndRow($i, $j++, utf8_encode("LISTADO DE DOCUMENTOS DEL ".strftime("%d/%m/%Y", strtotime($dtFecI))." AL ".strftime("%d/%m/%Y", strtotime($dtFecF))))
    ->setCellValueByColumnAndRow($i, $j++, utf8_encode("CRITERIO DE BUSQUEDA: ".TRIM($txtBene)));
    $objPHPExcel->getActiveSheet()->getStyle('A1:G4')->applyFromArray($bold17);

$j++;

$i=$iIni;
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($bordersThin);
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, 'Cuenta')
    ->setCellValueByColumnAndRow($i++,  $j, 'Tipo')
    ->setCellValueByColumnAndRow($i++,  $j, 'Numero')
    ->setCellValueByColumnAndRow($i++,  $j, 'Fecha')
    ->setCellValueByColumnAndRow($i++,  $j, 'Beneficiario')
    ->setCellValueByColumnAndRow($i++,  $j, 'Concepto')
    ->setCellValueByColumnAndRow($i++,  $j, 'Monto');


# VALORES PRIMER HOJA

$j++;

# CREA EL CICLO PARA EL LISTADO DE MOVIMIENTOS

$select["mov_acu"] = $db->query($sMovAcu);
while ($rec = $db->fetchAssoc($select['mov_acu'])) {
    $i=$iIni;

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

    $j++;

    $linea=2;
}


$j++;

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

$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(5, $j, 'Total')
    ->setCellValueByColumnAndRow(6, $j, '=SUM(G5: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(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(06);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(14);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(17);

# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('G5'.':G'.$j)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('C5'.':C'.$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['listado'])->setTitle('Segun Beneficiario');

# 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="Reporte segun beneficiario.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;
?>