<?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'];

$selGrupo=$_GET["selGrupo"];

# QUERYS
if ($selGrupo=='0000') {
    $sArtic = "SELECT *, TRIM(art_cod) AS art_cod,
                TRIM(art_desc) AS art_desc,
                TRIM(art_desd) AS art_desd,
                TRIM(art_marca) AS art_marca,
                TRIM(art_codf) AS art_codf,
                TRIM(art_codbarr) AS art_codbarr
                FROM artic art LEFT JOIN gruposi gru ON art.art_emp=gru.gru_emp AND art.art_gru=gru.gru_cod 
                LEFT JOIN  clasii cla ON art.art_emp=cla.cla_emp AND art.art_clas=cla.cla_cod 
                LEFT JOIN unimed um ON art.art_medi=um.um_cod
                WHERE art_emp='$empCod' AND art_bienser='B' ORDER BY art_emp,art_gru,art_clas,art_desc";
} else {
    $sArtic = "SELECT *, TRIM(art_cod) AS art_cod,
                TRIM(art_desc) AS art_desc,
                TRIM(art_desd) AS art_desd,
                TRIM(art_marca) AS art_marca,
                TRIM(art_codf) AS art_codf,
                TRIM(art_codbarr) AS art_codbarr
                FROM artic art LEFT JOIN gruposi gru ON art.art_emp=gru.gru_emp AND art.art_gru=gru.gru_cod 
                LEFT JOIN  clasii cla ON art.art_emp=cla.cla_emp AND art.art_clas=cla.cla_cod 
                LEFT JOIN unimed um ON art.art_medi=um.um_cod
                WHERE art_emp='$empCod' AND art_gru='$selGrupo' AND art_bienser='B' ORDER BY art_emp,art_gru,art_clas,art_desc";
}
# EJECUCION DE QUERYS
$db = new dbExec();
$select["artic"] = $db->query($sArtic);
$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['articulos']=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['articulos'])
			->setCellValueByColumnAndRow($i, 1, $empNom)
			->setCellValueByColumnAndRow($i, 2, "Listado de Articulos al ".strftime("%d/%m/%Y"))
			->setCellValueByColumnAndRow($i++, $j, 'Grupo')
			->setCellValueByColumnAndRow($i++, $j, 'Clasificacion')
			->setCellValueByColumnAndRow($i++, $j, 'Codigo')
			->setCellValueByColumnAndRow($i++, $j, 'Codigo Fabrica')
			->setCellValueByColumnAndRow($i++, $j, 'Codigo Barras')
			->setCellValueByColumnAndRow($i++, $j, 'Descripcion')
			->setCellValueByColumnAndRow($i++, $j, 'Descripcion Larga')
			->setCellValueByColumnAndRow($i++, $j, 'Uni/Medida')
			->setCellValueByColumnAndRow($i++, $j, 'Minimo')
			->setCellValueByColumnAndRow($i++, $j, 'Maximo')
			->setCellValueByColumnAndRow($i++, $j, 'Marca')
			->setCellValueByColumnAndRow($i++, $j, 'Proveedor')
			->setCellValueByColumnAndRow($i++, $j, 'Costo/Promedio')
			->setCellValueByColumnAndRow($i++, $j, 'Precio 1')
			->setCellValueByColumnAndRow($i++, $j, 'Precio 2')
			->setCellValueByColumnAndRow($i++, $j, 'Precio 3')
			->setCellValueByColumnAndRow($i++, $j, 'Precio 4')
			->setCellValueByColumnAndRow($i++, $j, 'Cuenta Costos')
			->setCellValueByColumnAndRow($i++, $j, 'Cuenta Inventario')
			->setCellValueByColumnAndRow($i++, $j, 'Cuenta Ventas');

# 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','T') as $colID) { 
    $objPHPExcel->getActiveSheet()->getColumnDimension($colID)->setAutoSize(true); 
}

$objPHPExcel->getActiveSheet()->mergeCells('A1:T1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:T2')->getStyle('A2')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->getStyle('A4:T4')->applyFromArray($styEncabezado);

# VALORES PRIMER HOJA
$i=$iIni;
for ($j=5; $rec = $db->fetchAssoc($select['artic']); $j++) {
	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['gru_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['cla_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_cod'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_codf'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_codbarr'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_desc'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_desd'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['um_nom'])))
				->setCellValueByColumnAndRow($i++, $j, $rec['art_mini'])
				->setCellValueByColumnAndRow($i++, $j, $rec['art_maxi'])
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_marca'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_prov'])))
				->setCellValueByColumnAndRow($i++, $j, $rec['art_cosp'])
				->setCellValueByColumnAndRow($i++, $j, $rec['art_pre1'])
				->setCellValueByColumnAndRow($i++, $j, $rec['art_pre2'])
				->setCellValueByColumnAndRow($i++, $j, $rec['art_pre3'])
				->setCellValueByColumnAndRow($i++, $j, $rec['art_pre4'])
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_ctacos'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_ctainv'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_ctaven'])));
	$i=$iIni;
}

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(45);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(15);

$objPHPExcel->getActiveSheet()->getStyle('I5'.':J'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('M5'.':M'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00000');
$objPHPExcel->getActiveSheet()->getStyle('N5'.':Q'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A5'.':H'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
$objPHPExcel->getActiveSheet()->getStyle('K5'.':L'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
$objPHPExcel->getActiveSheet()->getStyle('R5'.':T'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

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

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

?>