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

$ti_clasi="XXX";
$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="";
$nomp="";
$clas="";
$clasnom="";

$arrayCli = array();

while ($rec = $db->fetchAssoc($select["doctoscc"])) {
    if ($t_lini == 1) {
        $codp=$rec["dc_codp"];
        $ti_codp=$rec["dc_codp"];
        $nomp=$rec["cli_nom"];
        $clas=$rec["cli_clas"];
        $clasnom=$rec["cla_nom"];
        $t_lini=2;
    }   
    if ($ti_codp!=$rec["dc_codp"]) {
        array_push($arrayCli, array('codp'=>$codp, 'nomp'=>$nomp, 'clas'=>$clas, 'clasnom'=>$clasnom, 'dal_dia'=>$subal_dia, 'd1_30'=>$sub1_30, 'd31_60'=>$sub31_60, 'd61_90'=>$sub61_90, 'dmas_90'=>$submas_90)); 
        $subal_dia=0;
        $sub1_30=0;
        $sub31_60=0;
        $sub61_90=0;
        $submas_90=0;
        $codp=$rec["dc_codp"];
        $ti_codp=$rec["dc_codp"];
        $nomp=$rec["dc_clien"];
        $clas=$rec["cli_clas"];
        $clasnom=$rec["cla_nom"];
    }   
    $tipod=$rec["dc_tipo"];
    $seried=$rec["dc_serie"];
    $numd=$rec["dc_num"];
    $fecp=$rec["dc_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;
    // 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;
    }
    $subal_dia += $AL_DIA;
    $sub1_30 += $D1_30;
    $sub31_60 += $D31_60;
    $sub61_90 += $D61_90;
    $submas_90 += $DMAS_90;
}

array_push($arrayCli, array('codp'=>$codp, 'nomp'=>$nomp, 'clas'=>$clas, 'clasnom'=>$clasnom, 'dal_dia'=>$subal_dia, 'd1_30'=>$sub1_30, 'd31_60'=>$sub31_60, 'd61_90'=>$sub61_90, 'dmas_90'=>$submas_90)); 

// Para definir si incluye anticipos
if ($crTrepo == 'A') {
    $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="";
    $nomp="";
    $clas="";
    $clasnom="";

    while ($reca = $db->fetchAssoc($select["anticpc"])) {
        if ($t_lini == 1) {
            $codp=$reca["ant_codp"];
            $ti_codp=$reca["ant_codp"];
            $nomp=$reca["cli_nom"];
            $clas="ZZZ999";
            $clasnom="ANTICIPOS";
            $t_lini=2;
        }   
        if ($ti_codp!=$reca["ant_codp"]) {
            array_push($arrayCli, array('codp'=>$codp, 'nomp'=>$nomp, 'clas'=>$clas, 'clasnom'=>$clasnom, 'dal_dia'=>$subal_dia, 'd1_30'=>$sub1_30, 'd31_60'=>$sub31_60, 'd61_90'=>$sub61_90, 'dmas_90'=>$submas_90)); 
            $subal_dia=0;
            $sub1_30=0;
            $sub31_60=0;
            $sub61_90=0;
            $submas_90=0;
            $codp=$reca["ant_codp"];
            $ti_codp=$reca["ant_codp"];
            $nomp=$reca["cli_nom"];
            $clas="ZZZ999";
            $clasnom="ANTICIPOS";
        }   
        $tipod="ANT";
        $seried="ANTICIPO";
        $numd=$reca["ant_num"];
        $fecp=$reca["ant_fec"];
        $tcam=$reca["ant_tcam"];
        $saldod=$reca["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);
            }
        }

        // 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;
        }
        $subal_dia -= $AL_DIA;
        $sub1_30 -= $D1_30;
        $sub31_60 -= $D31_60;
        $sub61_90 -= $D61_90;
        $submas_90 -= $DMAS_90;
    }
    array_push($arrayCli, array('codp'=>$codp, 'nomp'=>$nomp, 'clas'=>$clas, 'clasnom'=>$clasnom, 'dal_dia'=>$subal_dia, 'd1_30'=>$sub1_30, 'd31_60'=>$sub31_60, 'd61_90'=>$sub61_90, 'dmas_90'=>$submas_90)); 
}
//

/** 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, "REPORTE DE SALDOS POR CLIENTE AL ".strftime("%d/%m/%Y", strtotime($dtFec)))
			->setCellValueByColumnAndRow($i, 3, "CIFRAS EXPRESADAS EN ".$tipomon)
			->setCellValueByColumnAndRow($i++, $j, 'CODIGO')
			->setCellValueByColumnAndRow($i++, $j, 'NOMBRE DEL CLIENTE')
			->setCellValueByColumnAndRow($i++, $j, '    SALDO');

# 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:C1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:C2')->getStyle('A2')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A3:C3')->getStyle('A3')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->getStyle('A5:C5')->applyFromArray($styEncabezado);

$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;
$ti_clasi="XXX";
$inigru=1;
$initot=6;
# VALORES PRIMER HOJA
$i=$iIni;
$j=6;
$inigru=6;
foreach ($arrayCli as $recp) {
    if ($ti_clasi!=$recp["clas"]) {
        if ($t_lini > 1) {
        	$i=$iIni;
			$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, "")
				->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE GRUPO")
		        ->setCellValueByColumnAndRow($i++, $j, '=SUM(C'.$inigru.':C'.($j-1).')');
		    $objPHPExcel->getActiveSheet()->getStyle('C'.$j.':C'.$j)->applyFromArray($styEncabezado);

            $subal_dia=0;
            $sub1_30=0;
            $sub31_60=0;
            $sub61_90=0;
            $submas_90=0;
            $subtot=0;
            $j+=2;
        }
       	$i=$iIni;
		$objPHPExcel->getActiveSheet()
			->setCellValueByColumnAndRow($i++, $j, "GRUPO: ".$recp["clasnom"]);

       $ti_clasi=$recp["clas"];
       $j+=1;
       $t_lini=2;
       $inigru=$j;
    }
    $codp=$recp["codp"];
    $nomp=$recp["nomp"];

    $subal_dia += $recp["dal_dia"];
    $sub1_30 += $recp["d1_30"];
    $sub31_60 += $recp["d31_60"];
    $sub61_90 += $recp["d61_90"];
    $submas_90 += $recp["dmas_90"];
    $TOTALL = ($recp["dal_dia"]+$recp["d1_30"]+$recp["d31_60"]+$recp["d61_90"]+$recp["dmas_90"]);
    $subtot += $TOTALL;
    $total_dia += $recp["dal_dia"];
    $tot1_30 += $recp["d1_30"];
    $tot31_60 += $recp["d31_60"];
    $tot61_90 += $recp["d61_90"];
    $totmas_90 += $recp["dmas_90"];
    $tottot += $TOTALL;
    if ($TOTALL==0) {
       continue;
    }
   	$i=$iIni;
	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, $codp)
				->setCellValueByColumnAndRow($i++, $j, $nomp)
			    ->setCellValueByColumnAndRow($i++, $j, $TOTALL);
    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':C'.$j)->applyFromArray($styLineas);
	$i=$iIni;
	$j+=1;
}
$i=$iIni;
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++, $j, "")
	->setCellValueByColumnAndRow($i++, $j, "    SUBTOTAL DE ESTE GRUPO")
    ->setCellValueByColumnAndRow($i++, $j, '=SUM(C'.$inigru.':C'.($j-1).')');
$objPHPExcel->getActiveSheet()->getStyle('C'.$j.':C'.$j)->applyFromArray($styEncabezado);



$i=$iIni;
$j+=1;
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++, $j, "")
	->setCellValueByColumnAndRow($i++, $j, "    TOTAL GENERAL")
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B6:B'.($j-1).',"    SUBTOTAL DE ESTE GRUPO",C6:C'.($j-1).')');
$objPHPExcel->getActiveSheet()->getStyle('C'.$j.':C'.$j)->applyFromArray($styEncabezado);


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

$objPHPExcel->getActiveSheet()->getStyle('C6'.':C'.$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="Salancli.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;
?>