<?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'];
$empConso=utf8_decode($_SESSION["empConso"]);

$dtFecI=$_GET["dtFecI"];
$dtFecF=$_GET["dtFecF"];
$txtCtai=$_GET["txtCtai"];
$txtCtaiNom=$_GET["txtCtaiNom"];
$cbFecsn=$_GET["cbFecsn"];

$numAno=date("Y", strtotime($dtFecI));
$numMes=date("m", strtotime($dtFecI));

# QUERYS
$sCierres = "SELECT
                c.cie_mes,
                cta.cta_niv,
                cta.cta_con,
                TRIM(c.cie_cta) AS cie_cta,
                TRIM(cta.cta_nom) AS cta_nom,
                TRIM(cta.cta_acta) AS cta_acta,
                (0) AS salIni,
                SUM(cie_mdebe) AS cie_mdebe,
                SUM(cie_mhaber) AS cie_mhaber,
                (SUM(cie_mdebe)-SUM(cie_mhaber)) AS salMes
            FROM empresas emp 
            LEFT JOIN cierres c ON c.cie_emp=emp.emp_cod
            INNER JOIN cuentas cta ON c.cie_emp=cta.cta_emp AND c.cie_cta=cta.cta
            WHERE emp.emp_conso='$empConso' AND c.cie_cta='$txtCtai' AND c.cie_ano=$numAno AND c.cie_mes<=$numMes
            GROUP BY c.cie_cta, c.cie_mes=$numMes";

$sPoliDet = "SELECT *,
             TRIM(pd.pold_cta) AS pold_cta
            FROM empresas emp 
            LEFT JOIN poli_det pd ON pd.pold_emp=emp.emp_cod 
            LEFT JOIN polizas p ON pd.pold_emp=p.pol_emp AND pd.pold_ban=p.pol_ban AND pd.pold_tipo=p.pol_tipo AND pd.pold_fec=p.pol_fec AND pd.pold_num=p.pol_num AND pd.pold_tipoi=p.pol_tipoi AND pd.pold_nit=p.pol_nit 
            WHERE emp.emp_conso='$empConso' AND pd.pold_cta='$txtCtai' AND pd.pold_fec>='$dtFecI' AND pd.pold_fec<='$dtFecF' ORDER BY pold_fec,pold_tipo,pold_ban,pold_num";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["cierres"] = $db->query($sCierres);
$select["poli_det"]=$db->query($sPoliDet);

$arrayCie=$db->fetchAll($select["cierres"]);

/** 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['integracion']=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
$bold17 = array(
    'font' => array(
        'bold' => true,
        'size' => 13,
    ),
);

$col=$colIni;
$objPHPExcel->setActiveSheetIndex($sheet['integracion'])
	->setCellValueByColumnAndRow($col, 1, $empNom)
	->setCellValueByColumnAndRow($col, 2, utf8_encode("INTEGRACION DE UNA CUENTA DEL ".strftime("%d/%m/%Y", strtotime($dtFecI))." AL ".strftime("%d/%m/%Y", strtotime($dtFecF))));

// Para Llegar al saldo inicial de la fecha inicial
$salIni=0;
$k=0;
foreach ($arrayCie as $rec) {
    $rec["salIni"]=$salIni;
    $k++;
    if ($rec["cie_mes"]!=$numMes) {
        $salIni=$rec["salMes"];

        if ($k<sizeof($arrayCie)) {
            if ($arrayCie[$k]["cie_cta"]==$rec["cie_cta"]){
                continue;
            }
        }
        $rec["salIni"]=$salIni;
    }
	$objPHPExcel->setActiveSheetIndex($sheet['integracion'])
		->setCellValueByColumnAndRow($col, 4, utf8_encode("CUENTA:  ".$txtCtai." - ".$rec["cta_nom"]))
		->setCellValueByColumnAndRow(6, 5, "Saldo Inicial: ")
		->setCellValueByColumnAndRow(8, 5, $rec["salIni"]);
	$objPHPExcel->getActiveSheet()->getStyle('A5:I5')->applyFromArray($bold17);
}

$objPHPExcel->setActiveSheetIndex($sheet['integracion'])
	->setCellValueByColumnAndRow($col++, 6, 'No. Docto')
	->setCellValueByColumnAndRow($col++, 6, 'Serie')
	->setCellValueByColumnAndRow($col++, 6, 'Nit')
	->setCellValueByColumnAndRow($col++, 6, 'Tipo')
	->setCellValueByColumnAndRow($col++, 6, 'Fecha')
	->setCellValueByColumnAndRow($col++, 6, 'Concepto')
	->setCellValueByColumnAndRow($col++, 6, 'Debe')
	->setCellValueByColumnAndRow($col++, 6, 'Haber')
	->setCellValueByColumnAndRow($col, 6, 'Saldo');

# 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
        )
    )
);

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

$objPHPExcel->getActiveSheet()->getStyle('A6:I6')->applyFromArray($bordersThin);

$rowIni = 7;

$Saldo = $salIni;

$row = $rowIni;
while ($rec = $db->fetchAssoc($select['poli_det'])) {
    $Saldo = ($Saldo+$rec["pold_debe"])-$rec["pold_haber"];

	$col=$colIni;
	$objPHPExcel->getActiveSheet()
		->setCellValueByColumnAndRow($col++, $row, $rec['pold_num'])
		->setCellValueByColumnAndRow($col++, $row, $rec['pold_tipoi'])
		->setCellValueByColumnAndRow($col++, $row, $rec['pold_nit'])
		->setCellValueByColumnAndRow($col++, $row, $rec['pold_tipo'])
		->setCellValueByColumnAndRow($col++, $row, strftime("%d/%m/%Y", strtotime($rec["pold_fec"])))
		->setCellValueByColumnAndRow($col++, $row, utf8_encode($rec['pol_con']))
		->setCellValueByColumnAndRow($col++, $row, (round($rec["pold_debe"],2) != 0) ? $rec["pold_debe"] : "")
		->setCellValueByColumnAndRow($col++, $row, (round($rec["pold_haber"],2) != 0) ? $rec["pold_haber"] : "")
		->setCellValueByColumnAndRow($col, $row, $Saldo);

	$row++;
}

$col = 5;
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($col++, $row, 'Totales')
	->setCellValueByColumnAndRow($col++, $row, '=SUM(G'.$rowIni.':G'.($row-1).')')
	->setCellValueByColumnAndRow($col, $row, '=SUM(H'.$rowIni.':H'.($row-1).')');

$rowTot = $row; 

# FORMATO NUMERICO
$objPHPExcel->getActiveSheet()->getStyle('G'.$rowIni.':G'.$row)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('H'.$rowIni.':H'.$row)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('I'.($rowIni-2).':I'.$row)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A'.$rowIni.':A'.$row)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
$objPHPExcel->getActiveSheet()->getStyle('C'.$rowIni.':C'.$row)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);


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

$row+=2;
$objPHPExcel->getActiveSheet()->getStyle('B'.$row.':B'.($row+5))->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A'.$row.':B'.$row)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow(0, $row, 'Saldo Inicial: ')
	->setCellValueByColumnAndRow(1, $row++, '=I'.($rowIni-2))
	->setCellValueByColumnAndRow(0, $row, 'Suma Debe: ')
	->setCellValueByColumnAndRow(1, $row++, '=G'.$rowTot)
	->setCellValueByColumnAndRow(0, $row, 'Suma Haber: ')
	->setCellValueByColumnAndRow(1, $row++, '=H'.$rowTot)
	->setCellValueByColumnAndRow(0, $row, 'Suma Mes: ')
	->setCellValueByColumnAndRow(1, $row++, '=G'.$rowTot.'-H'.$rowTot)
	->setCellValueByColumnAndRow(0, $row, 'Suma Actual: ')
	->setCellValueByColumnAndRow(1, $row, '=(B'.($row-4).'+G'.$rowTot.')-H'.$rowTot);
$objPHPExcel->getActiveSheet()->getStyle('A'.$row.':B'.$row)->applyFromArray($borderBottomDouble);

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

# FORMATOS
$objPHPExcel->getActiveSheet()->mergeCells('A1:I1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:I2')->getStyle('A2')->applyFromArray($alignC);
$objPHPExcel->getActiveSheet()->mergeCells('A4:I4');
$objPHPExcel->getActiveSheet()->mergeCells('G5:H5');

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

# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('G6'.':I'.$row)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A5'.':A'.$row)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
$objPHPExcel->getActiveSheet()->getStyle('C5'.':C'.$row)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

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

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