<?php
class ControllerCommonHeader extends Controller {
	protected function index() {

		$this->setUserCookie();

		$this->data['title'] = $this->document->getTitle();

		$this->document->addStylePrioridade('catalog/view/theme/OPC070156/public/css/mainheader.css');
    $this->document->addScriptPrioridade('catalog/view/theme/OPC070156/public/js/mainheader.js');

		$this->loadScripts();

		 // start body_class code
   $this->data['text_information'] = $this->language->get('text_information');
   $this->load->model('catalog/information');
   $this->data['informations'] = array();

   if (isset($this->request->get['route'])) {
     $route = (string)$this->request->get['route'];
   } else {
	 	 $route = 'common/home';
   }

		foreach ($this->model_catalog_information->getInformations() as $result) {
			if ($result['bottom']) {
				$this->data['informations'][] = array(
					'title' => $result['title'],
					'href'  => $this->url->link('information/information', 'information_id=' . $result['information_id'])
				);
			}
    	}

    $current_path = $this->request->get;
    if (empty($current_path) || $current_path['route'] == 'common/home') {
      $body_class = 'home';
    }
    else {
      $body_class = explode('/', str_replace('product/', '', $current_path['route']));
      unset($current_path['route']);
      if (isset($current_path['_route_'])) {
        $body_class = array_merge($body_class, explode('/', str_replace('-', '_', $current_path['_route_'])));
        unset($current_path['_route_']);
      }
      foreach ($current_path as $key => $value) {
        $body_class[] = $key . "_" . $value;
      }
      $body_class = 'page_' . implode(" page_", array_unique($body_class));
    }
    $body_class .= ' lang_' . $this->language->get('code');
    $this->data['body_class'] = $body_class;

    // end body_class code

		if (isset($this->request->server['HTTPS']) && (($this->request->server['HTTPS'] == 'on') || ($this->request->server['HTTPS'] == '1'))) {
			$server = $this->config->get('config_ssl');
		} else {
			$server = $this->config->get('config_url');
		}

        if (isset($this->session->data['error']) && !empty($this->session->data['error'])) {
            $this->data['error'] = $this->session->data['error'];

            unset($this->session->data['error']);
        } else {
            $this->data['error'] = '';
        }

		$this->data['base'] = $server;
		$this->data['description'] = $this->document->getDescription();
		$this->data['keywords'] = $this->document->getKeywords();
		$this->data['links'] = $this->document->getLinks();
		$this->data['styles'] = $this->document->getStyles();
		$this->data['scripts'] = $this->document->getScripts();
		$this->data['lang'] = $this->language->get('code');
		$this->data['direction'] = $this->language->get('direction');
		$this->data['google_analytics'] = html_entity_decode($this->config->get('config_google_analytics'), ENT_QUOTES, 'UTF-8');
		$this->data['name'] = $this->config->get('config_name');

		if ($this->config->get('config_icon') && file_exists(DIR_IMAGE . $this->config->get('config_icon'))) {
			$this->data['icon'] = $server . 'image/' . $this->config->get('config_icon');
		} else {
			$this->data['icon'] = '';
		}

		if ($this->config->get('config_logo') && file_exists(DIR_IMAGE . $this->config->get('config_logo'))) {
			$this->data['logo'] = $server . 'image/' . $this->config->get('config_logo');
		} else {
			$this->data['logo'] = '';
		}

		$this->language->load('common/header');

		$this->data['text_home'] = $this->language->get('text_home');
		$this->data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), (isset($this->session->data['wishlist']) ? count($this->session->data['wishlist']) : 0));
		$this->data['text_shopping_cart'] = $this->language->get('text_shopping_cart');
    	$this->data['text_search'] = $this->language->get('text_search');
		$this->data['text_welcome'] = sprintf($this->language->get('text_welcome'), /* comentario porque agora so tem um parametro %s no header pelo fato de chamar o fancybox
																					$this->url->link('account/login', '', 'SSL'),*/ $this->url->link('account/register', '', 'SSL'));
		$this->data['text_logged'] = sprintf($this->language->get('text_logged'), $this->url->link('account/account', '', 'SSL'), $this->customer->getFirstName(), $this->url->link('account/logout', '', 'SSL'));
		$this->data['text_account'] = $this->language->get('text_account');
    $this->data['text_checkout'] = $this->language->get('text_checkout');

		$this->data['home'] = $this->url->link('common/home','','NONSSL','false');
		$this->data['wishlist'] = $this->url->link('account/wishlist', '', 'SSL');
		$this->data['logged'] = $this->customer->isLogged();
		$this->data['account'] = $this->url->link('account/account', '', 'SSL');
		$this->data['shopping_cart'] = $this->url->link('checkout/cart');
		$this->data['checkout'] = $this->url->link('checkout/checkout', '', 'SSL');

		$this->data['fields_register_brazil_tipo_de_pessoa'] = $this->config->get('fields_register_brazil_tipo_de_pessoa');

		// Daniel's robot detector
		$status = true;

		if (isset($this->request->server['HTTP_USER_AGENT'])) {
			$robots = explode("\n", trim($this->config->get('config_robots')));

			foreach ($robots as $robot) {
				if ($robot && strpos($this->request->server['HTTP_USER_AGENT'], trim($robot)) !== false) {
					$status = false;

					break;
				}
			}
		}

		// A dirty hack to try to set a cookie for the multi-store feature
		$this->load->model('setting/store');

		$this->data['stores'] = array();

		if ($this->config->get('config_shared') && $status) {
			$this->data['stores'][] = $server . 'catalog/view/javascript/crossdomain.php?session_id=' . $this->session->getId();

			$stores = $this->model_setting_store->getStores();

			foreach ($stores as $store) {
				$this->data['stores'][] = $store['url'] . 'catalog/view/javascript/crossdomain.php?session_id=' . $this->session->getId();
			}
		}

		// Search
		if (isset($this->request->get['search'])) {
			$this->data['search'] = $this->request->get['search'];
		} else {
			$this->data['search'] = '';
		}

		// Menu
		$this->load->model('catalog/category');
		$this->load->model('catalog/product');


		if (($route == "common/home") || ($route == "product/category") || ($route == "product/product") || ($route == "product/search") || ($route == "product/latest") || ($route == "product/featured") ){

			$this->data['categories'] = array();

			$categories_1 = $this->model_catalog_category->getCategories(0);

			foreach ($categories_1 as $category_1) {
				if ($category_1['top']) {


						$level_2_data = array();

					$categories_2 = $this->model_catalog_category->getCategories($category_1['category_id']);

					foreach ($categories_2 as $category_2) {
					$level_3_data = array();

					$categories_3 = $this->model_catalog_category->getCategories($category_2['category_id']);

				foreach ($categories_3 as $category_3) {
							$data = array(
							'filter_category_id'  => $category_3['category_id'],
							'filter_sub_category' => true
						);

	//					$product_total = $this->model_catalog_product->getTotalProducts($data);

						$level_3_data[] = array(
	//						'name'  => $child['name'] . ' (' . $product_total . ')',
							'name' => $category_3['name'],
							'href' => $this->url->link('product/category', 'path=' . $category_1['category_id'] . '_' . $category_2['category_id'] . '_' . $category_3['category_id'])
						);

					}

					$level_2_data[] = array(
						'name'     => $category_2['name'],
						'children' => $level_3_data,
						'column'   => $category_2['column'] ? $category_2['column'] : 1,
						'href'     => $this->url->link('product/category', 'path=' . $category_1['category_id'] . '_' . $category_2['category_id'])
					);
				}

					// Level 1
					$this->data['categories'][] = array(
						'name'     =>  $category_1['name'],
						'children' => $level_2_data,
						'column'   => $category_1['column'] ? $category_1['column'] : 1,
						'href'     => $this->url->link('product/category', 'path=' . $category_1['category_id']),
						'id' => $category_1['category_id']
					);
				}
			}
		}else{

		  $this->data['categories'] = "";
		}

    $this->data['interests_categories'] = $this->getChild('account/interests_categories');
    $this->data['customer_interests_remember'] = (($this->customer->getInterestsRemember() && $this->customer->getInterestsDate() < date('Y-m-d') || $this->customer->isLogged() && is_null($this->customer->getInterestsRemember())) && $this->config->get('fields_register_brazil_status_interests') && $this->config->get('fields_register_brazil_status_interests_for_old_users')) ? true : false;

		$this->children = array(
			'module/language',
			'module/currency',
			'module/cart' ,
			'common/header_block',
			'common/newsletter'
		);

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/header.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/common/header.tpl';
		} else {
			$this->template = 'default/template/common/header.tpl';
		}

    	$this->render();
	}


 public function setUserCookie(){

	 if($this->customer->isLogged()){
		 setcookie('user_logado', $this->customer->getEmail(), strtotime( '+5 days' ));
	 }

	 if(isset($_COOKIE['user_logado']) && !$this->customer->isLogged()){
		 $this->customer->login($_COOKIE['user_logado'], '', true);
	 }

 }

 public function loadScripts(){

   /*
   função para carregar os scripts/styles que a pagina necessita
   foi criado um array para cada um onde especificamos no key o caminho do arquivo e no value
   se esse arquivo necessita de alguma validação sendo que caso ele necessite podemos o usar o
   $this->config->get(campo_validacao) onde ele buscara se é verdadeiro ou falso passando o paramentro corrreto
   para a função, caso ele não necessite de validação basta passar o paramentro false.
   */
   $arrayCss = array (
     //'catalog/view/theme/default/stylesheet/listadepresentes.css' => $this->config->get('listapresente_status'),
     //'catalog/view/theme/vista/stylesheet/aviseme.css' => $this->config->get('avise_me_status')
   );

   foreach($arrayCss as $key => $value){
     if(!is_null($value)){
       if($value){
         $this->document->addStyle($key);
       }
     }
   }

   $arrayJs = array (
		 'catalog/view/javascript/jquery.mask.js' => true,
		 'catalog/view/javascript/masks.js' => true
   );

   foreach($arrayJs as $key => $value){
     if(!is_null($value)){
       if($value){
         $this->document->addScript($key);
       }
     }
   }

 }

}
?>
