<?php
require_once 'api/PHPExcel/Classes/PHPExcel.php';
require_once "connect.php";
require_once 'inc/usuario.php';
require_once "inc/report_analitico.php";


/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('America/Sao_Paulo');

if (PHP_SAPI == 'cli')
	die('This example should only be run from a Web Browser');

$report = new VendaReportToExcel();

$ReportAnalitico = new ReportAnalitico();

if(isset($_GET['dt_inicio'])){
	$report->dt_inicio = base64_decode($_GET['dt_inicio']);
	$ReportAnalitico->dt_inicio = base64_decode($_GET['dt_inicio']);
}

if(isset($_GET['dt_final'])){
	$report->dt_final  = base64_decode($_GET['dt_final']);
	$ReportAnalitico->dt_final  = base64_decode($_GET['dt_final']);
}

if(isset($_GET['dt_inicio'])){
	$report->id_tipo_venda   = base64_decode($_GET['id_tipo_venda']);
	$ReportAnalitico->id_tipo= base64_decode($_GET['id_tipo_venda']);
}

if(isset($_GET['dt_inicio'])){
	$report->id_forma_pagamento	= base64_decode($_GET['id_forma_pagamento']);
	$ReportAnalitico->id_forma = base64_decode($_GET['id_forma_pagamento']);
}


  $ReportAnalitico->getFormaPagamento();
  $ReportAnalitico->getTipoVenda();

$report->ExportarParaExcel();

exit;

/* A classe Resgata o SQL do BD e Exporta para o Excel */
class VendaReportToExcel{

	private $titulo = 'Relatório Analítico de Vendas';
	/*
	public $dt_inicio = '01/01/1900';
	public $dt_final  = '01/01/1900';
	public $id_tipo_venda = '';
	public $id_forma_pagamento	= '';

	private $ds_forma_pagamento= ''; // Forma de pagamento;
	private $ds_tipo_venda     = ''; // Tipo de Venda;
	*/


	/* Constantes para inserir uma cor da Fonte */
	const COLOR_BLACK      = 'FF000000';
	const COLOR_WHITE      = 'FFFFFFFF';
	const COLOR_RED        = 'FFFF0000';
	const COLOR_DARKRED    = 'FF800000';
	const COLOR_BLUE       = 'FF0000FF';
	const COLOR_DARKBLUE   = 'FF000080';
	const COLOR_GREEN      = 'FF00FF00';
	const COLOR_DARKGREEN  = 'FF008000';
	const COLOR_YELLOW     = 'FFFFFF00';
	const COLOR_DARKYELLOW = 'FF808000';


  function __construct() {
    $usuario = getLoggedUser();
    $this->id_usuario = $usuario['id'];
		$this->id_unidade = $usuario['unidade'];
   }

	 /* Transformar a Fonte Negrito e Tamanho*/
	 function definirFont($p_size, $p_text, $p_bold = true, $p_ita = true, $p_color = ''){
		 $objRichText = new PHPExcel_RichText();
		 $objPayable = $objRichText->createTextRun("$p_text");
		 $objPayable->getFont()->setBold($p_bold);
		 $objPayable->getFont()->setItalic($p_ita);
		 $objPayable->getFont()->setSize($p_size);

		 if($p_color!=''){
			$objPayable->getFont()->setColor( new PHPExcel_Style_Color($p_color) );
		 }

		 return $objRichText;
	 }

	 function capturarLogo($obj_include){
		 global $ReportAnalitico;

		 // Consulta no BD o path do Logo do Cliente
		 $p_linhas = 0;
		 $consulta = "select ds_logo from erpc_unidades where id=$this->id_unidade";
		 $resultado= $ReportAnalitico->getSQL($consulta);

		 if(count($resultado)>0){
			 $ds_logo = $resultado[0]['ds_logo'];
			 $objDrawing = new PHPExcel_Worksheet_Drawing();
  		 $objDrawing->setName('Logo');
  		 $objDrawing->setDescription('Logo');
  		 $objDrawing->setPath("$ds_logo");
  		 $objDrawing->setHeight(60);
  		 $objDrawing->setWorksheet($obj_include->getActiveSheet());
			 $p_linhas = 5;
		 }

		 return $p_linhas;
	 }

		function ExportarParaExcel(){
			global $ReportAnalitico;

			/**
			 * 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##
			 */


			// Create new PHPExcel object
			$objPHPExcel = new PHPExcel();

			// Set document properties
			$objPHPExcel->getProperties()->setCreator("ERPC - CODE TECNOLOGIA")
										 ->setLastModifiedBy("ERPC - CODE TECNOLOGIA")
										 ->setTitle("$this->titulo", true)
										 /*->setSubject("Office 2007 XLSX Relatório de Vendas")
										 ->setDescription("Relatório de Vendas - Office 2007 XLSX, generated using PHP classes.")
										 // ->setKeywords("office 2007 openxml php")*/
										 ->setCategory("Resultado direto para arquivo");


			// Add some data
			/*$objPHPExcel->getDefaultStyle()->getFont()->setName('Calibri')
			                                          ->setSize(11);*/


      // $p_size, $p_text, $p_bold = true, $p_ita = true, $p_color = ''
			$line_first_report = $this->capturarLogo($objPHPExcel);

			// tamanho, texto, Negrito, Italico, Cor da Fonte
			$report_name     = $this->definirFont(16, 'Relatório Analítico de Vendas', true, true, PHPExcel_Style_Color::COLOR_RED);
			$report_intervalo= $this->definirFont(12, "Intervalo De: $this->dt_inicio Até: $this->dt_final", true, false);
			$report_forma    = $this->definirFont(12, "Forma de Pagamento:$ReportAnalitico->ds_forma", true, false);
			$report_tipo     = $this->definirFont(12, "Tipos:$ReportAnalitico->ds_tipo", true, false);


			$objPHPExcel->setActiveSheetIndex(0)
									->setCellValue('A5', $report_name)
									->setCellValue('A6', $report_intervalo)
									->setCellValue('A7', $report_forma)
									->setCellValue('A8', $report_tipo);

		$line_title_table = $line_first_report + 4;
		$objPHPExcel->setActiveSheetIndex(0)
									->setCellValue("A$line_title_table", 'Data')
									->setCellValue("B$line_title_table", 'Pedido')
									->setCellValue("C$line_title_table", 'Tipo')
									->setCellValue("D$line_title_table", 'Forma')
									->setCellValue("E$line_title_table", 'Qtde')
									->setCellValue("F$line_title_table", 'Unitário')
									->setCellValue("G$line_title_table", 'Desconto')
									->setCellValue("H$line_title_table", 'Total');

			$objPHPExcel->getDefaultStyle()->getFont()->setName('Calibri')
			                                          ->setSize(11);


									/* Faz o Loop Preenchendo a Tabela */
									$nr_linha = $line_title_table+1;
									$sum_vl_total=0;

									$resultado = $ReportAnalitico->getCapturarVendas();

									if (Count($resultado)>0) {
										foreach ($resultado as $key => $value) {
											// Miscellaneous glyphs, UTF-8
											$dh_liberacao= $value['dt_emissao'];
											$tipo 		= $value['tipo'];
											$ds_forma = $value['ds_forma'];
											$pedido 					  = $value['pedido'];
											$nr_quantidade      = $value['nr_quantidade'];
											$vl_unitario        = $value['vl_unitario'];
											$vl_desconto_produto= $value['vl_desconto_produto'];
											$vl_total           = $value['vl_total'];


											$dt_conv = date('d/m/Y', strtotime($dh_liberacao));

											$objPHPExcel->setActiveSheetIndex(0)
																	->setCellValue("A$nr_linha", "$dt_conv")
																	->setCellValue("B$nr_linha", "$pedido")
																	->setCellValue("D$nr_linha", "$tipo")
																	->setCellValue("C$nr_linha", "$ds_forma")
																	->setCellValue("E$nr_linha", "$nr_quantidade")
																	->setCellValue("F$nr_linha", "$vl_unitario")
																	->setCellValue("G$nr_linha", "$vl_desconto_produto")
																	->setCellValue("H$nr_linha", $vl_total);
																	/*->setCellValue("D$nr_linha", 'Number')
																	->setCellValue("D$nr_linha", 'Float')*/

										  $nr_linha ++;
											$sum_vl_total += $vl_total;
										}
										$nr_linha ++;
										$sum_vl_total = number_format($sum_vl_total, 2, ',', '.');

										$report_rodape= $this->definirFont(16, "Total de Vendas", true, true, PHPExcel_Style_Color::COLOR_RED);
										$report_sum   = $this->definirFont(16, "$sum_vl_total"  , true, true, PHPExcel_Style_Color::COLOR_RED);


										$objPHPExcel->setActiveSheetIndex(0)
																->setCellValue("A$nr_linha", $report_rodape)
																->setCellValue("H$nr_linha", $report_sum  );

									}

			// Rename worksheet
			$objPHPExcel->getActiveSheet()->setTitle($this->titulo);
			// $objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddHeader("&L&G&C&HERPC CODE TECNOLOGIA");
			// $objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $objPHPExcel->getProperties()->getTitle() . '&RPágina &P of &N');
			$ds_page_footer = "ERP - Code v1.0 - Relatório de Vendas - Code Tecnologia www.codetecnologia.com.br";

			$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $ds_page_footer . '&RPágina &P of &N');

			$objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT);
			$objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);

			$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
			$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
			$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);

			// Set active sheet index to the first sheet, so Excel opens this as the first sheet
			$objPHPExcel->setActiveSheetIndex(0);


			// Redirect output to a client’s web browser (Excel5)
			header('Content-Type: application/vnd.ms-excel');
			header('Content-Disposition: attachment;filename="erpcCode01.xls"');
			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, 'Excel5');
			$objWriter->save('php://output');
		}
}
