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

$dtFec=date("Y-m-d");
$txtCodp=$_GET["txtCodp"];
$txtSerie=$_GET["txtSerie"];
$numNum=$_GET["numNum"];
$crTmone=$_GET["crTmone"];
if ($crTmone == 'L') {
    $tipomon=$empMoneda;
} else {
    $tipomon='DOLARES';
}   

# QUERYS
$sDoctoscc = "SELECT *, TRIM(dc_clien) AS dc_clien, TRIM(dc_codp) AS dc_codp, TRIM(dc_nit) AS dc_nit, 
    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_serie='$txtSerie' and dc_num='$numNum' and dc_codp='$txtCodp'";

function sAbonosc($codp,$tipod,$seried,$numd) { 
    global $empCod;
    return "SELECT * FROM movicc mc LEFT JOIN tipoaboc ta ON mc.mov_tipo=ta.ta_cod WHERE mov_emp='$empCod'  and mov_codp='$codp' and mov_tipoc='$tipod' and mov_seriec='$seried' and mov_numc='$numd'";
}    
# EJECUCION DE QUERYS
$db = new dbExec();
$lineHeight=0.35;
$select["doctoscc"] = $db->query($sDoctoscc);

$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, "ESTADO DE CUENTA DE UN DOCUMENTO ESPECIFICO AL ".strftime("%d/%m/%Y"))
            ->setCellValueByColumnAndRow($i, 3, "CIFRAS EXPRESADAS EN ".$tipomon);

# 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";
$totcargos=0;
$totret=0;
$totreti=0;
$totabonos=0;
$t_lini=1;
$codp="";
$ti_codp="XXZZZ999";
$nomp="";
$clas="";
$clasnom="";
$saldoact=0;

$j=5;
$AL_DIA=0;
$D1_30=0;
$D31_60=0;
$D61_90=0;
$DMAS_90=0;
$inigru=5;
$iniprov=5;
while ($rec = $db->fetchAssoc($select["doctoscc"])) {
    if ($t_lini == 1) {
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow(0, $j, "CLIENTE:  ".$rec["dc_codp"]."-".utf8_encode($rec["cli_nom"]));
        $j+=1;
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow(0, $j, "DIRECCION:  ".utf8_encode($rec["cli_dir"]));
        $j+=1;
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow(0, $j, "NIT:  ".$rec["cli_nit"]."           TELEFONO:  ".$rec["cli_tel"]);
        $j+=1;
        $i=$iIni;
        $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($i++, $j, 'SERIE')
                    ->setCellValueByColumnAndRow($i++, $j, 'NUMERO')
                    ->setCellValueByColumnAndRow($i++, $j, 'FECHA/DOC.')
                    ->setCellValueByColumnAndRow($i++, $j, 'FECHA/VENCE')
                    ->setCellValueByColumnAndRow($i++, $j, 'D/VENCIDO')
                    ->setCellValueByColumnAndRow($i++, $j, '     CARGOS')
                    ->setCellValueByColumnAndRow($i++, $j, '     ABONOS')
                    ->setCellValueByColumnAndRow($i++, $j, '     RET/ISR')
                    ->setCellValueByColumnAndRow($i++, $j, '     RET/IVA')
                    ->setCellValueByColumnAndRow($i++, $j, '     SALDO');
        $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':J'.$j)->applyFromArray($styEncabezado); 
        $j+=1;
        $codp=$rec["dc_codp"];
        $nomp=$rec["cli_nom"];
        $clas=$rec["cli_clas"];
        $clasnom=$rec["cla_nom"];
        $iniprov=6;
        $inigru=6;
        //$t_lini=2;
    }
    $t_lini=2;

    $codp=$rec["dc_codp"];
    $clas=$rec["cli_clas"];
    $tipod=$rec["dc_tipo"];
    $seried=$rec["dc_serie"];
    $numd=$rec["dc_num"];
    $fec=$rec["dc_fec"];
    $fecp=$rec["dc_fecp"];
    $tcam=$rec["dc_tcam"];
    $tot=$rec["dc_tot"];
    $ret=$rec["dc_ret"];
    $reti=$rec["dc_reti"];
    $abo=$rec["dc_abo"];
    if ($tot>0) {
        if ($crTmone == 'L' && $tcam>1) {
            $tot=round($tot*$tcam,2);
            $abo=round($abo*$tcam,2);
            $ret=round($ret*$tcam,2);
            $reti=round($reti*$tcam,2);
        }
        if ($crTmone == 'E' && $tcam == 1) {
            $tot=round($tot/$empTcam,2);
            $abo=round($abo/$empTcam,2);
            $ret=round($ret/$empTcam,2);
            $reti=round($reti/$empTcam,2);
        }
    } else {
        continue;
    }
    // Para saber cuantos dias
    $diff=$func->dateDiff($dtFec, $fecp);
    $dias=($diff->invert == 1) ? '-'.$diff->days : $diff->days;

    $saldoact = ($saldoact+$tot)-($ret+$reti);

    $totcargos += $tot;
    $totabonos += $abo;
    $totret += $ret;
    $totreti += $reti;
    $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, $dias)
                ->setCellValueByColumnAndRow($i++, $j, $tot)
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, $ret)
                ->setCellValueByColumnAndRow($i++, $j, $reti)
                ->setCellValueByColumnAndRow($i++, $j, $saldoact);
    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':J'.$j)->applyFromArray($styLineas); 
    $j+=1;

    $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;
        }
        $saldoact = ($saldoact-$vabo);
        $i=$iIni;
        $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($i++, $j, trim($recabo["ta_nom"]))
                    ->setCellValueByColumnAndRow($i++, $j, trim($recabo["mov_num"]))
                    ->setCellValueByColumnAndRow($i++, $j, strftime("%d/%m/%Y", strtotime($recabo["mov_fec"])))
                    ->setCellValueByColumnAndRow($i++, $j, "")
                    ->setCellValueByColumnAndRow($i++, $j, "")
                    ->setCellValueByColumnAndRow($i++, $j, "")
                    ->setCellValueByColumnAndRow($i++, $j, $vabo)
                    ->setCellValueByColumnAndRow($i++, $j, "")
                    ->setCellValueByColumnAndRow($i++, $j, "")
                    ->setCellValueByColumnAndRow($i++, $j, $saldoact);
        $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':J'.$j)->applyFromArray($styLineas); 
        $j+=1;
    } 
}
$i=$iIni;
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "    TOTALES DEL DOCUMENTO")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "") 
    ->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, '=(J'.($j-1).')'); 
$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('F6'.':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="EstadoUndoc.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;
?>