<?php
@set_time_limit(1800);

class ModelUniversalFeedCeneo extends Model {

  public function writeHeader($fh, $config) {
    fwrite($fh, '<?xml version="1.0" encoding="UTF-8"?>'.
                '<offers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1">'."\n");
  }
  
  public function writeFooter($fh) {
    fwrite($fh, '</offers>');
  }
  
  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'];
      
      // 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);
      // }

      // 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;
        } 
      }
      
      $price = $this->tax->calculate($price_value * $price_modifier, $item['tax_class_id']);
      
      // $line = array(
      //   'Name' => $item['name'],
      //   'Model' => $item['model'],
      //   'Link' => $this->url->link('product/product', 'product_id=' . $product['product_id'] . (!empty($config['force_currency']) ? '&currency='.$currency : '')),
      //   'Price' => $price,
      //   'Category' => $item['product_category'],
      //   'Description' => $item['description'],
      //   'Tags' => $item['tag'],
      //   'Status' => $item['quantity'] ? 'in stock' : 'out of stock',
      //   'Quantity' => $item['quantity'],
      //   'Manufacturer' => $item['manufacturer'],
      //   'Meta_Description' => $item['meta_description'],
      //   'ISBN' => $item['isbn'],
      //   'UPC' => $item['upc'],
      //   'EAN' => $item['ean'],
      //   'JAN' => $item['jan'],
      //   'SKU' => $item['sku'],
      //   'Image' => $item['image'],
      //   'Weight' => $this->weight->format($item['weight'], $item['weight_class_id']),
      //   //'Images' => $item['additional_images'],
      //   //'Thumbnail' => $thumb,
      // );
      
      // if (!empty($config['thumbnail']) && !empty($item['image_path'])) {
      //   $line['Thumbnail'] = @$this->model_tool_image->resize($item['image_path'], 400, 400);
      // }
      $availability = $item['quantity'] ? '1' : '0';
      $output = '<o id="'.$item['product_id'].'" url="'.$this->url->link('product/product', 'product_id=' . $item['product_id'] . (!empty($config['force_currency']) ? '&currency='.$currency : '')).'" price="'.$price.'" avail="'.$availability.'" weight="'.$item['weight'].'" stock="'.$item['quantity'].'">';
      $output .= '<cat><![CDATA['.$item['product_category'].']]></cat>';
      $output .= '<name><![CDATA['.$item['name'].']]></name>';
      $output .= '<desc><![CDATA['.html_entity_decode($item['description'], ENT_QUOTES, 'UTF-8').']]></desc>';

      $output .= '<imgs>';
      $output .= '<main url="'.$item['image'].'" />';
      $add_images = array();
      $add_images = explode('|',$item['additional_images']);
      if(!empty($add_images)){
        foreach ($add_images as $a_i_k => $a_i_v) {
          $output .= '<i url="'.$a_i_v.'" />';
        }
      }
      $output .= '</imgs>';
      
      $output .= '<attrs>';

      $output .= '<a name="Producent"><![CDATA['.$item['manufacturer'].']]></a>';
      if(!empty($item['model'])){
        $output .= '<a name="Kod_producenta"><![CDATA['.$item['model'].']]></a>';
      }
      if(!empty($item['ean'])){
        $output .= '<a name="EAN"><![CDATA['.$item['ean'].']]></a>';
      }
      if(!empty($item['upc'])){
        $output .= '<a name="UPC"><![CDATA['.$item['upc'].']]></a>';
      }
      if(!empty($item['sku'])){
        $output .= '<a name="SKU"><![CDATA['.$item['sku'].']]></a>';
      }
      if(!empty($item['isbn'])){
        $output .= '<a name="ISBN"><![CDATA['.$item['isbn'].']]></a>';
      }
      if(!empty($item['mpn'])){
        $output .= '<a name="MPN"><![CDATA['.$item['mpn'].']]></a>';
      }
      foreach (explode('|', $item['product_attribute']) as $attr) {
        if (strpos($attr, ':') !== false) {
          list($attr_name, $attr_value) = explode(':', $attr);
          $output .= '<a name="'.html_entity_decode($attr_name, ENT_QUOTES, 'UTF-8').'"><![CDATA['.html_entity_decode($attr_value, ENT_QUOTES, 'UTF-8').']]></a>'."\n";
        }
      }
      $output .= '</attrs>';
      // foreach ($line as $k => $v) {
      //   if ($v) {
      //     $output .= '<'.$k.'><![CDATA['.html_entity_decode($v, ENT_QUOTES, 'UTF-8').']]></'.$k.'>'."\n";
      //   } else {
      //     $output .= '<'.$k.'/>'."\n";
      //   }
      // }
      

      

      
      $output .= '</o>' . "\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'],
        );
      }
		}
	}
}