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

$empCod=utf8_decode($_SESSION["empCod"]);
$empNom=utf8_decode($_SESSION["empNom"]);
$empNomc=utf8_decode($_SESSION["empNomc"]);


$selTipo=$_GET["selTipo"];
$Tiponom=$_GET["Tiponom"];
$dtFeci=$_GET["dtFecI"];
$dtFecf=$_GET["dtFecF"];
$txtCodd=$_GET["txtCodd"];
$txtDescd=$_GET["txtDescd"];
$selBodega=$_GET["selBodega"];
$Bodeganom=$_GET["Bodeganom"];

# QUERYS
if ($selBodega=='0000') {
    $sDoctose = "SELECT *, TRIM(de.de_obs) AS de_obs, TRIM(td.td_nom) AS td_nom, TRIM(pc.pro_nom) AS pro_nom, TRIM(bod.bod_nom) AS bod_nom, TRIM(bods.bod_nom) AS bod_noms, TRIM(bods.bod_cod) AS bod_cods
       FROM doctose de 
       LEFT JOIN doce_det ded ON ded.ded_emp=de.de_emp and ded.ded_tipo=de.de_tipo and ded.ded_num=de.de_num 
       LEFT JOIN tipodoci td ON  ded.ded_tipo=td.td_cod 
       LEFT JOIN bodegas bod ON  de.de_bodent=bod.bod_cod 
       LEFT JOIN bodegas bods ON  de.de_bodsal=bods.bod_cod 
       LEFT JOIN provcp pc ON  de.de_codp=pc.pro_cod 
       WHERE de_emp='$empCod' AND de_tipo='$selTipo' AND de_fec>='$dtFeci' AND de_fec<='$dtFecf' AND ded_cod LIKE '%$txtCodd%' ORDER BY de_fec,de_tipo,de_num";
} else {
    $sDoctose = "SELECT *, TRIM(de.de_obs) AS de_obs, TRIM(td.td_nom) AS td_nom, TRIM(pc.pro_nom) AS pro_nom, TRIM(bod.bod_nom) AS bod_nom, TRIM(bods.bod_nom) AS bod_noms, TRIM(bods.bod_cod) AS bod_cods
       FROM doctose de 
       LEFT JOIN doce_det ded ON ded.ded_emp=de.de_emp and ded.ded_tipo=de.de_tipo and ded.ded_num=de.de_num 
       LEFT JOIN tipodoci td ON  ded.ded_tipo=td.td_cod 
       LEFT JOIN bodegas bod ON  de.de_bodent=bod.bod_cod 
       LEFT JOIN bodegas bods ON  de.de_bodsal=bods.bod_cod 
       LEFT JOIN provcp pc ON  de.de_codp=pc.pro_cod 
       WHERE de_emp='$empCod' AND (de_bodent='$selBodega' OR de_bodsal='$selBodega')AND de_tipo='$selTipo' AND de_fec>='$dtFeci' AND de_fec<='$dtFecf' AND ded_cod LIKE '%$txtCodd%' ORDER BY de_fec,de_tipo,de_num";
} 

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

/** 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;
$jIni=0;
$objPHPExcel = new PHPExcel();

# CREAR HOJAS
for ($i=0; $i < 1; $i++) { 
	$objPHPExcel->createSheet();
}

$bordersThin = array(
    'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'C5D9F1') ),
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        'wrap' => true,
        ),

    '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
        )
    )
);

$bold17 = array(
    'font' => array(
        'bold' => true,
        'size' => 13,
    ),
);

# HOJAS
$sheet['Traslados']=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=$jIni+1;

$objPHPExcel->setActiveSheetIndex($sheet['Traslados'])
	->setCellValueByColumnAndRow($i,	$j++, utf8_encode($empNom))
    ->setCellValueByColumnAndRow($i, $j++, utf8_encode("REPORTE DE TRASLADOS  DEL ".strftime("%d/%m/%Y", strtotime($dtFeci))." AL ".strftime("%d/%m/%Y", strtotime($dtFecf))))
	->setCellValueByColumnAndRow($i,   $j++, utf8_encode("ARTICULO: ".$txtCodd." - ".$txtDescd))
    ->setCellValueByColumnAndRow($i,   $j++, utf8_encode("BODEGA: ".$Bodeganom))
    ->setCellValueByColumnAndRow($i,   $j++, utf8_encode("TIPO: ".$Tiponom));

    $objPHPExcel->getActiveSheet()->getStyle('A1:H6')->applyFromArray($bold17);

$j++;

$i=$iIni;

$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':M'.$j)->applyFromArray($bordersThin);
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, 'BODEGA ENTRO')
    ->setCellValueByColumnAndRow($i++,  $j, 'BODEGA SALIO')
    ->setCellValueByColumnAndRow($i++,  $j, 'NUMERO')
    ->setCellValueByColumnAndRow($i++,  $j, 'FEC/DOC.')
    ->setCellValueByColumnAndRow($i++,  $j, 'OBSERVACIONES')
    ->setCellValueByColumnAndRow($i++,  $j, 'CODIGO')
    ->setCellValueByColumnAndRow($i++,  $j, 'DESCRIPCION')
    ->setCellValueByColumnAndRow($i++,  $j, 'MEDIDA')
    ->setCellValueByColumnAndRow($i++,  $j, 'CANTIDAD')
    ->setCellValueByColumnAndRow($i++,  $j, 'UNITARIO')
    ->setCellValueByColumnAndRow($i++,  $j, 'TOTAL')
    ->setCellValueByColumnAndRow($i++,  $j, 'BONIFICA')
    ->setCellValueByColumnAndRow($i++,  $j, 'EXENTO');



$j++;

# CREA EL CICLO PARA EL LISTADO DE MOVIMIENTOS

$select["doctose"] = $db->query($sDoctose);
while ($rec = $db->fetchAssoc($select['doctose'])) {
    $i=$iIni;

    $objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, $rec["bod_nom"])
    ->setCellValueByColumnAndRow($i++,  $j, $rec["bod_noms"])
    ->setCellValueByColumnAndRow($i++,  $j, $rec["de_num"])
    ->setCellValueByColumnAndRow($i++,  $j, strftime("%d/%m/%Y", strtotime($rec["de_fec"])))
    ->setCellValueByColumnAndRow($i++,  $j, $rec["de_obs"])
    ->setCellValueByColumnAndRow($i++, $j, trim($rec["ded_cod"]))
    ->setCellValueByColumnAndRow($i++, $j, trim($rec["ded_desc"]))
    ->setCellValueByColumnAndRow($i++, $j, trim($rec["ded_unimed"]))
    ->setCellValueByColumnAndRow($i++, $j, $rec["ded_cant"])
    ->setCellValueByColumnAndRow($i++, $j, $rec["ded_cosu"])
    ->setCellValueByColumnAndRow($i++, $j, $rec["ded_cost"])
    ->setCellValueByColumnAndRow($i++, $j, $rec["ded_boni"])
    ->setCellValueByColumnAndRow($i++, $j, $rec["ded_exesn"]);
    // Esta linea sirve para poner como texto en el caso de numero grandes
    $objPHPExcel->getActiveSheet()->setCellValueExplicit('F'.$j, $rec["ded_cod"], PHPExcel_Cell_DataType::TYPE_STRING);

    $j++;
}

$j++;

/*
// TOTALES DEL MOVIMIENTO
$objPHPExcel->getActiveSheet()->getStyle('D'.$j.':R'.$j)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('D'.$j.':R'.$j)->applyFromArray($borderBottomDouble);

*/
# ESTILO HOJA
$xCenter = array(
    'font' => array(
        'bold' => true,
    ),
	'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

//for ($q=1; $q < 6; $q++) { 
//	$objPHPExcel->getActiveSheet()->mergeCells('A'.$q.':R'.$q)->getStyle('A'.$q)->applyFromArray($xCenter);
//}


$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(14);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(14);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(17);


# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('I6'.':L'.$j)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A6'.':H'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
$objPHPExcel->getActiveSheet()->getStyle('F6'.':F'.$j,PHPExcel_Cell_DataType :: TYPE_STRING);

/*foreach(range('A','G') as $colID) { 
	$objPHPExcel->getActiveSheet()->getColumnDimension($colID)->setAutoSize(true); 
} */

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

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