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

$empCod=utf8_decode($_SESSION["empCod"]);
$empNom=utf8_decode($_SESSION["empNom"]);
$empMoneda=utf8_decode($_SESSION["empMoneda"]);
$empTcam=utf8_decode($_SESSION["pTcam"]);

$dtDel=$_GET["dtDel"];
$dtAl=$_GET["dtAl"];
$txtCod=$_GET['txtCod'];
$txtDesc=$_GET['txtDesc'];

# QUERYS
if ($txtCod=="") {
    $sResuProd = "SELECT npp.*, SUM(npp_cant) AS npp_uniprod, SUM(npp_tot) AS npp_valprod, TRIM(mae.mae_bodega) AS mae_bodega, TRIM(fes.fes_cod) AS fes_cod,
                  TRIM(fes.fes_prenda) AS fes_prenda, TRIM(fesd.fesd_desc) AS fesd_desc, TRIM(bp.bp_nom) AS bp_nom 
                  FROM nomper_prod npp
                  LEFT JOIN maestro mae ON npp.npp_emp=mae.mae_emp AND npp.npp_codemple=mae.mae_cod
                  LEFT JOIN festilos fes ON npp.npp_emp=fes.fes_emp AND npp.npp_cod=fes.fes_cod 
                  LEFT JOIN festilos_d fesd ON npp.npp_emp=fesd.fesd_emp AND npp.npp_cod=fesd.fesd_cod AND npp.npp_linea=fesd.fesd_linea 
                  LEFT JOIN bodegapro bp ON bp.bp_cod=mae.mae_bodega  
                  WHERE npp_emp='$empCod' AND npp_fec>='$dtDel' AND npp_fec<='$dtAl' AND npp_cant>0 GROUP BY npp_emp,npp_cod,mae.mae_bodega,npp_linea ORDER BY npp_emp,npp_cod,mae.mae_bodega,npp_linea";
} else {
    $sResuProd = "SELECT npp.*, SUM(npp_cant) AS npp_uniprod, SUM(npp_tot) AS npp_valprod, TRIM(mae.mae_bodega) AS mae_bodega, TRIM(fes.fes_cod) AS fes_cod,
                  TRIM(fes.fes_prenda) AS fes_prenda, TRIM(fesd.fesd_desc) AS fesd_desc, TRIM(bp.bp_nom) AS bp_nom 
                  FROM nomper_prod npp
                  LEFT JOIN maestro mae ON npp.npp_emp=mae.mae_emp AND npp.npp_codemple=mae.mae_cod
                  LEFT JOIN festilos fes ON npp.npp_emp=fes.fes_emp AND npp.npp_cod=fes.fes_cod 
                  LEFT JOIN festilos_d fesd ON npp.npp_emp=fesd.fesd_emp AND npp.npp_cod=fesd.fesd_cod AND npp.npp_linea=fesd.fesd_linea 
                  LEFT JOIN bodegapro bp ON bp.bp_cod=mae.mae_bodega  
                  WHERE npp_emp='$empCod' AND npp_fec>='$dtDel' AND npp_fec<='$dtAl' AND npp_cant>0 AND npp_cod='$txtCod' GROUP BY npp_emp,npp_cod,mae.mae_bodega,npp_linea ORDER BY npp_emp,npp_cod,mae.mae_bodega,npp_linea";
}       

# EJECUCION DE QUERYS
$db = new dbExec();
$select["nomper_prod"] = $db->query($sResuProd);

$func = new functions();

/** 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['planilla']=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=7;
$objPHPExcel->setActiveSheetIndex($sheet['planilla'])
            ->setCellValueByColumnAndRow($i, 2, TRIM($empNom))
            ->setCellValueByColumnAndRow($i, 3, "RESUMEN DE PRODUCCION DEL : ".strftime("%d/%m/%Y", strtotime($dtDel))." al ".strftime("%d/%m/%Y", strtotime($dtAl)))
            ->setCellValueByColumnAndRow($i, 4, "ESTILO(S) : ".$txtDesc)
            ->setCellValueByColumnAndRow($i++, $j, 'LINEA DE PRODUCCION')
            ->setCellValueByColumnAndRow($i++, $j, 'CANTIDAD')
            ->setCellValueByColumnAndRow($i++, $j, 'VALOR');

# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'name' => 'Arial',
        'bold' => true,
        'size' => 12,
        //'color' => array('rgb' => 'FFFFFF')
        'color' => array('rgb' => '16365C')

    )
/*    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),      */
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '354D73') ),
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
/*    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
//        'wrap' => true,
        'merge' => true,
        )  */
);
$styEmp1 = array(
    'font' => array(
        'name' => 'Arial',
        'bold' => true,
        'size' => 12,
        //'color' => array('rgb' => 'FFFFFF')
        'color' => array('rgb' => '16365C')

    )
/*    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),    */
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '354D73') ),
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
/*    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,  
    //    'wrap' => true,
        )    */
);

$styEst = array(
    'font' => array(
        'name' => 'Arial',
        'bold' => true,
        'size' => 12,
        //'color' => array('rgb' => 'FFFFFF')
        'color' => array('rgb' => '8E0808')

    )
/*    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),      */
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '354D73') ),
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
/*    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
//        'wrap' => true,
        'merge' => true,
        )  */
);


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

$styEncabezado = array(
    'font' => array(
        'name' => 'Arial',
        'bold' => true,
        'size' => 12,
        'name' => 'Arial',
        //'color' => array('rgb' => 'FFFFFF')
        'color' => array('rgb' => '16365C')

    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),
    'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'E6B8B7') ),
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        'wrap' => true,
        )    
);

$styTotales = array(
    'font' => array(
        'bold' => true,
        'size' => 12,
        'color' => array('rgb' => 'FFFFFF')
        //'color' => array('rgb' => '001a57')

    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),
    'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '354D73') )
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
);

$styTotales1 = array(
    'font' => array(
        'bold' => true,
        'size' => 12,
        'color' => array('rgb' => 'FFFFFF')
        //'color' => array('rgb' => '001a57')

    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),
    'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '8E0808') )
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
);

$styTotales2 = array(
    'font' => array(
        'bold' => true,
        'size' => 12,
        'color' => array('rgb' => 'FFFFFF')
        //'color' => array('rgb' => '001a57')

    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),
    'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '1A7B03') )
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
);

$styLineas = array(
    'font' => array(
        'name' => 'Arial',
        'bold' => false,
        '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('A2:C2')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->getStyle('A3:C3')->applyFromArray($styEmp1);
$objPHPExcel->getActiveSheet()->getStyle('A4:C4')->applyFromArray($styEmp1);
$objPHPExcel->getActiveSheet()->getStyle('A7:C7')->applyFromArray($styEncabezado);

$estilop="ZZZ999";
$bodegap=99999;
$t_lini=1;
$j=8;
$inibod=8;
$iniestilo=8;
$nocorr=1;

while ($rec = $db->fetchAssoc($select["nomper_prod"])) {
    if ($rec["npp_cod"].$rec["mae_bodega"] != $estilop.$bodegap) {
        if ($t_lini>1) {
           $i=$iIni;
           $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($i++, $j, "    TOTAL ESTA BODEGA")
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(B'.$inibod.':B'.($j-1).')')
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(C'.$inibod.':C'.($j-1).')');
                $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':C'.$j)->applyFromArray($styTotales);
            $j+=1;
            $inibod=$j;
            if ($rec["npp_cod"] != $estilop) {
                $j+=1;
                $i=$iIni;
                $objPHPExcel->getActiveSheet()
                        ->setCellValueByColumnAndRow($i++, $j, "    TOTAL ESTE ESTILO")
                        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(A'.$iniestilo.':A'.($j-1).',"    TOTAL ESTA BODEGA",B'.$iniestilo.':B'.($j-1).')') 
                        ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(A'.$iniestilo.':A'.($j-1).',"    TOTAL ESTA BODEGA",C'.$iniestilo.':C'.($j-1).')');
                    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':C'.$j)->applyFromArray($styTotales1);
                $j+=1;
                $iniestilo=$j;
                $inibod=$j;
            }
        }
        if ($rec["npp_cod"] != $estilop) {
            $j+=1;
            $i=$iIni;
            $objPHPExcel->getActiveSheet()
                        ->setCellValueByColumnAndRow($i++, $j, $rec["npp_cod"]." - ".$rec["fes_prenda"]);
            $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':C'.$j)->applyFromArray($styEst);
            $estilop=$rec["npp_cod"];
        }
        $j+=1;
        $i=$iIni;
        $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($i++, $j, $rec["bp_nom"]);
        $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':C'.$j)->applyFromArray($styEmp);
        $bodegap=$rec["mae_bodega"];
        $j+=1;
        $t_lini=2;
    }  
    $i=$iIni;
    $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, $rec["fesd_desc"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["npp_uniprod"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["npp_valprod"]);
    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':C'.$j)->applyFromArray($styLineas); 
    $j+=1;
}
$i=$iIni;
$objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow($i++, $j, "    TOTAL ESTA BODEGA")
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(B'.$inibod.':B'.($j-1).')')
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(C'.$inibod.':C'.($j-1).')');
    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':C'.$j)->applyFromArray($styTotales);
$j+=1;
$inibod=$j;

$i=$iIni;
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++, $j, "    TOTAL ESTE ESTILO")
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(A'.$iniestilo.':A'.($j-1).',"    TOTAL ESTA BODEGA",B'.$iniestilo.':B'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(A'.$iniestilo.':A'.($j-1).',"    TOTAL ESTA BODEGA",C'.$iniestilo.':C'.($j-1).')');
    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':C'.$j)->applyFromArray($styTotales1);
$j+=1;
$iniestilo=$j;

$i=$iIni;
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++, $j, "      TOTAL GENERAL")
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(A8:B'.($j-1).',"    TOTAL ESTA BODEGA",B8:B'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(A8:C'.($j-1).',"    TOTAL ESTA BODEGA",C8:C'.($j-1).')');
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':C'.$j)->applyFromArray($styTotales2); 

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(60);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
$objPHPExcel->getActiveSheet()->getStyle('B8'.':C'.$j)->getNumberFormat()->setFormatCode('###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A8'.':A'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

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

# 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="Resumen Produccion.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;
?>