<?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"];
$selBodega=$_GET["selBodega"];
$BodegaNom=$_GET["BodegaNom"];

# 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
                    LEFT JOIN unimed um ON art.art_medi=um.um_cod
                    WHERE art_emp='$empCod' AND art_bienser='B' ORDER BY art_emp,art_dep,art_subdep,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_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
                    LEFT JOIN unimed um ON art.art_medi=um.um_cod
                    WHERE art_emp='$empCod' AND art_subdep='$selsubDepto' AND art_bienser='B' ORDER BY art_emp,art_dep,art_subdep,art_desc";
    }
} 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
                    LEFT JOIN unimed um ON art.art_medi=um.um_cod
                    WHERE art_emp='$empCod' AND art_dep='$selDepto' AND art_bienser='B' ORDER BY art_emp,art_dep,art_subdep,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_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
                    LEFT JOIN unimed um ON art.art_medi=um.um_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_desc";
    }
}
function sExiart($codd) { 
    global $empCod, $usuNom, $selBodega;
    return "SELECT * FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$selBodega'";
}

# 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=4;
$objPHPExcel->setActiveSheetIndex($sheet['articulos'])
			->setCellValueByColumnAndRow($i, 1, utf8_encode($empNom))
            ->setCellValueByColumnAndRow($i, 2, "Listado de Articulos que sobrepasaron el maximo ".strftime("%d/%m/%Y"))
            ->setCellValueByColumnAndRow($i, 3, "Bodega:  ".$BodegaNom)
			->setCellValueByColumnAndRow($i++, $j, 'Familia')
			->setCellValueByColumnAndRow($i++, $j, 'SubFamilia')
			->setCellValueByColumnAndRow($i++, $j, 'Codigo')
			->setCellValueByColumnAndRow($i++, $j, 'Descripcion')
			->setCellValueByColumnAndRow($i++, $j, 'Medida')
			->setCellValueByColumnAndRow($i++, $j, '  Sistema')
			->setCellValueByColumnAndRow($i++, $j, '  Maximo')
            ->setCellValueByColumnAndRow($i++, $j, 'Diferencia');
# 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:H1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:H2')->getStyle('A2')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->mergeCells('A3:H3')->getStyle('A3')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->getStyle('A4:H4')->applyFromArray($styEncabezado);

# VALORES PRIMER HOJA
$i=$iIni;
for ($j=5; $rec = $db->fetchAssoc($select['artic']); $j++) {
    if ($rec["art_maxi"] == 0) {
       $j=$j-1;
       continue;
    }

    $codd=$rec["art_cod"];
    $maximo=$rec["art_maxi"];
   
    $select["exiart"] = $db->query(sExiart($codd));
    $fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
    $Exist = $fetchAssoc["exiart"]["ea_exist"];

    if ($Exist<=$maximo) {
       $j=$j-1;
       continue;
    }    
    $Diferencia=($Exist-$maximo);
	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['dep_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['sdep_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_cod'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_desc'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['um_nom'])))
				->setCellValueByColumnAndRow($i++, $j, $Exist)
				->setCellValueByColumnAndRow($i++, $j, $maximo)
                ->setCellValueByColumnAndRow($i++, $j, $Diferencia);
	$i=$iIni;
}

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(45);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);

$objPHPExcel->getActiveSheet()->getStyle('F5'.':H'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A5'.':E'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
//$objPHPExcel->getActiveSheet()->getStyle('G5'.':G'.$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="Maximo.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;

?>