<?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/maxExecTime.php');

$empCod = $_SESSION['empCod'];
$empNom = $_SESSION['empNom'];

$tipoPol="018";
$numTr=$_GET["numTr"];
$selBanCod=$_GET["selBanCod"];
$selBanNom=$_GET["selBanNom"];

# QUERYS
$sIva_comp = "SELECT *, trim(iva_prov) AS iva_prov, trim(iva_serie) AS iva_serie FROM iva_comp i 
                  LEFT JOIN provee p ON i.iva_nit=p.pro_nit 
                  WHERE iva_emp='$empCod' AND iva_ban='$selBanCod' AND iva_cheque='$numTr'";


# EJECUCION DE QUERYS
$db = new dbExec();
$select["iva_comp"] = $db->query($sIva_comp);
$db->close();

/** 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;
$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['iva_comp']=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=5;
$objPHPExcel->setActiveSheetIndex($sheet['iva_comp'])
			->setCellValueByColumnAndRow($i, 1, trim($empNom))
            ->setCellValueByColumnAndRow($i, 2, trim(utf8_decode("Listado de Documentos Relacionados a una Transferencia")))
			->setCellValueByColumnAndRow($i, 3, "Cuenta: ".trim($selBanNom)." Transferencia No. ".$numTr)
            ->setCellValueByColumnAndRow($i++, $j, 'Serie')
			->setCellValueByColumnAndRow($i++, $j, 'Numero')
			->setCellValueByColumnAndRow($i++, $j, 'Fecha')
			->setCellValueByColumnAndRow($i++, $j, 'Nit')
			->setCellValueByColumnAndRow($i++, $j, 'Proveedor')
			->setCellValueByColumnAndRow($i++, $j, 'Valor');
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':F'.$j)->applyFromArray($bordersThin);			

# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'bold' => true,
        'size' => 12,
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styFec = array(
	'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styEncabezado = array(
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);

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

$objPHPExcel->getActiveSheet()->mergeCells('A1:F1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:F2')->getStyle('A2')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->mergeCells('A3:F3')->getStyle('A3')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->getStyle('A5:F4')->applyFromArray($styEncabezado);

# VALORES PRIMER HOJA
$i=$iIni;
for ($j=6; $rec = $db->fetchAssoc($select['iva_comp']); $j++) {
	$objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, $rec['iva_serie'])
				->setCellValueByColumnAndRow($i++, $j, $rec['iva_num'])
				->setCellValueByColumnAndRow($i++, $j, strftime("%d/%m/%Y", strtotime($rec["iva_fec"])))
				->setCellValueByColumnAndRow($i++, $j, trim(utf8_encode($rec["iva_nit"])))
				->setCellValueByColumnAndRow($i++, $j, trim(utf8_encode($rec["iva_prov"])))
				->setCellValueByColumnAndRow($i++, $j, (round($rec["iva_tot"]+$rec["iva_dedu"],2)));
	$i=$iIni;
}

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

$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(4, $j, 'Total')
    ->setCellValueByColumnAndRow(5, $j, '=SUM(F6:F'.($j-1).')'); 

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(60);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(17);

# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('F6'.':F'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');

# ESTABLECER TITULOS
$objPHPExcel->setActiveSheetIndex($sheet['iva_comp'])->setTitle('iva_comp');

# 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="LisDocTransf.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;
?>