<?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'];

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

# QUERYS
if ($selTipoCod == "999") {
    $sPolizas = "SELECT * FROM polizas p LEFT JOIN tipopol tp ON p.pol_tipo=tp.tp_cod WHERE pol_emp='$empCod' AND pol_fec>='$dtFecI' AND pol_fec<='$dtFecF'";
} else {
    $sPolizas = "SELECT * FROM polizas p LEFT JOIN tipopol tp ON p.pol_tipo=tp.tp_cod WHERE pol_emp='$empCod' AND pol_fec>='$dtFecI' AND pol_fec<='$dtFecF' AND pol_tipo='$selTipoCod'";
}

function sPoli_det($dtFec, $selBanCod, $selTipoCod, $numNum) {
    global $empCod;
    return "SELECT * FROM poli_det WHERE pold_emp='$empCod' AND pold_fec='$dtFec' AND pold_ban='$selBanCod' AND pold_tipo='$selTipoCod' AND pold_num='$numNum'";
}

# EJECUCION DE QUERYS
$db = new dbExec();
$select["polizas"] = $db->query($sPolizas);

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

$colIni=0;
$objPHPExcel = new PHPExcel();

# CREAR HOJAS
for ($col=0; $col < 1; $col++) { 
	$objPHPExcel->createSheet();
}

# HOJAS
$sheet['polizas']=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
$col=$colIni;
$objPHPExcel->setActiveSheetIndex($sheet['polizas'])
	->setCellValueByColumnAndRow($col, 1, $empNom)
	->setCellValueByColumnAndRow($col, 2, "Listado de polizas del ".strftime("%d/%m/%Y", strtotime($dtFecI))." al ".strftime("%d/%m/%Y", strtotime($dtFecF)));

# VALORES PRIMER HOJA
$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
        )
    )
);

$rowVal = 4;
$row = $rowVal;
while ($rec = $db->fetchAssoc($select['polizas'])) {
	# ENCABEZADO DEL DOCUMENTO
	$col=$colIni;
	$objPHPExcel->setActiveSheetIndex($sheet['polizas'])
		->setCellValueByColumnAndRow($col,	 $row++, 'Tipo de Póliza: '.$rec['tp_nom'])
		->setCellValueByColumnAndRow($col,	 $row, 'Número de Póliza: '.$rec['pol_tipo'].'-'.$rec['pol_num'])
		->setCellValueByColumnAndRow($col+2, $row++, 'Fecha: '.strftime("%d/%m/%Y", strtotime($rec["pol_fec"])))
		->setCellValueByColumnAndRow($col,	 $row++, 'Concepto: '.utf8_encode($rec['pol_con']))
		->setCellValueByColumnAndRow($col++, $row, 'Cuenta')
		->setCellValueByColumnAndRow($col++, $row, 'Nombre de Cuenta')
		->setCellValueByColumnAndRow($col++, $row, 'Debe')
		->setCellValueByColumnAndRow($col++, $row, 'Haber');

	# ESTILO ENCABEZADO DEL DOCUMENTO
	$objPHPExcel->getActiveSheet()->getStyle('A'.$row.':D'.$row)->applyFromArray($bordersThin);
	
	# DETALLE DEL DOCUMENTO
	$select["poli_det"] = $db->query(sPoli_det($rec["pol_fec"], $rec["pol_ban"], $rec["pol_tipo"], $rec["pol_num"]));

	$row++;
	$rowIni = $row;
	while ($recTbl = $db->fetchAssoc($select['poli_det'])) {
		$col=$colIni;
		$objPHPExcel->getActiveSheet()
			->setCellValueByColumnAndRow($col++, $row, $recTbl['pold_cta'])
			->setCellValueByColumnAndRow($col++, $row, utf8_decode($recTbl['pold_ctan']))
			->setCellValueByColumnAndRow($col++, $row, ($recTbl["pold_debe"] != 0) ? $recTbl["pold_debe"] : "")
			->setCellValueByColumnAndRow($col, $row, ($recTbl["pold_haber"] != 0) ? $recTbl["pold_haber"] : "");
		$row++;
	}

	$col = $colIni+1;
	$objPHPExcel->getActiveSheet()
		->setCellValueByColumnAndRow($col++, $row, 'Totales del documento')
		->setCellValueByColumnAndRow($col++, $row, '=SUM(C'.$rowIni.':C'.($row-1).')')
		->setCellValueByColumnAndRow($col, $row, '=SUM(D'.$rowIni.':D'.($row-1).')');

	# FORMATO NUMERICO
	$objPHPExcel->getActiveSheet()->getStyle('C'.$rowIni.':C'.$row)->getNumberFormat()->setFormatCode('#,##0.00');
	$objPHPExcel->getActiveSheet()->getStyle('D'.$rowIni.':D'.$row)->getNumberFormat()->setFormatCode('#,##0.00');

	# ESTILO TOTAL
	$objPHPExcel->getActiveSheet()->getStyle('C'.$row.':D'.$row)->applyFromArray($borderTopThin);
	$objPHPExcel->getActiveSheet()->getStyle('C'.$row.':D'.$row)->applyFromArray($borderBottomDouble);

	$row+=2;
}
$col = $colIni+1;
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($col++, $row, 'Totales Generales')
	->setCellValueByColumnAndRow($col++, $row, '=SUMIF(B'.($rowVal+2).':B'.($row-2).',"Totales del documento",C'.($rowVal+2).':C'.($row-2).')')
	->setCellValueByColumnAndRow($col, $row, '=SUMIF(B'.($rowVal+2).':B'.($row-2).',"Totales del documento",D'.($rowVal+2).':D'.($row-2).')');

# FORMATO NUMERICO
$objPHPExcel->getActiveSheet()->getStyle('C'.$row)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('D'.$row)->getNumberFormat()->setFormatCode('#,##0.00');

# ESTILO TOTAL
$objPHPExcel->getActiveSheet()->getStyle('C'.$row.':D'.$row)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('C'.$row.':D'.$row)->applyFromArray($borderBottomDouble);

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

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

$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); 

$objPHPExcel->getActiveSheet()->mergeCells('A1:D1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:D2')->getStyle('A2')->applyFromArray($styFec);

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

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