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

$numNum=$_GET["numNum"];
//$selBan=$_GET["selBan"];
//$Banctab=$_GET["Banctab"];
//$Banctac=$_GET["Banctac"];
//$dtFec=$_GET["dtFec"];
$dtDel=$_GET["dtDel"];
$dtAl=$_GET["dtAl"];
$fecano=date("Y", strtotime($dtAl));
$fecmes=date("n", strtotime($dtAl));
$fecdia=date("d", strtotime($dtAl));
$nenvio=$_GET["numNenvio"];    /// Aqui hay que colocar el numero de envio que van a hacer

# QUERYS
$sAnti = "SELECT ant.*, TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape,
            TRIM(mae.mae_nomch) AS mae_nomch, TRIM(mae.mae_ctab) AS mae_ctab, TRIM(tpu.tpu_nom) AS tpu_nom
            FROM antipla ant
            LEFT JOIN maestro mae ON ant.ant_emp = mae.mae_emp  AND ant.ant_cod = mae.mae_cod 
            LEFT JOIN tpuesto tpu ON mae.mae_tpue = tpu.tpu_cod 
            WHERE ant_emp='$empCod' AND ant_numpla='$numNum' AND mae_fpago<3";

function sMeses($mes) {
    return "SELECT mes_nom FROM meses WHERE mes_cod=$mes";
}

# EJECUCION DE QUERYS
$db = new dbExec();
$select["antipla"] = $db->query($sAnti);
$select["meses"] = $db->query(sMeses($fecmes));
$fetchAssoc["meses"] = $db->fetchAssoc($select["meses"]);
if ($db->numRows($select["meses"])>0) {
    $mesnom=$fetchAssoc["meses"]["mes_nom"];
}
$db->close();

$concepto="PRIMERA QUINCENA ".TRIM($mesnom)." ".$fecano;

/** 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['maestro']=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=1;
$objPHPExcel->setActiveSheetIndex($sheet['maestro'])
            ->setCellValueByColumnAndRow($i++, $j, "Registro")
            ->setCellValueByColumnAndRow($i++, $j, "Referencia")
            ->setCellValueByColumnAndRow($i++, $j, "No.Cuenta")
            ->setCellValueByColumnAndRow($i++, $j, "Nombre")
            ->setCellValueByColumnAndRow($i++, $j, "Salario");

# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'bold' => true,
        'size' => 13,
    ),
    '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' => 12,
    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    ),
	'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styTotales = array(
    'font' => array(
        'bold' => true,
        'size' => 12,
    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);


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

//$objPHPExcel->getActiveSheet()->getStyle('A1:E1')->applyFromArray($styEncabezado);

# VALORES PRIMER HOJA
$i=$iIni;
$suma=0;
$item=1;
for ($j=2; $rec = $db->fetchAssoc($select['antipla']); $j++) {
    $lcant=strlen(TRIM($rec["mae_ctab"]));
    $t_ctab=TRIM($rec["mae_ctab"]);
/*    
    $t_guion=1;
    $t_agen="";
    $t_corr="";
    $t_digi="";
    for ($k=0; $k<=$lcant; $k++) {
      $t_car=SUBSTR($t_ctab,$k,1);
      IF ($t_guion==1 && $t_car!="-") {
        $t_agen=$t_agen.TRIM($t_car);
      }
      IF ($t_guion==1 && $t_car=="-") {
        //$k++;
        $t_guion=2;
        continue;
      }
      IF ($t_guion==2 && $t_car!="-") {
        $t_corr=$t_corr.TRIM($t_car);
      }
      IF ($t_guion==2 && $t_car=="-") {
        //$k++;
        $t_guion=3;
        continue;
      }
      IF ($t_guion==3 && $t_car!="-") {
        $t_digi=$t_digi.TRIM($t_car);
      }
    }
*/    
/*    
    $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, "T")
                ->setCellValueByColumnAndRow($i++, $j, "TP88")
                ->setCellValueByColumnAndRow($i++, $j, trim($nenvio))
                ->setCellValueByColumnAndRow($i++, $j, trim($t_ctab))
                ->setCellValueByColumnAndRow($i++, $j, ($j-1))
                ->setCellValueByColumnAndRow($i++, $j, $fecano)
                ->setCellValueByColumnAndRow($i++, $j, $fecmes)
                ->setCellValueByColumnAndRow($i++, $j, $fecdia)
                ->setCellValueByColumnAndRow($i++, $j, round($rec['ant_liqrec']*100,0))
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($concepto)))
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_nomch'])))
                ->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($t_ctab)));
*/         
    $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, $item)
                ->setCellValueByColumnAndRow($i++, $j, trim($t_ctab))
                ->setCellValueByColumnAndRow($i++, $j, trim($t_ctab))
                ->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['mae_nomch'])))
                ->setCellValueByColumnAndRow($i++, $j, round($rec['ant_liqrec'],2));

    $suma=$suma+$rec['ant_liqrec'];
	$i=$iIni;
    $item=$item+1;
}
$i=$iIni;
/*
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(8, 1, round($suma*100,0))
    ->setCellValueByColumnAndRow(9, 1, ($j-2));
*/
    
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(70);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(12);


//$objPHPExcel->getActiveSheet()->getStyle('A2'.':D'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
$objPHPExcel->getActiveSheet()->getStyle('E1'.':E'.$j)->getNumberFormat()->setFormatCode('###0.00');

# ESTABLECER TITULOS
$objPHPExcel->setActiveSheetIndex($sheet['maestro'])->setTitle('Envio Anticipo');

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

?>