<?php
@set_time_limit(1800);

class ModelUniversalFeedHeureka extends Model {

  public function writeHeader($fh, $config) {
    fwrite ($fh, '<?xml version="1.0" encoding="utf-8"?>'.
                '<SHOP>'."\n");
  }
  
  public function writeFooter($fh) {
    fwrite($fh, '</SHOP>');
  }
  
  public function writeBody($fh, $config) {
    $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) {
      if ($this->config->get('univfeed_sleep')) {
        usleep((int) $this->config->get('univfeed_sleep') * 1000); // 1 000 000 = 1s
      }
      
      // 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'];
      
      // which price to show?
      $price_order = !empty($config['price_order']) ? explode('_', $config['price_order']) : array('special', 'discount', 'price');
      
      foreach ($price_order as $p) {
        if ($item[$p]) {
          $price_value = $item[$p];
          break;
        } 
      }
      
      if (empty($config['price_tax'])) {
        $price = $this->currency->format($this->tax->calculate($price_value * $price_modifier, $item['tax_class_id']), $currency, false, false);
      } else {
        $price = $this->currency->format($price_value * $price_modifier, $currency, false, false);
      }
      
      $output = '<SHOPITEM>'."\n";
      
      $output .= '<ITEM_ID>'.$item['model'].'</ITEM_ID>'."\n";
      
      // Group identifier for variants
      $output .= '<ITEMGROUP_ID>'.$item['model'].'</ITEMGROUP_ID>'."\n";
      
      $output .= '<PRODUCTNAME><![CDATA['.html_entity_decode($item['name'], ENT_QUOTES, 'UTF-8').']]></PRODUCTNAME>'."\n";
      $output .= '<PRODUCT><![CDATA['.html_entity_decode($item['name'], ENT_QUOTES, 'UTF-8').']]></PRODUCT>'."\n";
      $output .= '<DESCRIPTION><![CDATA['.html_entity_decode($item['meta_description'], ENT_QUOTES, 'UTF-8').']]></DESCRIPTION>'."\n";
      $output .= '<URL><![CDATA['.$this->url->link('product/product', 'product_id='.$item['product_id'], 'SSL').']]></URL>'."\n";
      
      $output .= '<IMGURL><![CDATA['.$item['image'].']]></IMGURL>'."\n";
      if(!empty($item['additional_images'])){
        $addimages = explode('|',$item['additional_images']);
        foreach ($addimages as $ai_k => $ai_v) {
          $output .= '<IMGURL_ALTERNATIVE><![CDATA['.$ai_v.']]></IMGURL_ALTERNATIVE>'."\n";
        }
      }
      
      $output .= '<PRICE_VAT>'.$item['price'].'</PRICE_VAT>'."\n";
      
      // Max price per click for advertising the product - do not insert if none
      //$output .= '<HEUREKA_CPC>'.$item['price'].'</HEUREKA_CPC>'."\n";
      
      //$output .= '<VIDEO_URL></VIDEO_URL>'."\n";
      
      $output .= '<MANUFACTURER><![CDATA['.html_entity_decode($item['manufacturer'], ENT_QUOTES, 'UTF-8').']]></MANUFACTURER>'."\n";
      
      // get heureka category
      $category = $this->getCategory($item['product_id']);
      
      if (!empty($category['heureka_cat'])) {
        $output .= '<CATEGORYTEXT><![CDATA['.$category['heureka_cat'].']]></CATEGORYTEXT>'."\n";
      }
      
      if(!empty($item['ean'])){
        $output .= '<EAN>'.$item['ean'].'</EAN>'."\n";
      }

      foreach (explode('|', $item['product_attribute']) as $attr) {
        if (strpos($attr, ':') !== false) {
          list($attr_name, $attr_value) = explode(':', $attr);
          $output .= '<PARAM><PARAM_NAME><![CDATA['.html_entity_decode($attr_name, ENT_QUOTES, 'UTF-8').']]></PARAM_NAME><VAL><![CDATA['.html_entity_decode($attr_value, ENT_QUOTES, 'UTF-8').']]></VAL></PARAM>'."\n";
        }
      }
      
      /*
        <DELIVERY_DATE>2</DELIVERY_DATE>
        <DELIVERY>
          <DELIVERY_ID>SLOVENSKA_POSTA</DELIVERY_ID>
          <DELIVERY_PRICE>3</DELIVERY_PRICE>
          <DELIVERY_PRICE_COD>5</DELIVERY_PRICE_COD>
        </DELIVERY>
        <DELIVERY>
          <DELIVERY_ID>PPL</DELIVERY_ID>
          <DELIVERY_PRICE>3</DELIVERY_PRICE>
          <DELIVERY_PRICE_COD>5</DELIVERY_PRICE_COD>
        </DELIVERY>
        <ACCESSORY>CD456</ACCESSORY>
        <GIFT>Púzdro zadarmo</GIFT>
      */
      
      $output .= '</SHOPITEM>'."\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 getCategory($product_id) {
		$gcats = array();
		$categories = $this->db->query("SELECT c.heureka_cat, 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['heureka_cat'])) {
        return array(
          'heureka_cat' => $category['heureka_cat'],
          'name' => $category['name'],
        );
      }
		}
	}
}