<?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"]);

$selMes=$_GET["selMes"];
$selMesNom=$_GET["selMesNom"];
$numAno=$_GET["numAno"];
$selBan=$_GET["selBan"];
$selBanNom=$_GET["selBanNom"];
$selBanCtab=$_GET["selBanCtab"];
$numAjus=$_GET["numAjus"];

if ($selMes == 12) {
  $selMesi = 1;
  $numAnoi = $numAno + 1;
} else {
  $selMesi = $selMes + 1;
  $numAnoi = $numAno;
}   
$numDiai = 1;
$Fecini = (strval($numAnoi)."-".strval($selMesi)."-".strval($numDiai));

# QUERYS
$sMova0cd = "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<'$Fecini' AND ma_stat='C' GROUP BY '$empCod','$selBan'";

$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>='$Fecini' GROUP BY '$empCod','$selBan'";

$sMovAcu = "SELECT *,
            TRIM(ma_bene) AS ma_bene,
            TRIM(ma_con) AS ma_con 
            FROM mov_acu WHERE ma_emp='$empCod' AND ma_ban='$selBan' AND ma_tipo='004' AND ma_fec<'$Fecini' AND ma_stat='C' AND ma_haber!=0.00 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";

$sConcilia = "SELECT * FROM concilia WHERE con_emp='$empCod' AND con_ban='$selBan' AND con_ano=$numAno AND con_mes=$selMes";

$sConci_det = "SELECT * FROM conci_det WHERE cd_emp='$empCod' AND cd_ban='$selBan' AND cd_ano=$numAno AND cd_mes=$selMes";

# 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["mov_acu"] = $db->query($sMova0cd);
$recma0 = $db->fetchAssoc($select['mov_acu']);
$sumCheques=$recma0["ma_shaber"];
$sumMovi=$recma0["ma_sdebe"];

$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"];

$salConta=($Saldo-$sDebemov)+$sHabermov;
$salCuenta=($salConta+$sumCheques)-($sumMovi+$numAjus);
$Saldo=0;

# Para saber si esta cerrada la conciliacion
$select["concilia"] = $db->query($sConcilia);
$fetchAssoc["concilia"] = $db->fetchAssoc($select["concilia"]);
if ($db->numRows($select["concilia"]) == 0) {
   $statcon = false;
   $stattxt ="CONCILIACION ABIERTA";
} else {
   $statcon = true;
   $stattxt ="CONCILIACION CERRADA";
}  

/** 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['conciliacion']=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['conciliacion'])
	->setCellValueByColumnAndRow($i,	$j++, utf8_encode($empNom))
    ->setCellValueByColumnAndRow($i, $j++, utf8_decode("CONCILIACION BANCARIA CORRESPONDIENTE A ".trim($selMesNom)." del ".$numAno))
	->setCellValueByColumnAndRow($i,   $j++, utf8_encode("BANCO: ".$banNom."  CUENTA BANCARIA: ".$banCtab))
    ->setCellValueByColumnAndRow($i,   $j++, utf8_encode($stattxt))
    ->setCellValueByColumnAndRow(0, 5, "CHEQUES EN CIRCULACION: ");
     $objPHPExcel->getActiveSheet()->getStyle('A5:D5')->applyFromArray($bold17);

$j++;

$i=$iIni;
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':D'.$j)->applyFromArray($bordersThin);
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, 'Cheque No.')
    ->setCellValueByColumnAndRow($i++,  $j, 'Fecha')
    ->setCellValueByColumnAndRow($i++,  $j, 'Beneficiario')
    ->setCellValueByColumnAndRow($i++,  $j, 'Valor');


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

$j++;

# CREA EL CICLO PARA EL LISTADO DE MOVIMIENTOS
if (!$statcon) {
    $select["mov_acu"] = $db->query($sMovAcu);
    while ($rec = $db->fetchAssoc($select['mov_acu'])) {
        $i=$iIni;

        $objPHPExcel->getActiveSheet()
        ->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, (round($rec["ma_haber"],2) != 0) ? $rec["ma_haber"] : "");

        $j++;

        $linea=2;
    }
} else {
    $select["conci_det"] = $db->query($sConci_det);
    while ($rec = $db->fetchAssoc($select['conci_det'])) {
        $i=$iIni;

        $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow($i++,  $j, $rec["cd_num"])
        ->setCellValueByColumnAndRow($i++,  $j, strftime("%d/%m/%Y", strtotime($rec["cd_fec"])))
        ->setCellValueByColumnAndRow($i++,  $j, TRIM(utf8_encode($rec["cd_bene"])))
        ->setCellValueByColumnAndRow($i++,  $j, (round($rec["cd_haber"],2) != 0) ? $rec["cd_haber"] : "");

        $j++;

        $linea=2;
    }
}

$j=$j+3;
$k=$j+4;
// TOTALES DEL MOVIMIENTO
$objPHPExcel->getActiveSheet()->getStyle('C'.$j.':D'.$k)->applyFromArray($bordersThin);
IF (!$statcon) {
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow(2, $j, 'Saldo Segun Estado de Cuenta')
        ->setCellValueByColumnAndRow(3, $j, $salCuenta);
    $j++;    
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow(2, $j, '(-) Cheques en Circulacion')
        ->setCellValueByColumnAndRow(3, $j, $sumCheques);
    $j++;    
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow(2, $j, '(+) Depositos en Circulacion')
        ->setCellValueByColumnAndRow(3, $j, $sumMovi);
    $j++;    
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow(2, $j, '(+) Ajustes')
        ->setCellValueByColumnAndRow(3, $j, $numAjus);
    $j++;
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow(2, $j, 'Saldo segun Contabilidad')
        ->setCellValueByColumnAndRow(3, $j, $salConta);
} else {
    $select["concilia"] = $db->query($sConcilia);
    $fetchAssoc["concilia"] = $db->fetchAssoc($select["concilia"]);
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow(2, $j, 'Saldo Segun Estado de Cuenta')
        ->setCellValueByColumnAndRow(3, $j, $fetchAssoc["concilia"]["con_salban"]);
    $j++;    
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow(2, $j, '(-) Cheques en Circulacion')
        ->setCellValueByColumnAndRow(3, $j, $fetchAssoc["concilia"]["con_cir"]);
    $j++;    
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow(2, $j, '(+) Depositos en Circulacion')
        ->setCellValueByColumnAndRow(3, $j, $fetchAssoc["concilia"]["con_depcir"]);
    $j++;    
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow(2, $j, '(+) Ajustes')
        ->setCellValueByColumnAndRow(3, $j, $fetchAssoc["concilia"]["con_ajus"]);
    $j++;
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow(2, $j, 'Saldo segun Contabilidad')
        ->setCellValueByColumnAndRow(3, $j, $fetchAssoc["concilia"]["con_salem"]);
}
$j++;    

# ESTILO HOJA
$xCenter = array(
    'font' => array(
        'bold' => true,
    ),
	'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

for ($q=1; $q < 5; $q++) { 
	$objPHPExcel->getActiveSheet()->mergeCells('A'.$q.':D'.$q)->getStyle('A'.$q)->applyFromArray($xCenter);
}

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(14);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(60);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(17);

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

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

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

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