<?php
class ControllerFeedGoogleBase extends Controller {

	public function index() {

		if ($this->config->get('google_base_status')) {

			ini_set('memory_limit', '256m');
			ini_set('max_execution_time', '900');

			$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->config->get('config_name') . '</title>';
			$output .= '<description>' . $this->config->get('config_meta_description') . '</description>';
			$output .= '<link>' . $this->config->get('config_url') . '</link>';

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

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

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

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

			foreach ($products as $product) {
				if ( (trim(strip_tags($product['description']))!="") && (trim($product['image'])!="") ) {
					$output .= '<item>';
					$output .= '<title>' . htmlspecialchars($product['name'], ENT_QUOTES, 'UTF-8') . '</title>';
					$output .= '<link>' . htmlspecialchars(str_replace('&amp;', '&', $this->url->link('product/product', 'product_id=' . $product['product_id']))) . '</link>';
					$output .= '<description>' . strtolower(str_replace('&nbsp;', ' ',strip_tags($product['description']))). '</description>';					
					$output .= '<g:condition>new</g:condition>';

					if($product['manufacturer']!=''){
						$output .= '<g:brand>' . htmlspecialchars($product['manufacturer'], ENT_QUOTES, 'UTF-8') . '</g:brand>';
					}
					
					
					if( $this->isEAN8($product['codigo_barra']) ){
						$output .= '<g:gtin>'.$product['codigo_barra'].'</g:gtin>';
					}

					if( $this->isEAN12($product['codigo_barra']) ){
						$output .= '<g:gtin>'.$product['codigo_barra'].'</g:gtin>';
					}

					if( $this->isEAN13($product['codigo_barra']) ){
						$output .= '<g:gtin>'.$product['codigo_barra'].'</g:gtin>';
					}

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

					if( ($product['codigo_barra']=='') && ($product['mpn']=='') ){
						$output .= '<g:identifier_exists>false</g:identifier_exists>';
					}

					$output .= '<g:id>' . $product['product_id'] . '</g:id>';

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

					$currencies = array('USD','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');
				  }

				  $output .= '<g:price>' . $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id']), $currency_code, $currency_value, false) . '</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 = htmlspecialchars($category_info['name']);
									} else {
										$string .= ' &gt; ' . htmlspecialchars($category_info['name']);
									}
								}
							}
							$output .= '<g:product_type>' . $string . '</g:product_type>';
						}
					}

					$output .= '<g:quantity>' . $product['quantity'] . '</g:quantity>';
					$output .= '<g:upc>' . $product['upc'] . '</g:upc>';
					$output .= '<g:weight>' . $this->weight->format($product['weight'], $product['weight_class_id']) . '</g:weight>';

					$stock = '';
					if($product['quantity'] > 0){
						$stock = 'in stock';
					}else{
						$stock = 'out of stock';
					}

					$output .= '<g:availability>' . $stock. '</g:availability>';
					$output .= '</item>';
				}
			}

			$output .= '</channel>';
			$output .= '</rss>';

			$this->response->addHeader('Content-Type: application/xml');
			$this->response->setOutput($output);
		}
	}

	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;
			}
		}
	}

	protected function isEAN8($upccode){// também conhecido como GTIN
    $odd_sum = $even_sum = 0;
    if(strlen($upccode) != 8) return FALSE;
    $chars = str_split($upccode);
    for($i=0;$i<7;$i++)
    {
        if($i%2==0){
          $odd_sum += $chars[$i] * 3;
        }else{
          $even_sum += $chars[$i] ;
        }
    }
    $total_sum = $even_sum + $odd_sum;

    $modulo10 = $total_sum % 10;
    $check_digit = 10 - $modulo10;
    return (int)$chars[7] === $check_digit;
  }
  
  protected function isEAN12($upccode){// também conhecido como UPC
    $odd_sum = $even_sum = 0;
    if(strlen($upccode) != 12) return FALSE;
    $chars = str_split($upccode);
    for($i=0;$i<11;$i++)
    {
        if($i%2==0){
          $odd_sum += $chars[$i] * 3;
        }else{
          $even_sum += $chars[$i] ;
        }
    }
    $total_sum = $even_sum + $odd_sum;

    $modulo10 = $total_sum % 10;
    $check_digit = 10 - $modulo10;
    return (int)$chars[11] === $check_digit;
  }


  protected function isEAN13($upccode){// também conhecido como EAN13 mesmo kkkk
    $odd_sum = $even_sum = 0;
    if(strlen($upccode) != 13) return FALSE;
    $chars = str_split($upccode);
    for($i=0;$i<12;$i++)
    {
        if($i%2==0){
          $odd_sum += $chars[$i];
        }else{
          $even_sum += $chars[$i] * 3;
        }
    }
    $total_sum = $even_sum + $odd_sum;

    $modulo10 = $total_sum % 10;
    $check_digit = 10 - $modulo10;
    return (int)$chars[12] === $check_digit;
  }  

}
