<?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/functions.php');
include_once("../../../php/fpdf/functions.php");
include_once('../../../php/maxExecTime.php');

$empCod = $_SESSION['empCod'];
$empNom = $_SESSION['empNom'];

$selDepto=$_GET["selDepto"];
$selsubDepto=$_GET["selSubDepto"];
$DeptoNom=$_GET["DeptoNom"];

# QUERYS
if ($selDepto=='0000') {
    if ($selsubDepto=='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_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    WHERE art_emp='$empCod' AND art_bienser='B' ORDER BY art_emp,art_dep,art_subdep,art_cod";
    } 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_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN  subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    WHERE art_emp='$empCod' AND art_subdep='$selsubDepto' AND art_bienser='B' ORDER BY art_emp,art_dep,art_subdep,art_cod";
    }
} else {
    if ($selsubDepto=='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_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN  subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    WHERE art_emp='$empCod' AND art_dep='$selDepto' AND art_bienser='B' ORDER BY art_emp,art_dep,art_subdep,art_cod";
    } 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_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN  subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    WHERE art_emp='$empCod' AND art_dep='$selDepto' AND art_subdep='$selsubDepto' AND art_bienser='B' ORDER BY art_emp,art_dep,art_subdep,art_cod";
    }
}

# EJECUCION DE QUERYS
$db = new dbExec();

$func = new functions();

$select["artic"] = $db->query($sArtic);

/** 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=6;
$objPHPExcel->setActiveSheetIndex($sheet['articulos'])
			->setCellValueByColumnAndRow($i, 1, utf8_encode($empNom))
			->setCellValueByColumnAndRow($i, 2, "Listado de Precios")
            ->setCellValueByColumnAndRow($i, 3, "Familia:  ".$DeptoNom)
			->setCellValueByColumnAndRow($i++, $j, 'Codigo')
			->setCellValueByColumnAndRow($i++, $j, 'Descripcion')
			->setCellValueByColumnAndRow($i++, $j, '  Precio');
# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'bold' => true,
        'size' => 17,
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styFam = array(
    'font' => array(
        'bold' => true,
        'size' => 12,
    )
);

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

$styEncabezado = array(
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);

$bordersThin = array(
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);

$borderBottomDouble = array(
    'borders' => array(
        'bottom' => array(
            'style' => PHPExcel_Style_Border::BORDER_DOUBLE
        )
    )
);

$borderTopThin = array(
    'borders' => array(
        'top' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);


foreach(range('A','T') 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($styFec);
$objPHPExcel->getActiveSheet()->mergeCells('A3:C3')->getStyle('A3')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->mergeCells('A4:C4')->getStyle('A4')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->getStyle('A6:H6')->applyFromArray($styEncabezado);
$ti_Depto="XXXX";
$ti_sDepto="XXXX";
# VALORES PRIMER HOJA
$i=$iIni;
for ($j=7; $rec = $db->fetchAssoc($select['artic']); $j++) {
    if ($ti_Depto.$ti_sDepto!=$rec["art_dep"].$rec["art_subdep"]) {
        $i=$iIni;
        $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec["dep_nom"]).", ".rtrim($rec["sdep_nom"])));
        $objPHPExcel->getActiveSheet()->mergeCells('A'.$j.':C'.$j)->getStyle('A'.$j)->applyFromArray($styFam);
        $j+=1;
       $ti_Depto=$rec["art_dep"];
       $ti_sDepto=$rec["art_subdep"];
    }

    $codd=$rec["art_cod"];
    $pre1=$rec["art_pre1"];
    $i=$iIni;
	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_cod'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_desc'])))
                ->setCellValueByColumnAndRow($i++, $j, $pre1);
	$i=$iIni;
}

// TOTALES DEL MOVIMIENTO
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':C'.$j)->applyFromArray($borderBottomDouble);

/*$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(4, $j, 'Total')
    ->setCellValueByColumnAndRow(5, $j, '=SUM(F7:F'.($j-1).')');   */

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(65);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);

$objPHPExcel->getActiveSheet()->getStyle('C5'.':C'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A5'.':B'.$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);

$db->close();

// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="LPrecios.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;

?>