<?php
class ControllerFeedGoogleBase extends Controller {
	public function index() {
		if ($this->config->get('google_base_status')) {
			$output  = '<?xml version="1.0" encoding="UTF-8" ?>';
			$output .= '<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">';
			$output .= '<channel>';
			$output .= '<title>' . $this->addCDATA($this->simpleCleanString($this->config->get('config_name'))) . '</title>';
			$output .= '<description>' . $this->addCDATA($this->cleanString($this->config->get('config_meta_description'))) . '</description>';
			$output .= '<link>' . HTTP_SERVER . '</link>';

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

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

			$this->load->model('tool/image');

			$products = $this->model_catalog_product->getProducts();

				$total_incluidos = 0;
			

			foreach ($products as $product) {
				if ($product['description']) {

				$total_incluidos++;
			

				$output .= "\n";
			
					$output .= '<item>';
					$output .= '<title>' . $this->addCDATA(substr($this->simpleCleanString($product['name']), 0, 150)) . '</title>';
					$output .= '<link>' . $this->url->link('product/product', 'product_id=' . $product['product_id']) . '</link>';
					$output .= '<description>' . $this->addCDATA(substr($this->cleanString($product['description']), 0, 5000)) . '</description>';
					$output .= '<g:brand>' . $this->addCDATA(substr($this->simpleCleanString($product['manufacturer']), 0, 70)) . '</g:brand>';
					$output .= '<g:condition>new</g:condition>';
					$output .= '<g:id>' . $product['product_id'] . '</g:id>';

					if ($product['image']) {
						$output .= '<g:image_link>' . $this->model_tool_image->resize($product['image'], 500, 500) . '</g:image_link>';
					} else {
						$output .= '<g:image_link></g:image_link>';
					}

					$output .= '<g:model_number>' . $this->addCDATA($this->simpleCleanString($product['model'])) . '</g:model_number>';

					if ($product['mpn']) {
						$output .= '<g:mpn>' . $this->addCDATA($this->simpleCleanString($product['mpn'])) . '</g:mpn>' ;
					} else {
						
				if ($product['upc'] == '' && $product['ean'] == '' && $product['jan'] == '' && $product['isbn'] == '') {
					$output .= '<g:identifier_exists>false</g:identifier_exists>';
				}
			
					}


				if ($product['upc'] != '' || $product['ean'] != '' || $product['jan'] != '' || $product['isbn'] != '') {
					if ($product['upc'] != '') {
						$gtin = $product['upc'];

					} else if ($product['ean'] != '') {
						$gtin = $product['ean'];

					} else if ($product['jan'] != '') {
						$gtin = $product['jan'];

					} else if ($product['isbn'] != '') {
						$gtin = $product['isbn'];
					}

					$output .= '<g:gtin>' . $gtin . '</g:gtin>';
				}

				if ($product['jan']) {
					$output .= '<g:jan>' . $product['jan'] . '</g:jan>';
				}

				if ($product['isbn']) {
					$output .= '<g:isbn>' . $product['isbn'] . '</g:isbn>';
				}
			
					if ($product['upc']) {
						$output .= '<g:upc>' . $product['upc'] . '</g:upc>';
					}

					if ($product['ean']) {
						$output .= '<g:ean>' . $product['ean'] . '</g:ean>';
					}

					$currencies = array(
						'USD',

				'BRL',
			
						'EUR',
						'GBP'
					);

					if (in_array($this->currency->getCode(), $currencies)) {
						$currency_code = $this->currency->getCode();
						$currency_value = $this->currency->getValue();
					} else {
						$currency_code = 'USD';
						$currency_value = $this->currency->getValue('USD');
					}

					if ((float)$product['special']) {
						$output .= '<g:price>' . $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id']), $currency_code, $currency_value, false) . ' ' . $currency_code . '</g:price>';
				$output .= '<g:sale_price>' .  $this->currency->format($this->tax->calculate($product['special'], $product['tax_class_id']), $currency_code, $currency_value, false) . ' ' . $currency_code . '</g:sale_price>';
					} else {
						$output .= '<g:price>' . $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id']), $currency_code, $currency_value, false) . ' ' . $currency_code . '</g:price>';
					}

					$categories = $this->model_catalog_product->getCategories($product['product_id']);

					foreach ($categories as $category) {
						$path = $this->getPath($category['category_id']);

						if ($path) {
							$string = '';

							foreach (explode('_', $path) as $path_id) {
								$category_info = $this->model_catalog_category->getCategory($path_id);

								if ($category_info) {
									if (!$string) {
										$string = $category_info['name'];
									} else {
										$string .= ' &gt; ' . $category_info['name'];
									}
								}
							}

							$output .= '<g:product_type>' . $this->addCDATA(substr($this->simpleCleanString($string), 0, 750)) . '</g:product_type>';
						}
					}

					$output .= '<g:quantity>' . $product['quantity'] . '</g:quantity>';
					$weight_unit = $this->weight->getUnit($product['weight_class_id']);
				$output .= '<g:weight>' . str_replace($weight_unit, " {$weight_unit}", $this->weight->format($product['weight'], $product['weight_class_id'])) . '</g:weight>';
					$output .= '<g:availability>' . $this->addCDATA(($product['quantity'] ? 'in stock' : 'out of stock')) . '</g:availability>';
					$output .= '</item>';
				}
			}


				$output .= "\n";
				$output .= '<total_geral>'. count($products) .'</total_geral>';
				$output .= '<total_incluidos>'. $total_incluidos .'</total_incluidos>';
			
			$output .= '</channel>';
			$output .= '</rss>';

			$this->response->addHeader('Content-Type: application/rss+xml; charset=utf-8');
			$this->response->setOutput($output);
		}
	}


				private function convert_accented_characters($str) {
					$foreign_characters = array(
						'/ä|æ|ǽ/' => 'ae',
						'/ö|œ/' => 'oe',
						'/ü/' => 'ue',
						'/Ä/' => 'Ae',
						'/Ü/' => 'Ue',
						'/Ö/' => 'Oe',
						'/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A',
						'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a',
						'/Ç|Ć|Ĉ|Ċ|Č/' => 'C',
						'/ç|ć|ĉ|ċ|č/' => 'c',
						'/Ð|Ď|Đ/' => 'D',
						'/ð|ď|đ/' => 'd',
						'/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E',
						'/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e',
						'/Ĝ|Ğ|Ġ|Ģ/' => 'G',
						'/ĝ|ğ|ġ|ģ/' => 'g',
						'/Ĥ|Ħ/' => 'H',
						'/ĥ|ħ/' => 'h',
						'/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I',
						'/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i',
						'/Ĵ/' => 'J',
						'/ĵ/' => 'j',
						'/Ķ/' => 'K',
						'/ķ/' => 'k',
						'/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L',
						'/ĺ|ļ|ľ|ŀ|ł/' => 'l',
						'/Ñ|Ń|Ņ|Ň/' => 'N',
						'/ñ|ń|ņ|ň|ŉ/' => 'n',
						'/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O',
						'/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o',
						'/Ŕ|Ŗ|Ř/' => 'R',
						'/ŕ|ŗ|ř/' => 'r',
						'/Ś|Ŝ|Ş|Š/' => 'S',
						'/ś|ŝ|ş|š|ſ/' => 's',
						'/Ţ|Ť|Ŧ/' => 'T',
						'/ţ|ť|ŧ/' => 't',
						'/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U',
						'/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u',
						'/Ý|Ÿ|Ŷ/' => 'Y',
						'/ý|ÿ|ŷ/' => 'y',
						'/Ŵ/' => 'W',
						'/ŵ/' => 'w',
						'/Ź|Ż|Ž/' => 'Z',
						'/ź|ż|ž/' => 'z',
						'/Æ|Ǽ/' => 'AE',
						'/ß/'=> 'ss',
						'/Ĳ/' => 'IJ',
						'/ĳ/' => 'ij',
						'/Œ/' => 'OE',
						'/ƒ/' => 'f',
						'/¹/' => '1',
						'/²/' => '2',
						'/³/' => '3'
					);

					return preg_replace(array_keys($foreign_characters), array_values($foreign_characters), $str);
				}

				protected function cleanString($string) {
					$string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
					$string = str_replace('&nbsp;', ' ', $string);
					$string = $this->convert_accented_characters($string);
					$string = preg_replace('/<[^>]*>/', ' ', $string); // remove tags
					$string = preg_replace('/[^[:word:][:punct:][:space:]]/', ' ', $string); // remove qualquer caractere estranho
					$string = preg_replace('/[([:punct:])]{2,}/', '$1', $string); // substitui pontuações seguidas
					$string = preg_replace('/[\n\r\t\v\h\f]+/', ' ', $string); // substitui newline e tabs
					$string = preg_replace('/\s+/', ' ', $string); // substitui vários espaços por um
					$string = strip_tags($string);
					$string = trim($string);
					return $string;
				}

				protected function simpleCleanString($string) {
					$string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
					$string = str_replace('&nbsp;', ' ', $string);
					$string = trim($string);
					return $string;
				}

				protected function addCDATA($string) {
					return '<!['.'CDATA[' . $string . ']'.']>';
				}
			
	protected function getPath($parent_id, $current_path = '') {
		$category_info = $this->model_catalog_category->getCategory($parent_id);

		if ($category_info) {
			if (!$current_path) {
				$new_path = $category_info['category_id'];
			} else {
				$new_path = $category_info['category_id'] . '_' . $current_path;
			}

			$path = $this->getPath($category_info['parent_id'], $new_path);

			if ($path) {
				return $path;
			} else {
				return $new_path;
			}
		}
	}
}