<?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');
include_once('../../../php/functions.php');
include_once("../../../php/fpdf/functions.php");

$empCod=utf8_decode($_SESSION["empCod"]);
$empNom=utf8_decode($_SESSION["empNom"]);
$empMoneda=utf8_decode($_SESSION["empMoneda"]);
$empTcam=utf8_decode($_SESSION["pTcam"]);

$selClasi=$_GET["selClasi"];
$selVend=$_GET["selVend"];
$selVendnom=$_GET["selVendnom"];
$dtFec=$_GET["dtFec"];
$crTmone=$_GET["crTmone"];
$crTrepo=$_GET["crTrepo"];
if ($crTmone == 'L') {
    $tipomon=$empMoneda;
} else {
    $tipomon='DOLARES';
}   

# QUERYS
if ($selClasi=='000') {
    $sDoctoscc = "SELECT *, TRIM(dc_clien) AS dc_clien, TRIM(dc_codp) AS dc_codp, TRIM(dc_nit) AS dc_nit, (dc_tot-(dc_abo+dc_ret+dc_reti)) AS dc_saldod, TRIM(cl.cli_clas) AS dc_clas, TRIM(cla.cla_nom) AS cla_nom FROM doctoscc dc 
        LEFT JOIN cliencc cl ON dc.dc_emp=cl.cli_emp and dc.dc_codp=cl.cli_cod 
        LEFT JOIN clasic cla ON cl.cli_clas=cla.cla_cod
        WHERE dc_emp='$empCod' and dc_fec<='$dtFec' AND cli_ven='$selVend' ORDER BY cli_clas,cli_nom";

    $sAnticpc="SELECT * FROM anticpc ant
               LEFT JOIN cliencc cl ON ant.ant_emp=cl.cli_emp and ant.ant_codp=cl.cli_cod 
               LEFT JOIN clasic cla ON cl.cli_clas=cla.cla_cod
               WHERE ant_emp='$empCod' and ant_fec<='$dtFec' and ant_stat='P' AND cli_ven='$selVend' ORDER BY cli_clas,cli_nom";

    function sAbonosc($codp,$tipod,$seried,$numd) { 
        global $empCod, $dtFec;
        return "SELECT * FROM movicc mc WHERE mov_emp='$empCod' and mov_fec>'$dtFec' and mov_codp='$codp' and mov_tipoc='$tipod' and mov_seriec='$seried' and mov_numc='$numd'";
    }    

} else {
    $sDoctoscc = "SELECT *, TRIM(dc_clien) AS dc_clien, TRIM(dc_codp) AS dc_codp, TRIM(dc_nit) AS dc_nit, (dc_tot-(dc_abo+dc_ret+dc_reti)) AS dc_saldod, TRIM(cl.cli_clas) AS dc_clas, TRIM(cla.cla_nom) AS cla_nom FROM doctoscc dc 
        LEFT JOIN cliencc cl ON dc.dc_emp=cl.cli_emp and dc.dc_codp=cl.cli_cod 
        LEFT JOIN clasic cla ON cl.cli_clas=cla.cla_cod
        WHERE dc_emp='$empCod' AND dc_fec<='$dtFec' and cli_clas='$selClasi' AND cli_ven='$selVend' ORDER BY cli_clas,cli_nom";

    $sAnticpc="SELECT * FROM anticpc ant
               LEFT JOIN cliencc cl ON ant.ant_emp=cl.cli_emp and ant.ant_codp=cl.cli_cod 
               LEFT JOIN clasic cla ON cl.cli_clas=cla.cla_cod
               WHERE ant_emp='$empCod' and ant_fec<='$dtFec' and cli_clas='$selClasi' and ant_stat='P' AND cli_ven='$selVend' ORDER BY cli_clas,cli_nom";

    function sAbonosc($codp,$tipod,$seried,$numd) { 
        global $empCod, $dtFec;
        return "SELECT * FROM movicc mc WHERE mov_emp='$empCod' and mov_fec>'$dtFec' and mov_codp='$codp' and mov_tipoc='$tipod' and mov_seriec='$seried' and mov_numc='$numd'";
    }
}
# EJECUCION DE QUERYS
$db = new dbExec();
$select["doctoscc"] = $db->query($sDoctoscc);
$select["anticpc"] = $db->query($sAnticpc);

$func = new functions();

/** 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();
}

# HOJAS
$sheet['salantiguedad']=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['salantiguedad'])
            ->setCellValueByColumnAndRow($i, 1, $empNom)
            ->setCellValueByColumnAndRow($i, 2, "SALDOS DE ANTIGUEDAD POR DOCUMENTO CUENTAS POR COBRAR AL ".strftime("%d/%m/%Y", strtotime($dtFec)))
            ->setCellValueByColumnAndRow($i, 3, "CIFRAS EXPRESADAS EN ".$tipomon)
            ->setCellValueByColumnAndRow($i, 3, "VENDEDOR:  ".$selVendnom)
            ->setCellValueByColumnAndRow($i++, $j, 'SERIE')
            ->setCellValueByColumnAndRow($i++, $j, 'NUMERO')
            ->setCellValueByColumnAndRow($i++, $j, 'FECHA/DOC.')
            ->setCellValueByColumnAndRow($i++, $j, 'FECHA/VENCE')
            ->setCellValueByColumnAndRow($i++, $j, '   AL DIA')
            ->setCellValueByColumnAndRow($i++, $j, '     1 A 30 DIAS')
            ->setCellValueByColumnAndRow($i++, $j, '     31 A 60 DIAS')
            ->setCellValueByColumnAndRow($i++, $j, '     61 A 90 DIAS')
            ->setCellValueByColumnAndRow($i++, $j, '     MAS DE 90')
            ->setCellValueByColumnAndRow($i++, $j, '       TOTAL');

# 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(
    'font' => array(
        'bold' => true,
        'size' => 9,
        //'color' => array('rgb' => '001a57')
    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),
    'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
);

$styLineas = array(
    'font' => array(
        'bold' => false,
        'size' => 9,
    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);
//foreach(range('A','I') as $colID) { 
//    $objPHPExcel->getActiveSheet()->getColumnDimension($colID)->setAutoSize(true); 
//}

$objPHPExcel->getActiveSheet()->mergeCells('A1:J1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:J2')->getStyle('A2')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A3:J3')->getStyle('A3')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->getStyle('A5:J5')->applyFromArray($styEncabezado);

$ti_clasi="XXXZZZ999";
$subcodal_dia=0;
$subcod1_30=0;
$subcod31_60=0;
$subcod61_90=0;
$subcodmas_90=0;
$subcodtot=0;
$subal_dia=0;
$sub1_30=0;
$sub31_60=0;
$sub61_90=0;
$submas_90=0;
$subtot=0;
$total_dia=0;
$tot1_30=0;
$tot31_60=0;
$tot61_90=0;
$totmas_90=0;
$tottot=0;
$t_lini=1;
$codp="";
$ti_codp="XXZZZ999";
$nomp="";
$clas="";
$clasnom="";

$arrayProv = array();
$j=6;
$AL_DIA=0;
$D1_30=0;
$D31_60=0;
$D61_90=0;
$DMAS_90=0;
$inigru=6;
$iniprov=6;
while ($rec = $db->fetchAssoc($select["doctoscc"])) {
    $codp=$rec["dc_codp"];
    $clas=$rec["cli_clas"];
    $tipod=$rec["dc_tipo"];
    $seried=$rec["dc_serie"];
    $numd=$rec["dc_num"];
    $fec=$rec["dc_fec"];
    $diasc=$rec["cli_dcre"];
    $fecp=strtotime('+'.$diasc.' day', strtotime($rec["dc_fec"]));
    $fecp=date('d-m-Y', $fecp);
    $tcam=$rec["dc_tcam"];
    $saldod=$rec["dc_saldod"];
    if ($saldod>0) {
        if ($crTmone == 'L' && $tcam>1) {
            $saldod=round($saldod*$tcam,2);
        }
        if ($crTmone == 'E' && $tcam == 1) {
            $saldod=round($saldod/$empTcam,2);
        }
    }

    $sumabo=0;
    $select["movicc"] = $db->query(sAbonosc($codp,$tipod,$seried,$numd));
    //$fetchAssoc["movic"] = $db->sFetchAssoc(sAbonos($codp));
    while ($recabo = $db->fetchAssoc($select["movicc"])) {
        $vabo=$recabo["mov_abo"];
        $tcamabo=$recabo["mov_tcam"];
        if ($vabo>0) {
            if ($crTmone == 'L' && $tcamabo>1) {
                $vabo=round($vabo*$tcamabo,2);
            }
            if ($crTmone == 'E' && $tcamabo == 1) {
                $vabo=round($vabo/$empTcam,2);
            }
            $sumabo += $vabo;
        }
    }
    
    $saldod+=$sumabo;
    if ($saldod == 0) {
       continue;
    }
    
    if ($t_lini == 1) {
        $codp=$rec["dc_codp"];
        $nomp=$rec["cli_nom"];
        $clas=$rec["cli_clas"];
        $clasnom=$rec["cla_nom"];
        $iniprov=6;
        $inigru=6;
        //$t_lini=2;
    }
    if ($ti_codp!=$rec["dc_codp"]) {
        if ($t_lini > 1) {
            $subcodtot=($subcodal_dia+$subcod1_30+$subcod31_60+$subcod61_90+$subcodmas_90);
            $i=$iIni;
           $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE CLIENTE")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$iniprov.':E'.($j-1).')') 
                ->setCellValueByColumnAndRow($i++, $j, '=SUM(F'.$iniprov.':F'.($j-1).')') 
                ->setCellValueByColumnAndRow($i++, $j, '=SUM(G'.$iniprov.':G'.($j-1).')') 
                ->setCellValueByColumnAndRow($i++, $j, '=SUM(H'.$iniprov.':H'.($j-1).')') 
                ->setCellValueByColumnAndRow($i++, $j, '=SUM(I'.$iniprov.':I'.($j-1).')') 
                ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$j.':I'.$j.')'); 
            $objPHPExcel->getActiveSheet()->getStyle('E'.$j.':J'.$j)->applyFromArray($styEncabezado);
            $j+=1;
        }             
        $subcodal_dia=0;
        $subcod1_30=0;
        $subcod31_60=0;
        $subcod61_90=0;
        $subcodmas_90=0;
        $codp=$rec["dc_codp"];
        $ti_codp=$rec["dc_codp"];
        $nomp=$rec["cli_nom"];
        if (TRIM($ti_clasi)!=TRIM($rec["cli_clas"])) {
            if ($t_lini > 1) {
                $subtot=($subal_dia+$sub1_30+$sub31_60+$sub61_90+$submas_90);
                $i=$iIni;
                $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE GRUPO")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",E'.$inigru.':E'.($j-1).')') 
                ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",F'.$inigru.':F'.($j-1).')') 
                ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",G'.$inigru.':G'.($j-1).')') 
                ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",H'.$inigru.':H'.($j-1).')') 
                ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",I'.$inigru.':I'.($j-1).')') 
                ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$j.':I'.$j.')'); 
                $objPHPExcel->getActiveSheet()->getStyle('E'.$j.':J'.$j)->applyFromArray($styEncabezado);
                $j+=2;
                $subal_dia=0;
                $sub1_30=0;
                $sub31_60=0;
                $sub61_90=0;
                $submas_90=0;
                $subtot=0;
            }
            $clas=$rec["cli_clas"];
            $clasnom=$rec["cla_nom"];
            $ti_clasi=$rec["cli_clas"];
            $i=$iIni;
            $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, "GRUPO: ".$clasnom); 
            $inigru=$j;
            $j+=1;
        }

        $i=$iIni;
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow($i++, $j, $codp."-".utf8_encode($nomp));
        $j+=1;
        $t_lini=2;
        $iniprov=$j;
    } 

    // Para saber cuantos dias
    $diff=$func->dateDiff($dtFec, $fecp);
    $dias=($diff->invert == 1) ? '-'.$diff->days : $diff->days;
    $AL_DIA=0;
    $D1_30=0;
    $D31_60=0;
    $D61_90=0;
    $DMAS_90=0;
    if ($dias<1) {
      $AL_DIA=$saldod;
    }
    if ($dias>0 && $dias<31) {
      $D1_30=$saldod;
    }
    if ($dias>30 && $dias<61) {
      $D31_60=$saldod;
    }
    if ($dias>60 && $dias<91) {
      $D61_90=$saldod;
    }
    if ($dias>90) {
      $DMAS_90=$saldod;
    }

    $subcodal_dia += $AL_DIA;
    $subcod1_30 += $D1_30;
    $subcod31_60 += $D31_60;
    $subcod61_90 += $D61_90;
    $subcodmas_90 += $DMAS_90;

    $subal_dia += $AL_DIA;
    $sub1_30 += $D1_30;
    $sub31_60 += $D31_60;
    $sub61_90 += $D61_90;
    $submas_90 += $DMAS_90;
    $TOTALL = ($AL_DIA+$D1_30+$D31_60+$D61_90+$DMAS_90);

    $total_dia += $AL_DIA;
    $tot1_30 += $D1_30;
    $tot31_60 += $D31_60;
    $tot61_90 += $D61_90;
    $totmas_90 += $DMAS_90;
    $i=$iIni;
    $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, $rec["dc_serie"])
                ->setCellValueByColumnAndRow($i++, $j, trim($rec["dc_num"]))
                ->setCellValueByColumnAndRow($i++, $j, strftime("%d/%m/%Y", strtotime($fec)))
                ->setCellValueByColumnAndRow($i++, $j, strftime("%d/%m/%Y", strtotime($fecp)))
                ->setCellValueByColumnAndRow($i++, $j, $AL_DIA)
                ->setCellValueByColumnAndRow($i++, $j, $D1_30)
                ->setCellValueByColumnAndRow($i++, $j, $D31_60)
                ->setCellValueByColumnAndRow($i++, $j, $D61_90)
                ->setCellValueByColumnAndRow($i++, $j, $DMAS_90)
                ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$j.':I'.$j.')');
    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':J'.$j)->applyFromArray($styLineas);
    $j+=1;
}

$i=$iIni;
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE CLIENTE")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$iniprov.':E'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(F'.$iniprov.':F'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(G'.$iniprov.':G'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(H'.$iniprov.':H'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(I'.$iniprov.':I'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$j.':I'.$j.')'); 
$objPHPExcel->getActiveSheet()->getStyle('E'.$j.':J'.$j)->applyFromArray($styEncabezado);
$j+=1;

$i=$iIni;
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE GRUPO")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",E'.$inigru.':E'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",F'.$inigru.':F'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",G'.$inigru.':G'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",H'.$inigru.':H'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",I'.$inigru.':I'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$j.':I'.$j.')'); 
$objPHPExcel->getActiveSheet()->getStyle('E'.$j.':J'.$j)->applyFromArray($styEncabezado); 


$j+=1;
$sipaso="N";
// Solo si se necesita incluir anticipos
if ($crTrepo == 'A') {
    $select["anticpc"] = $db->query($sAnticpc);
    $ti_clasi="XXXZZZ999";
    $subcodal_dia=0;
    $subcod1_30=0;
    $subcod31_60=0;
    $subcod61_90=0;
    $subcodmas_90=0;
    $subcodtot=0;
    $subal_dia=0;
    $sub1_30=0;
    $sub31_60=0;
    $sub61_90=0;
    $submas_90=0;
    $subtot=0;
    $t_lini=1;
    $codp="";
    $ti_codp="XXZZZ999";
    $nomp="";
    $clas="";
    $clasnom="";
    while ($recanti = $db->fetchAssoc($select["anticpc"])) {
        $codp=$recanti["ant_codp"];
        $clas="ZZZ999";
        $tipod="ANTICIPO";
        $seried="ANTICIPO";
        $numd=$recanti["ant_num"];
        $fec=$recanti["ant_fec"];
        $fecp=$recanti["ant_fec"];
        $tcam=$recanti["ant_tcam"];
        $saldod=$recanti["ant_tot"];
        if ($saldod>0) {
            if ($crTmone == 'L' && $tcam>1) {
                $saldod=round($saldod*$tcam,2);
            }
            if ($crTmone == 'E' && $tcam == 1) {
                $saldod=round($saldod/$empTcam,2);
            }
        }
        if ($saldod == 0) {
           continue;
        }
        if ($t_lini == 1) {
            $codp=$recanti["ant_codp"];
            $nomp=$rec["cli_nom"];
            $clas="ZZZ999";
            $clasnom="ANTICIPOS";
            //$t_lini=2;
        }
        if ($ti_codp!=$recanti["ant_codp"]) {
            if ($t_lini > 1) {
                $i=$iIni;
                $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($i++, $j, "")
                    ->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE CLIENTE")
                    ->setCellValueByColumnAndRow($i++, $j, "")
                    ->setCellValueByColumnAndRow($i++, $j, "")
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$iniprov.':E'.($j-1).')') 
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(F'.$iniprov.':F'.($j-1).')') 
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(G'.$iniprov.':G'.($j-1).')') 
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(H'.$iniprov.':H'.($j-1).')') 
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(I'.$iniprov.':I'.($j-1).')') 
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$j.':I'.$j.')'); 
                $objPHPExcel->getActiveSheet()->getStyle('E'.$j.':J'.$j)->applyFromArray($styEncabezado);
                $j+=1;
            }             
            $subcodal_dia=0;
            $subcod1_30=0;
            $subcod31_60=0;
            $subcod61_90=0;
            $subcodmas_90=0;
            $codp=$recanti["ant_codp"];
            $ti_codp=$recanti["ant_codp"];
            $nomp=$recanti["cli_nom"];
            if ($ti_clasi!=$rec["cli_clas"]) {
                if ($t_lini > 1) {
                    $subtot=($subal_dia+$sub1_30+$sub31_60+$sub61_90+$submas_90);
                    $i=$iIni;
                    $objPHPExcel->getActiveSheet()
                        ->setCellValueByColumnAndRow($i++, $j, "")
                        ->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE GRUPO")
                        ->setCellValueByColumnAndRow($i++, $j, "")
                        ->setCellValueByColumnAndRow($i++, $j, "")
                        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",E'.$inigru.':E'.($j-1).')') 
                        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",F'.$inigru.':F'.($j-1).')') 
                        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",G'.$inigru.':G'.($j-1).')') 
                        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",H'.$inigru.':H'.($j-1).')') 
                        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",I'.$inigru.':I'.($j-1).')') 
                        ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$j.':I'.$j.')'); 
                    $objPHPExcel->getActiveSheet()->getStyle('E'.$j.':J'.$j)->applyFromArray($styEncabezado); 
                    $j+=2;
                    $subal_dia=0;
                    $sub1_30=0;
                    $sub31_60=0;
                    $sub61_90=0;
                    $submas_90=0;
                    $subtot=0;
               }
               $clas="ZZZ999";
               $clasnom="ANTICIPOS";
               $i=$iIni;
               $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($i++, $j, "GRUPO: ".$clasnom); 
               $inigru=$j;
               $j+=1;
               $ti_clasi=$rec["cli_clas"];
               //$pdf->ln(.4);
            }
            $i=$iIni;
            $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, $codp."-".utf8_encode($nomp));
            $j+=1;
            $t_lini=2;
            $iniprov=$j;
        } 
        $vanti=$recanti["ant_tot"];
        $fecanti=$recanti["ant_fec"];
        $tcamanti=$recanti["ant_tcam"];
        if ($vanti>0) {
            if ($crTmone == 'L' && $tcamanti>1) {
                $vanti=round($vanti*$tcamanti,2);
            }
            if ($crTmone == 'E' && $tcamanti == 1) {
                $vanti=round($vanti/$empTcam,2);
            }
            $diff=$func->dateDiff($dtFecf, $fecanti);
            $dias=($diff->invert == 1) ? '-'.$diff->days : $diff->days;
            $AL_DIA=0;
            $D1_30=0;
            $D31_60=0;
            $D61_90=0;
            $DMAS_90=0;
        /*    if ($dias<1) {
              $total_dia=$total_dia-$vanti;
              $subal_dia=$subal_dia-$vanti;
              $subcodal_dia=$subcodal_dia-$vanti;
              $AL_DIA=$vanti*-1;
            } */
            if ($dias<31) {
              $tot1_30=$tot1_30-$vanti;
              $sub1_30=$sub1_30-$vanti;
              $subcod1_30=$subcod1_30-$vanti;
              $D1_30=$vanti*-1;
            }
            if ($dias>30 && $dias<61) {
              $tot31_60=$tot31_60-$vanti;
              $sub31_60=$sub31_60-$vanti;
              $subcod31_60=$subcod31_60-$vanti;
              $D31_60=$vanti*-1;
            }
            if ($dias>60 && $dias<91) {
              $tot61_90=$tot61_90-$vanti;
              $sub61_90=$sub61_90-$vanti;
              $subcod61_90=$subcod61_90-$vanti;
              $D61_90=$vanti*-1;
            }
            if ($dias>90) {
              $totmas_90=$totmas_90-$vanti;
              $submas_90=$submas_90-$vanti;
              $subcodmas_90=$subcodmas_90-$vanti;
              $DMAS_90=$vanti*-1;
            }
        }
        $TOTALL = ($AL_DIA+$D1_30+$D31_60+$D61_90+$DMAS_90);

        $i=$iIni;
        $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($i++, $j, "ANTICIPO")
                    ->setCellValueByColumnAndRow($i++, $j, trim($recanti["ant_num"]))
                    ->setCellValueByColumnAndRow($i++, $j, strftime("%d/%m/%Y", strtotime($recanti["ant_fec"])))
                    ->setCellValueByColumnAndRow($i++, $j, $rec["cli_dcre"])
                    ->setCellValueByColumnAndRow($i++, $j, $dias)
                    ->setCellValueByColumnAndRow($i++, $j, $D1_30)
                    ->setCellValueByColumnAndRow($i++, $j, $D31_60)
                    ->setCellValueByColumnAndRow($i++, $j, $D61_90)
                    ->setCellValueByColumnAndRow($i++, $j, $DMAS_90)
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(F'.$j.':I'.$j.')');
        $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':J'.$j)->applyFromArray($styLineas);
        $i=$iIni;
        $j+=1;
        $sipaso="S";
    }
}
if ($sipaso=='S') {
    $i=$iIni;
    $objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow($i++, $j, "")
        ->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE CLIENTE")
        ->setCellValueByColumnAndRow($i++, $j, "")
        ->setCellValueByColumnAndRow($i++, $j, "")
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$iniprov.':E'.($j-1).')') 
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(F'.$iniprov.':F'.($j-1).')') 
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(G'.$iniprov.':G'.($j-1).')') 
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(H'.$iniprov.':H'.($j-1).')') 
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(I'.$iniprov.':I'.($j-1).')') 
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$j.':I'.$j.')'); 
    $objPHPExcel->getActiveSheet()->getStyle('E'.$j.':J'.$j)->applyFromArray($styEncabezado);
    $j+=1;

    $i=$iIni;
    $objPHPExcel->getActiveSheet()
    	->setCellValueByColumnAndRow($i++, $j, "")
    	->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE GRUPO")
        ->setCellValueByColumnAndRow($i++, $j, "")
        ->setCellValueByColumnAndRow($i++, $j, "")
        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",E'.$inigru.':E'.($j-1).')') 
        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",F'.$inigru.':F'.($j-1).')') 
        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",G'.$inigru.':G'.($j-1).')') 
        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",H'.$inigru.':H'.($j-1).')') 
        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B'.$inigru.':B'.($j-1).',"    SUBTOTAL DE ESTE CLIENTE",I'.$inigru.':I'.($j-1).')') 
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$j.':I'.$j.')'); 
    $objPHPExcel->getActiveSheet()->getStyle('E'.$j.':J'.$j)->applyFromArray($styEncabezado); 
}
$i=$iIni;
$j+=1;
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++, $j, "")
	->setCellValueByColumnAndRow($i++, $j, "    TOTAL GENERAL")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B6:B'.($j-1).',"    SUBTOTAL DE ESTE GRUPO",E6:E'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B6:B'.($j-1).',"    SUBTOTAL DE ESTE GRUPO",F6:F'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B6:B'.($j-1).',"    SUBTOTAL DE ESTE GRUPO",G6:G'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B6:B'.($j-1).',"    SUBTOTAL DE ESTE GRUPO",H6:H'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B6:B'.($j-1).',"    SUBTOTAL DE ESTE GRUPO",I6:I'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$j.':I'.$j.')'); 
$objPHPExcel->getActiveSheet()->getStyle('E'.$j.':J'.$j)->applyFromArray($styEncabezado);


$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);

$objPHPExcel->getActiveSheet()->getStyle('E6'.':J'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A6'.':B'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

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

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