<?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 = $_SESSION['empCod'];
$empNom = $_SESSION['empNom'];

$selClasi=$_GET["selClasi"];

# QUERYS
if ($selClasi=='000') {
    $sCliencc = "SELECT *, TRIM(cli_cod) AS cli_cod,
                TRIM(cli_nom) AS cli_nom,
                TRIM(cli_nomfac) AS cli_nomfac,
                TRIM(cli_dir) AS cli_dir,
                TRIM(cli_nit) AS cli_nit,
                TRIM(cli_tel) AS cli_tel,
                TRIM(cli_reti) AS cli_reti 
                FROM cliencc LEFT JOIN clasic ON cliencc.cli_clas=clasic.cla_cod WHERE cli_emp='$empCod' ORDER BY cli_emp,cli_clas,cli_nom";
} else {
    $sCliencc = "SELECT *, TRIM(cli_cod) AS cli_cod,
                TRIM(cli_nom) AS cli_nom,
                TRIM(cli_nomfac) AS cli_nomfac,
                TRIM(cli_dir) AS cli_dir,
                TRIM(cli_nit) AS cli_nit,
                TRIM(cli_tel) AS cli_tel,
                TRIM(cli_reti) AS cli_reti 
                FROM cliencc LEFT JOIN clasic ON cliencc.cli_clas=clasic.cla_cod WHERE cli_emp='$empCod' AND cli_clas='$selClasi' ORDER BY cli_emp,cli_clas,cli_nom";
}
# EJECUCION DE QUERYS
$db = new dbExec();
$select["cliencc"] = $db->query($sCliencc);
$db->close();

/** 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['clientes']=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=4;
$objPHPExcel->setActiveSheetIndex($sheet['clientes'])
			->setCellValueByColumnAndRow($i, 1, $empNom)
			->setCellValueByColumnAndRow($i, 2, "Listado de clientes al ".strftime("%d/%m/%Y"))
			->setCellValueByColumnAndRow($i++, $j, 'Grupo')
			->setCellValueByColumnAndRow($i++, $j, 'Codigo')
			->setCellValueByColumnAndRow($i++, $j, 'Nombre')
			->setCellValueByColumnAndRow($i++, $j, 'Nombre Facturar')
			->setCellValueByColumnAndRow($i++, $j, 'Direccion')
			->setCellValueByColumnAndRow($i++, $j, 'Nit')
			->setCellValueByColumnAndRow($i++, $j, 'Telefono')
			->setCellValueByColumnAndRow($i++, $j, 'Ret.S/N')
			->setCellValueByColumnAndRow($i++, $j, 'D/Cred');

# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'bold' => true,
        'size' => 17,
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styFec = array(
	'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styEncabezado = array(
    '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:I1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:I2')->getStyle('A2')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->getStyle('A4:I4')->applyFromArray($styEncabezado);

# VALORES PRIMER HOJA
$i=$iIni;
for ($j=5; $rec = $db->fetchAssoc($select['cliencc']); $j++) {
	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['cla_nom'])))
				->setCellValueByColumnAndRow($i++, $j, $rec['cli_cod'])
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['cli_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode($rec['cli_nomfac']))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode($rec['cli_dir']))
				->setCellValueByColumnAndRow($i++, $j, $rec['cli_nit'])
				->setCellValueByColumnAndRow($i++, $j, $rec['cli_tel'])
				->setCellValueByColumnAndRow($i++, $j, $rec['cli_reti'])
				->setCellValueByColumnAndRow($i++, $j, $rec['cli_dcre']);
	$i=$iIni;
}

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
$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()->getStyle('I5'.':I'.$j)->getNumberFormat()->setFormatCode('#,##0');
$objPHPExcel->getActiveSheet()->getStyle('A5'.':I'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

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

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

?>