<?php
set_time_limit(1800);

class ModelUniversalFeedRssProduct extends Model {

  public function writeHeader($fh, $config) {
    $actual_link = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    
    fwrite($fh, '<?xml version="1.0"?>'.
                '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">'."\n".
                '<channel>'."\n".
                '<atom:link href="'.str_replace('&', '&amp;', $actual_link).'" rel="self" type="application/rss+xml" />'."\n".
                '<title>'.$this->config->get('config_name').'</title>'."\n".
                '<description>'.$this->config->get('config_meta_description').'</description>'."\n".
                '<link>'.$this->config->get('config_url').'</link>'."\n".
                '<pubDate>'.date('r').'</pubDate>'."\n".
                '<image><url>'.$this->model_tool_image->resize($this->config->get('config_image'), 100, 70).'</url><title>'.$this->config->get('config_name').'</title><link>'.$this->config->get('config_url').'</link><width>100</width><height>70</height></image>'."\n".
                "\n");
  }
  
  public function writeFooter($fh) {
    fwrite($fh, '</channel></rss>');
  }
  
  public function writeBody($fh, $config) {
    $config['sort'] = 'p.date_added';
    $config['order'] = 'DESC';
    $config['param_image_path'] = true;
    $config['filter_store'] = $this->config->get('config_store_id');
    
    $products = $this->model_universal_feed_driver_product->getItems($config);
    
    //$products = $this->model_tool_universal_feed->getProducts($config);

    $price_modifier = !empty($config['price_modifier']) ? $config['price_modifier'] : 1;
    $currency = !empty($config['currency']) ? $config['currency'] : 'USD';
    $gtin = !empty($config['gtin']) ? $config['gtin'] : '';

    $row = 0;
    $save_count = 0;
    
    foreach ($products as $item) {
      // fix issues of some special chars in descriptions
      //$item['description'] = preg_replace('~[^\P{Cc}\r\n]+~u', '', $item['description']);
      
      $this->session->data['ufeed_lastItem'] = $item['product_id'];
      
      if (empty($config['price_tax'])) {
        $price = $this->currency->format($this->tax->calculate(($item['special'] ? $item['special'] : $item['price']) * $price_modifier, $item['tax_class_id']), $currency, false, false);
      } else {
        $price = $this->currency->format(($item['special'] ? $item['special'] : $item['price']) * $price_modifier, $currency, false, false);
      }
      
      $desc = '';
      
      if ($item['image']) {
        $desc = '<div><img src="'.$this->model_tool_image->resize($item['image'], 200, 160).'" alt=""/></div>';
      }
      
      $desc .= $item['meta_description'];
      
      $line = array(
        'title' => $item['name'],
        'description' => $desc,
        'link' => $this->url->link('product/product', 'product_id='.$item['product_id']),
        'guid' => $this->url->link('product/product', 'product_id='.$item['product_id']),
        'pubDate' => date('r', strtotime($item['date_added'])),
      );
    
      $output = '<item>';
      
      foreach ($line as $k => $v) {
        if ($v) {
          $output .= '<'.$k.'><![CDATA['.html_entity_decode($v, ENT_QUOTES).']]></'.$k.'>'."\n";
        } else {
          $output .= '<'.$k.'/>'."\n";
        }
      }
      
      $output .= '</item>' . "\n";
      
      fwrite($fh, $output);
      
      $row++;
    }
    
    // return false when no more products
    return !empty($output);
  }
  
  public function getTotalItems($data = array()) {
    return $this->model_universal_feed_driver_product->getTotalItems($data);
  }
  
  private function getGoogleCategory($product_id) {
		$gcats = array();
		$categories = $this->db->query("SELECT c.google_merchant_id, cd.name FROM " . DB_PREFIX . "product_to_category p2c LEFT JOIN " . DB_PREFIX . "category c ON (p2c.category_id = c.category_id) LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) AND cd.language_id = " . $this->config->get('config_language_id') . " WHERE product_id = '" . (int)$product_id . "'")->rows;
		
		foreach($categories as $category) {
      if (!empty($category['google_merchant_id'])) {
        return array(
          'id' => $category['google_merchant_id'],
          'name' => $category['name'],
        );
      }
		}
	}
}