<?php 
class ControllerFeedUniversalFeed extends Controller {
  const CODE = 'universal_data_feed';
  const MODULE = 'universal_feed';
  const PREFIX = 'univfeed';
  const MOD_FILE = 'universal_data_feed';
  
	private $error = array(); 
  private $token;
	
  public function __construct($registry) {
		parent::__construct($registry);
    
    if (version_compare(VERSION, '3', '>=')) {
      $this->language->load('catalog/product');
      $this->language->load('extension/feed/universal_feed');
    } else {
      $this->language->load('feed/universal_feed');
    }
    
    $this->token = isset($this->session->data['user_token']) ? 'user_token='.$this->session->data['user_token'] : 'token='.$this->session->data['token'];
	}

	public function index() {
    $this->db_tables();
    
		$data['_language'] = &$this->language;
		$data['_config'] = &$this->config;
		$data['_url'] = &$this->url;
		$data['token'] = $this->token;
    $data['OC_V2'] = version_compare(VERSION, '2', '>=');
		
    $asset_path = 'view/universal_feed/';
    
		if (!version_compare(VERSION, '2', '>=')) {
			$this->document->addStyle($asset_path.'awesome/css/font-awesome.min.css');
      $data['style_scoped'] = file_get_contents($asset_path . 'bootstrap.min.css');
			$data['style_scoped'] .= str_replace('img/', $asset_path . 'img/', file_get_contents($asset_path . 'style.css'));
			$this->document->addScript($asset_path . 'bootstrap.min.js');
		}
    
    $this->document->addScript($asset_path.'selectize.js');
		//$this->document->addStyle($asset_path.'selectize.css');
		$this->document->addStyle($asset_path.'selectize.bootstrap3.css');
		$this->document->addScript($asset_path.'jquery.tablednd.js');
		$this->document->addScript($asset_path.'itoggle.js');
		$this->document->addScript($asset_path.'toggler.js');
		$this->document->addStyle($asset_path.'style.css');

    foreach (array(self::MOD_FILE, 'a_'.self::MOD_FILE, 'z_'.self::MOD_FILE) as $mod_file) {
      if (is_file(DIR_SYSTEM.'../vqmod/xml/'.$mod_file.'.xml')) {
        $data['module_version'] = @simplexml_load_file(DIR_SYSTEM.'../vqmod/xml/'.$mod_file.'.xml')->version;
        $data['module_type'] = 'vqmod';
        break;
      } else if (is_file(DIR_SYSTEM.'../system/'.$mod_file.'.ocmod.xml')) {
        $data['module_version'] = @simplexml_load_file(DIR_SYSTEM.'../system/'.$mod_file.'.ocmod.xml')->version;
        $data['module_type'] = 'ocmod';
        break;
      } else {
        $data['module_version'] = 'not found';
        $data['module_type'] = '';
 		  }
		}
    
    $this->load->model('localisation/language');
		$languages = $this->model_localisation_language->getLanguages();
    
    foreach ($languages as $lang) {
      $data['languages'][$lang['language_id']] = $lang;
    }
    
    $data['is_demo'] = !$this->user->hasPermission('modify', 'feed/universal_feed');
    
    $this->load->model('localisation/currency');
    $data['currencies'] = $this->model_localisation_currency->getCurrencies();
    
    $this->load->model('catalog/manufacturer');
    $data['manufacturers'] = $this->model_catalog_manufacturer->getManufacturers();
    
    $this->load->model('catalog/option');
    $data['options'] = $this->model_catalog_option->getOptions();
    
    $this->load->model('catalog/category');
    $data['categories'] = $this->model_catalog_category->getCategories(array());
    
    if (version_compare(VERSION, '2.1', '>=')) {
      $this->load->model('customer/customer_group');
      $data['customer_groups'] = $this->model_customer_customer_group->getCustomerGroups();
    } else {
      $this->load->model('sale/customer_group');
      $data['customer_groups'] = $this->model_sale_customer_group->getCustomerGroups();
    }
    
		$this->document->setTitle(strip_tags($this->language->get('heading_title')));

		$this->load->model('setting/setting');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
      // handle gg merchant categories
      if (!empty($this->request->post['gg_merchant_cats'])) {
        foreach($this->request->post['gg_merchant_cats'] as $cat_id => $feed_cat_id) {
          $this->db->query("UPDATE " . DB_PREFIX . "category SET google_merchant_id = '" . (INT) $feed_cat_id . "' WHERE category_id = '" . (INT) $cat_id  . "'");
        }
        
        unset($this->request->post['gg_merchant_cats']);
      }
      
      // handle shareasale categories
      if (!empty($this->request->post['shareasale_cats'])) {
        foreach($this->request->post['shareasale_cats'] as $cat_id => $feed_cat_id) {
          $this->db->query("UPDATE " . DB_PREFIX . "category SET shareasale_cat = '" . $this->db->escape($feed_cat_id) . "' WHERE category_id = '" . (INT) $cat_id  . "'");
        }
        
        unset($this->request->post['shareasale_cats']);
      }
      
      // handle glami_ro categories
      if (!empty($this->request->post['glami_ro_cats'])) {
        foreach($this->request->post['glami_ro_cats'] as $cat_id => $feed_cat_id) {
          $this->db->query("UPDATE " . DB_PREFIX . "category SET glami_ro_cat = '" . $this->db->escape($feed_cat_id) . "' WHERE category_id = '" . (INT) $cat_id  . "'");
        }
        
        unset($this->request->post['glami_ro_cats']);
      }
      
      // handle heureka categories
      if (!empty($this->request->post['heureka_cats'])) {
        foreach($this->request->post['heureka_cats'] as $cat_id => $feed_cat_id) {
          $this->db->query("UPDATE " . DB_PREFIX . "category SET heureka_cat = '" . $this->db->escape($feed_cat_id) . "' WHERE category_id = '" . (INT) $cat_id  . "'");
        }
        
        unset($this->request->post['heureka_cats']);
      }
      
      $feeds = array();
      
      if (!empty($this->request->post['univfeed_feeds'])) {
        foreach ($this->request->post['univfeed_feeds'] as $feed) {
          $feed['code'] = strtolower(str_replace(' ', '-', preg_replace('/[^\w\.-_ ]/', '', html_entity_decode($feed['title'], ENT_QUOTES, 'UTF-8')))) . '.' . $feed['format'];
          $feeds[$feed['code']] = $feed;
        }
      }
      
      $this->request->post['univfeed_feeds'] = $feeds;
      
			$this->model_setting_setting->editSetting('universal_feed', array('universal_feed_status' => 1));
      
			$this->model_setting_setting->editSetting('univfeed', $this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

      if (version_compare(VERSION, '2', '>=')) {
				$this->response->redirect($this->url->link('feed/universal_feed', $this->token, 'SSL'));
			} else {
				$this->redirect($this->url->link('feed/universal_feed', $this->token, 'SSL'));
			}
		}

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_enabled'] = $this->language->get('text_enabled');
		$data['text_disabled'] = $this->language->get('text_disabled');

		$data['button_save'] = $this->language->get('button_save');
		$data['button_cancel'] = $this->language->get('button_cancel');

		$data['tab_general'] = $this->language->get('tab_general');

    if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];
			unset($this->session->data['success']);
		} else $data['success'] = '';
		
		if (isset($this->session->data['error'])) {
			$data['error'] = $this->session->data['error'];
			unset($this->session->data['error']);
		} else $data['error'] = '';
    
		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', $this->token, 'SSL'),
			'separator' => false
		);

		if (version_compare(VERSION, '3', '>=')) {
      $extension_link = $this->url->link('marketplace/extension', 'type=feed&' . $this->token, 'SSL');
    } else if (version_compare(VERSION, '2.3', '>=')) {
      $extension_link = $this->url->link('extension/extension', 'type=feed&' . $this->token, 'SSL');
    } else {
      $extension_link = $this->url->link('extension/feed', $this->token, 'SSL');
    }
    
		$data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_feed'),
      'href'      => $extension_link,
			'separator' => ' :: '
		);

		$data['breadcrumbs'][] = array(
			'text'      => strip_tags($this->language->get('heading_title')),
			'href'      => $this->url->link('feed/universal_feed', $this->token, 'SSL'),
			'separator' => ' :: '
		);

		$data['action'] = $this->url->link('feed/universal_feed', $this->token, 'SSL');

		$data['cancel'] = $extension_link;

    // CLI logs
    if (!empty($this->request->get['clear_cli_logs']) && file_exists(DIR_LOGS.'universal_feed_cron.log')) {
      unlink(DIR_LOGS.'universal_feed_cron.log');
      
      if (version_compare(VERSION, '2', '>=')) {
        $this->response->redirect($this->url->link('feed/universal_feed', $this->token, 'SSL'));
      } else {
        $this->redirect($this->url->link('feed/universal_feed', $this->token, 'SSL'));
      }
    }
    
    $data['cli_log'] = $data['cli_log_link'] = '';
    
    $file = DIR_LOGS.'universal_feed_cron.log';
    
		if (file_exists($file)) {
      $data['cli_log_link'] = $this->url->link('feed/universal_feed/save_cli_log', $this->token, 'SSL');
			$size = filesize($file);

			if ($size >= 5242880) {
				$suffix = array(
					'B',
					'KB',
					'MB',
					'GB',
					'TB',
					'PB',
					'EB',
					'ZB',
					'YB'
				);

				$i = 0;

				while (($size / 1024) > 1) {
					$size = $size / 1024;
					$i++;
				}

				$data['cli_log'] = sprintf($this->language->get('text_cli_log_too_big'), round(substr($size, 0, strpos($size, '.') + 4), 2) . $suffix[$i]);
			} else {
				$data['cli_log'] = file_get_contents($file);
			}
		}
    
    $this->load->model('setting/store');
    
    $stores = array();
    $stores[] = array(
      'store_id' => 0,
      'name'     => $this->config->get('config_name'),
      'url'     => (!empty($_SERVER['HTTPS']) ? HTTPS_CATALOG : HTTP_CATALOG),
    );

    $stores_data = $this->model_setting_store->getStores();
    
    foreach ($stores_data as $store) {
      $action = array();

      $stores[] = array(
        'store_id' => $store['store_id'],
        'name'     => $store['name'],
        'url'     => (!empty($_SERVER['HTTPS']) ? $store['ssl'] : $store['url']),
      );
    }
    
    $stores_json = array();
    
    foreach ($stores as $store) {
      $stores_json[] = $store['store_id'];
    }
    
    $data['stores_json'] = json_encode($stores_json);
    $data['stores'] = $stores;
    
    $data['feed_types'] = array();
    
    $feed_groups = array(
      '- International -' => array('bing', 'google_merchant', 'google_adwords', 'google_promotion', 'google_reviews', 'wish', 'facebook', 'kelkoo', 'shopalike', 'shopmania', 'twenga', 'shareasale', 'amazon', 'glami_ro', 'stockmount'),
      '- Create your own -' => array('custom', 'custom_xml'),
      '- Standart -' => array('common_feed', 'rss_product'),
      'Austria' => array('geizhals'),
      'Czech/Slovakia/Poland' => array('heureka', 'okazje_info', 'nokaut', 'ceneo'),
      'Italia' => array('trovaprezzi_it', 'itscope'),
      'Turkey' => array('akakce', 'hepsiburada', 'trendyol', 'n11', 'xmlcikti'),
      'Russia/Ukraine' => array('ekatalog'),
      'Greece' => array('skroutz'),
      'Romania' => array('compari_ro'),
      'Hungary' => array('arukereso'),
      'Slovenia' => array('ceneje'),
    );
    
    $groups_array = array();
    
		foreach ($feed_groups as $group_name => $feed_group) {
      foreach ($feed_group as $feed_name) {
        $groups_array[$feed_name] = $group_name;
      }
    }
    
    $feed_types = glob(DIR_APPLICATION . 'view/template/feed/universal_feed/*.tpl');
    
		foreach ($feed_types as $feed_type) {
      $group = isset($groups_array[ basename($feed_type, '.tpl')]) ? $groups_array[ basename($feed_type, '.tpl')] : '- Undefined -';
			$data['feed_types'][$group][] = basename($feed_type, '.tpl');
		}
    
    ksort($data['feed_types']);
    
    if (isset($this->request->post['univfeed_feeds'])) {
			$data['univfeed_feeds'] = $this->request->post['univfeed_feeds'];
		} else {
			$data['univfeed_feeds'] = $this->config->get('univfeed_feeds');
		}
    
    if (isset($this->request->post['univfeed_rewrite'])) {
			$data['univfeed_rewrite'] = $this->request->post['univfeed_rewrite'];
		} else {
			$data['univfeed_rewrite'] = $this->config->get('univfeed_rewrite');
		}
    
    if (isset($this->request->post['univfeed_sleep'])) {
			$data['univfeed_sleep'] = $this->request->post['univfeed_sleep'];
		} else {
			$data['univfeed_sleep'] = $this->config->get('univfeed_sleep');
		}
    
    if (isset($this->request->post['univfeed_fix_chinese_chars'])) {
			$data['univfeed_fix_chinese_chars'] = $this->request->post['univfeed_fix_chinese_chars'];
		} else {
			$data['univfeed_fix_chinese_chars'] = $this->config->get('univfeed_fix_chinese_chars');
		}
    
    if (isset($this->request->post['univfeed_cron_key'])) {
			$data['univfeed_cron_key'] = $this->request->post['univfeed_cron_key'];
		} else {
			$data['univfeed_cron_key'] = $this->config->get('univfeed_cron_key');
		}
    
		//$data['data_feed'] = HTTP_CATALOG . 'index.php?route=feed/universal_feed';
    
		$data['generator_url'] = (!empty($_SERVER['HTTPS']) ? HTTPS_CATALOG : HTTP_CATALOG) . 'index.php?route=feed/universal_feed&generate=1';
    
		$data['gg_cats_url'] = $this->url->link('feed/universal_feed/gg_taxonomy', $this->token, 'SSL');
    
    $current_feed_types = array();
    
    // load specific feed options
    $feed_row = 1;
    if (!empty($data['univfeed_feeds'])) {
      foreach ($data['univfeed_feeds'] as &$feed) {
        $data['feed_row'] = $feed_row++;
        
        $current_feed_types[$feed['type']] = $feed['type'];
      
        // get file dates
        foreach ($stores as $store) { 
          $feed['date_cache_'.$store['store_id']] = $feed['date_reload_'.$store['store_id']] = '';
        
          $curFile = DIR_CACHE . 'feed/' . $store['store_id'] . '-' . $feed['code'];
        
        if (file_exists($curFile)) {
            $feed['date_cache_'.$store['store_id']] = date($this->language->get('datetime_format'), filemtime($curFile));
          
          if ($feed['cache_delay']) {
              $feed['date_reload_'.$store['store_id']] = date($this->language->get('datetime_format'), filemtime($curFile) + strtotime('+' . $feed['cache_delay'] . ' ' . $feed['cache_unit'], '0'));
            }
          }
        }
        
        $feed['feed_url'] = array();
        
        if (!empty($feed['protect_password'])) {
          if ($this->config->get('univfeed_rewrite')) {
            $password = '?pass='.$feed['protect_password'];
          } else {
            $password = '&pass='.$feed['protect_password'];
          }
        } else {
          $password = '';
        }
        
        foreach ($stores as $store) { 
          if (isset($feed['store']) && $feed['store'] !== '' && $feed['store'] != $store['store_id']) continue;
          
          if ($this->config->get('univfeed_rewrite')) {
            $feed['feed_url'][] = $store['url'] . 'feed/' . $feed['code'] . $password;
          } else {
            $feed['feed_url'][] = $store['url'] . 'index.php?route=feed/universal_feed&feed=' . $feed['code'] . $password;
          }
        }
        
        // get special options
        if (!empty($feed['type'])) {
          $tpl_file = 'feed/universal_feed/'.$feed['type'].'.tpl';
        
          $data['feed'] = $feed;
          if (version_compare(VERSION, '3', '>=')) {
            $template = new Template('template', $this->registry);
            foreach ($data as $key => $value) {
              $template->set($key, $value);
            }
            $tpl_file = pathinfo($tpl_file, PATHINFO_DIRNAME) . '/' . pathinfo($tpl_file, PATHINFO_FILENAME);
            
            $rf = new ReflectionMethod('Template', 'render');
          
            if ($rf->getNumberOfParameters() > 2) {
              $feed['specialOptions'][$feed['code']] = $template->render($tpl_file, $this->registry, false);
            } else {
              $feed['specialOptions'][$feed['code']] = $template->render($tpl_file, false);
            }
          } else if (version_compare(VERSION, '2.2', '>=')) {
            $template = new Template(version_compare(VERSION, '2.3', '>=') ? 'php': 'basic');
            foreach ($data as $key => $value) {
              $template->set($key, $value);
            }
            $feed['specialOptions'][$feed['code']] = $template->render($tpl_file, null);
          } elseif (method_exists($this->load, 'view')) {
            $feed['specialOptions'][$feed['code']] = $this->load->view($tpl_file, $data);
          } else {
            $template = new Template();
            $template->data = &$data;
            $feed['specialOptions'][$feed['code']] = $template->fetch($tpl_file);
          }
        }
      }
    }
    
    $data['current_feed_types'] = $current_feed_types;
    
    $extra_select = '';
    
    foreach ($current_feed_types as $type) {
      if (strpos($type, 'google') !== false || $type == 'facebook' || $type == 'bing') {
        if (!$this->db->query("SHOW COLUMNS FROM `" . DB_PREFIX . "category` LIKE 'google_merchant_id'")->row) {
          $this->db->query("ALTER TABLE `" . DB_PREFIX . "category` ADD `google_merchant_id` INT(11) DEFAULT 0");
        }
        
        $extra_select .= 'c1.google_merchant_id,';
      } else if ($type == 'shareasale') {
        if (!$this->db->query("SHOW COLUMNS FROM `" . DB_PREFIX . "category` LIKE 'shareasale_cat'")->row) {
          $this->db->query("ALTER TABLE `" . DB_PREFIX . "category` ADD `shareasale_cat` VARCHAR(10) DEFAULT ''");
        }
        
        $extra_select .= 'c1.shareasale_cat,';
      } else if ($type == 'glami_ro') {
        if (!$this->db->query("SHOW COLUMNS FROM `" . DB_PREFIX . "category` LIKE 'glami_ro_cat'")->row) {
          $this->db->query("ALTER TABLE `" . DB_PREFIX . "category` ADD `glami_ro_cat` VARCHAR(10) DEFAULT ''");
        }
        
        $extra_select .= 'c1.glami_ro_cat,';
      } else if ($type == 'heureka') {
        if (!$this->db->query("SHOW COLUMNS FROM `" . DB_PREFIX . "category` LIKE 'heureka_cat'")->row) {
          $this->db->query("ALTER TABLE `" . DB_PREFIX . "category` ADD `heureka_cat` VARCHAR(255) DEFAULT ''");
        }
        
        $extra_select .= 'c1.heureka_cat,';
      }
    }
    
    // categories
    //$this->load->model('catalog/category');
    //$data['categories'] = $this->model_catalog_category->getCategories(0);
    $data['categories'] = $this->db->query("SELECT " . $extra_select . " cp.category_id, GROUP_CONCAT(cd1.name ORDER BY cp.level SEPARATOR '&nbsp;&nbsp;&gt;&nbsp;&nbsp;') AS name, c1.parent_id, c1.sort_order FROM " . DB_PREFIX . "category_path cp LEFT JOIN " . DB_PREFIX . "category c1 ON (cp.category_id = c1.category_id) LEFT JOIN " . DB_PREFIX . "category c2 ON (cp.path_id = c2.category_id) LEFT JOIN " . DB_PREFIX . "category_description cd1 ON (cp.path_id = cd1.category_id) LEFT JOIN " . DB_PREFIX . "category_description cd2 ON (cp.category_id = cd2.category_id) WHERE cd1.language_id = '" . (int)$this->config->get('config_language_id') . "' AND cd2.language_id = '" . (int)$this->config->get('config_language_id') . "' GROUP BY cp.category_id ORDER BY name")->rows;
    
    // feed categories
    foreach ($current_feed_types as $type) {
      if ($type == 'google_merchant' || $type == 'facebook' || $type == 'bing') {
        $data['gg_cats_array'] = $this->getGoogleCategories($data['categories'], true, true);
        $data['gg_cats'] = $this->getGoogleCategories($data['categories'], true);
      } else if ($type == 'shareasale') {
        $data['shareasale_cats'] = $this->getCategories('shareasale');
        $data['shareasale_catgroups'] = $this->getCatetoryGroups('shareasale');
      } else if ($type == 'heureka') {
        $heureka_cats = $this->getEurekaCategories('heureka');
        $heureka_catgroups = array();
        
        foreach ($heureka_cats as $cat) {
          $heureka_catgroups[$cat['group']] = array(
            'group' => $cat['group'],
            'name' => $cat['group'],
          );
        }
        
        array_shift($heureka_catgroups);
        
        $data['heureka_cats'] = json_encode($heureka_cats);
        $data['heureka_catgroups'] = json_encode($heureka_catgroups);
      } else if ($type == 'glami_ro') {
        $glami_ro_cats = $this->getGlamiCategories('glami_ro');
        $glami_ro_catgroups = array();
        
        foreach ($glami_ro_cats as $cat) {
          $glami_ro_catgroups[$cat['group']] = array(
            'group' => $cat['group'],
            'name' => $cat['group'],
          );
        }
        
        array_shift($glami_ro_catgroups);
        
        $data['glami_ro_cats'] = json_encode($glami_ro_cats);
        $data['glami_ro_catgroups'] = json_encode($glami_ro_catgroups);
      }
    }
    
		if (version_compare(VERSION, '2', '>=')) {
			$data['header'] = $this->load->controller('common/header');
			$data['column_left'] = $this->load->controller('common/column_left');
			$data['footer'] = $this->load->controller('common/footer');
			
      if (version_compare(VERSION, '3', '>=')) {
        $this->config->set('template_engine', 'template');
        $this->response->setOutput($this->load->view('feed/universal_feed', $data));
      } else {
			 $this->response->setOutput($this->load->view('feed/universal_feed.tpl', $data));
      }
		} else {
			$data['column_left'] = '';
			$this->data = &$data;
			$this->template = 'feed/universal_feed.tpl';
			$this->children = array(
				'common/header',
				'common/footer'
			);
					
			$this->response->setOutput(str_replace(array('view/javascript/jquery/jquery-1.6.1.min.js', 'view/javascript/jquery/jquery-1.7.1.min.js', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'), $asset_path . 'jquery.min.js', $this->render()));
		}
	}

	public function gg_taxonomy($categories = null) {
    $gg_cats_file = 'view/universal_feed/google_taxonomy/'.substr($this->config->get('config_language'), 0, 2).'.txt';
    
    if (!file_exists($gg_cats_file)) {
      $gg_cats_file = 'view/universal_feed/google_taxonomy/en.txt';
    }
    
    $gg_cats_file = file($gg_cats_file);
    
    $header = array_shift($gg_cats_file);
    
    echo nl2br($header);
    
    foreach ($gg_cats_file as $gg_cat) {
      list($id, $fullname) = explode('-', $gg_cat, 2);
      echo trim(nl2br($fullname));
    }
    
    //echo nl2br(file_get_contents($gg_cats_file));
  }
  
	public function getGoogleCategories($categories = null, $return = false, $nojson = false) {
    $gg_cats_file = 'view/universal_feed/google_taxonomy/'.substr($this->config->get('config_admin_language'), 0, 2).'.txt';
    
    if (!file_exists($gg_cats_file)) {
      $gg_cats_file = 'view/universal_feed/google_taxonomy/en.txt';
    }
    
    $gg_cats = array();
    $gg_cats_file = file($gg_cats_file);
    array_shift($gg_cats_file);
    
    $limit = 500;
    
    $currIds = array();
    
    if ($categories) {
      foreach($categories as $cat) {
        $currIds[] = $cat['google_merchant_id'];
      }
    }
      
    foreach ($gg_cats_file as $gg_cat) {
      list($id, $fullname) = explode('-', $gg_cat, 2);
      $id = (int) $id;
      
      if ((isset($_GET['q']) && stripos($fullname, $_GET['q']) !== false) ||
         ((isset($currIds) && in_array($id, $currIds)))) {
           
        if (!$categories && ($limit < 0)) {
          break;
        }

        if (strrpos($fullname, '>') !== false) {
          $name = substr($fullname, strrpos($fullname, '>') + 1);
          $cats = substr($fullname, 0, strrpos($fullname, '>') -1);
        } else {
          $name = $fullname;
          $cats = '';
        }
        
        if ($nojson) {
          $gg_cats[$id] = array(
            'id' => $id,
            'name' => trim($name),
            'cats' => trim($cats),
          );
        } else {
          $gg_cats[] = array(
            'id' => $id,
            'name' => trim($name),
            'cats' => trim($cats),
          );
        }
        
        $limit--;
      }
    }
    
    if ($return) {
      if ($nojson) {
        return $gg_cats;
      }
      return json_encode($gg_cats);
    }
/*
    if (!count($gg_cats)) {
      $gg_cats[] = array(
        'id' => 0,
        'name' => 'No result',
        'cats' => '',
      );
    }
    */
    if ($nojson) {
      return $gg_cats;
    }

    header('Content-type: application/json');
    echo json_encode($gg_cats);
    die;
  }
  
  public function getCatetoryGroups($type) {
    $cats_file = 'view/universal_feed/'.$type.'_taxonomy/'.substr($this->config->get('config_language'), 0, 2).'.php';
    
    if (!file_exists($cats_file)) {
      $cats_file = 'view/universal_feed/'.$type.'_taxonomy/en.php';
    }
    
    include(DIR_APPLICATION . $cats_file);
    
    $array = array();
    
    foreach ($groups as $key => $group) {
      $array[] = array(
        'group' => (string) $key,
        'name' => $group,
      );
    }
    
    return json_encode($array);
  }
  
  public function getCategories($type) {
    $cats_file = 'view/universal_feed/'.$type.'_taxonomy/'.substr($this->config->get('config_language'), 0, 2).'.php';
    
    if (!file_exists($cats_file)) {
      $cats_file = 'view/universal_feed/'.$type.'_taxonomy/en.php';
    }
    
    include(DIR_APPLICATION . $cats_file);
    
    $array = array();
    
    foreach ($categories as $key => $name) {
      $array[] = array(
        'group' => strstr($key, '|', true),
        'val' => $key,
        'name' => $groups[strstr($key, '|', true)] . ' > ' . $name,
      );
    }
    
    return json_encode($array);
  }
  
  private function getGlamiCategories($type) {
    $cats_file = 'view/universal_feed/'.$type.'_taxonomy/'.substr($this->config->get('config_language'), 0, 2).'.xml';
    
    if (!file_exists($cats_file)) {
      $cats_file = 'view/universal_feed/'.$type.'_taxonomy/default.xml';
    }
    
    $xml = simplexml_load_file(DIR_APPLICATION . $cats_file);
    $array = array();
    
    $array = $this->getGlamiRecursive($xml);
    
    return $array;
  }
  
  private function getGlamiRecursive($categories, $array = array()) {
    foreach ($categories as $key => $cat) {
      $array[] = array(
        'group' => trim(str_replace(array('Glami.ro | ', (string) $cat->CATEGORY_NAME), '', (string) $cat->CATEGORY_FULLNAME), ' |'),
        'val' => (string) $cat->CATEGORY_ID,
        'name' => str_replace('Glami.ro | ', '', (string) $cat->CATEGORY_FULLNAME),
      );
      
      if (!empty($cat->CATEGORY)) {
        foreach ($this->getGlamiRecursive($cat->CATEGORY) as $val) {
          array_push($array, $val);
        }
      }
    }
    
    return $array;
  }
  
  private function getEurekaCategories($type) {
    $cats_file = 'view/universal_feed/'.$type.'_taxonomy/'.substr($this->config->get('config_language'), 0, 2).'.xml';
    
    if (!file_exists($cats_file)) {
      $cats_file = 'view/universal_feed/'.$type.'_taxonomy/default.xml';
    }
    
    $xml = simplexml_load_file(DIR_APPLICATION . $cats_file);
    
    $array = $this->getEurekaRecursive($xml);
    
    return $array;
  }
  
  private function getEurekaRecursive($categories, $array = array()) {
    foreach ($categories as $key => $cat) {
      $array[] = array(
        'group' => trim(str_replace(array('Heureka.sk | ', (string) $cat->CATEGORY_NAME), '', (string) $cat->CATEGORY_FULLNAME), ' |'),
        'val' => str_replace('Heureka.sk | ', '', (string) $cat->CATEGORY_FULLNAME),
        'name' => str_replace('Heureka.sk | ', '', (string) $cat->CATEGORY_FULLNAME),
      );
      
      if (!empty($cat->CATEGORY)) {
        foreach ($this->getEurekaRecursive($cat->CATEGORY) as $val) {
          array_push($array, $val);
        }
      }
    }
    
    return $array;
  }
  
	public function getFeedOptions() {
    $data['_language'] = &$this->language;
    
    $this->load->model('localisation/currency');
    $data['currencies'] = $this->model_localisation_currency->getCurrencies();
    
    $this->load->model('localisation/language');
    $data['languages'] = $this->model_localisation_language->getLanguages();
    
    $this->load->model('catalog/manufacturer');
    $data['manufacturers'] = $this->model_catalog_manufacturer->getManufacturers();
    
    $this->load->model('catalog/option');
    $data['options'] = $this->model_catalog_option->getOptions();
    
    $this->load->model('catalog/category');
    $data['categories'] = $this->model_catalog_category->getCategories(array());
         
    if (version_compare(VERSION, '2.1', '>=')) {
      $this->load->model('customer/customer_group');
      $data['customer_groups'] = $this->model_customer_customer_group->getCustomerGroups();
    } else {
      $this->load->model('sale/customer_group');
      $data['customer_groups'] = $this->model_sale_customer_group->getCustomerGroups();
    }
    
    $data['data_feed'] = (!empty($_SERVER['HTTPS']) ? HTTPS_CATALOG : HTTP_CATALOG) . 'index.php?route=feed/universal_feed';
    
    $this->load->model('setting/store');
    
    $stores = array();
    $stores[] = array(
      'store_id' => 0,
      'name'     => $this->config->get('config_name'),
      'url'     => (!empty($_SERVER['HTTPS']) ? HTTPS_CATALOG : HTTP_CATALOG),
    );

    $stores_data = $this->model_setting_store->getStores();
    
    foreach ($stores_data as $store) {
      $action = array();

      $stores[] = array(
        'store_id' => $store['store_id'],
        'name'     => $store['name'],
        'url'     => (!empty($_SERVER['HTTPS']) ? $store['ssl'] : $store['url']),
      );
    }

    $data['stores'] = $stores;
    
    foreach ($_POST['univfeed_feeds'] as $row => $feed) {
      if (!empty($feed['type'])) {
        $tpl_file = 'feed/universal_feed/'.$feed['type'].'.tpl';
      
        $data['feed_row'] = $row;
        
        $data['feed'] = $feed;
        if (version_compare(VERSION, '3', '>=')) {
          $template = new Template('template', $this->registry);
          foreach ($data as $key => $value) {
            $template->set($key, $value);
          }
          $tpl_file = pathinfo($tpl_file, PATHINFO_DIRNAME) . '/' . pathinfo($tpl_file, PATHINFO_FILENAME);

          $rf = new ReflectionMethod('Template', 'render');

          if ($rf->getNumberOfParameters() > 2) {
            echo $template->render($tpl_file, $this->registry, false);
          } else {
            echo $template->render($tpl_file, false);
          }
          die;
        } else if (version_compare(VERSION, '2.2', '>=')) {
          $template = new Template(version_compare(VERSION, '2.3', '>=') ? 'php': 'basic');
          foreach ($data as $key => $value) {
            $template->set($key, $value);
          }

          echo $template->render($tpl_file, null);
          die;
        } elseif (method_exists($this->load, 'view')) {
          echo $this->load->view($tpl_file, $data);
          die;
        } else {
          $template = new Template();
          $template->data = &$data;
          echo $template->fetch($tpl_file);
          die;
        }
      }
    }
  }
  
  // public function process() {
    // echo file_get_contents(HTTP_CATALOG . 'index.php?route=feed/universal_feed&feed='.$this->request->get['feed'].'&generate=1&start='.$this->request->get['start']);
  // }
  
  public function cron($params = '') {
    $this->cron_log(PHP_EOL . '##### Cron Request - ' . date('d/m/Y H:i:s') . ' #####' . PHP_EOL);
  }
  
  public function save_cli_log() {
    $file = DIR_LOGS.'universal_feed_cron.log';
    header('Content-Description: File Transfer');
    header('Content-Disposition: attachment; filename=universal_feed_cron.log');
    header('Content-Type: text/plain');
    header('Cache-Control: must-revalidate');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
  }
  
  public function cron_log($msg = '') {
    $echo = false;

    if ($echo) {
      echo $msg . PHP_EOL;
    } else {
      file_put_contents(DIR_LOGS.'universal_feed_cron.log', $msg . PHP_EOL, FILE_APPEND | LOCK_EX);
    }
  }
  
  public function test_ftp() {
    include(DIR_SYSTEM . 'library/SFTP.php');
    
    $ftp = new SFTP($this->request->post['ftp_server'], $this->request->post['ftp_user'], $this->request->post['ftp_pwd']);
    
    //error_reporting(0);

    if ($ftp->connect()) {
      echo $this->language->get('text_ftp_ok');
    } else {
      echo $ftp->error;
    }
    
    die;
  }
  
  private function db_tables() {
    // check DB columns
  }
  
	protected function validate() {
		if (!$this->user->hasPermission('modify', 'feed/universal_feed')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if (!$this->error) {
			return true;
		} else {
			return false;
		}	
	}	
}
?>