<?php
@set_time_limit(1800);

class ModelUniversalFeedEkatalog extends Model {

  public function __construct($registry) {
		parent::__construct($registry);
    $this->xml_tools = $this->model_tool_universal_feed;
  }
  
  public function writeHeader($fh, $config) {
    $output = '<?xml version="1.0" encoding="UTF-8"?>';
    $output .= $this->xml_tools->openXmlNode('yml_catalog', 0, array('date' => date('Y-m-d H:i')));
    
    $currency = !empty($config['currency']) ? $config['currency'] : 'USD';
    
    $output .= $this->xml_tools->openXmlNode('shop', 0);
    $output .= $this->xml_tools->getXmlNode('name', $this->config->get('config_name'), 1);
    $output .= $this->xml_tools->getXmlNode('url', $this->config->get('config_url'), 1);
    $output .= $this->xml_tools->openXmlNode('currencies', 1);
    $output .= $this->xml_tools->getXmlNode('currency', '', 2, array('id' => $currency, 'rate' => '1'));
    $output .= $this->xml_tools->closeXmlNode('currencies', 1);
    
    $categories = $this->db->query("SELECT * FROM " . DB_PREFIX . "category c LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) LEFT JOIN " . DB_PREFIX . "category_to_store c2s ON (c.category_id = c2s.category_id) WHERE cd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND c2s.store_id = '" . (int)$this->config->get('config_store_id') . "'  AND c.status = '1' ORDER BY c.sort_order, LCASE(cd.name)")->rows;
    
    $output .= $this->xml_tools->openXmlNode('catalog', 1);
    
    foreach ($categories as $cat) {
      $params = array('id' => $cat['category_id']);
      
      if ($cat['parent_id']) {
        $params['parentId'] = $cat['parent_id'];
      }
      
      $output .= $this->xml_tools->getXmlNode('category', $cat['name'], 2, $params);
    }
    
    $output .= $this->xml_tools->closeXmlNode('catalog', 1);
    
    $output .= $this->xml_tools->openXmlNode('items', 1);
    
    fwrite($fh, $output);
  }
  
  public function writeFooter($fh) {
    fwrite($fh, $this->xml_tools->closeXmlNode('items', 1) . 
                $this->xml_tools->closeXmlNode('shop', 0) . 
                $this->xml_tools->closeXmlNode('yml_catalog', 0));
  }
  
  public function writeBody($fh, $config) {
    $config['attributeAsArray'] = true;
    $config['optionAsArray'] = true;
    $config['one_category'] = true;
    
    $config['filter_store'] = $this->config->get('config_store_id');
    // if (!empty($config['option_size']) || !empty($config['option_color'])) {
      // $config['option_row'] = true;
    // }
    $products = $this->model_universal_feed_driver_product->getItems($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;
    
    $depth = 2;
    
    foreach ($products as $item) {
      if ($this->config->get('univfeed_sleep')) {
        usleep((int) $this->config->get('univfeed_sleep') * 1000); // 1 000 000 = 1s
      }
      
      $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;
        } 
      }
      
      $discount_price = '';
      if (!empty($item['discount'])) {
        $discount_price = $this->currency->format($this->tax->calculate($item['discount'] * $price_modifier, $item['tax_class_id']), $currency, false, false);
      }
      
      $special_price = '';
      if (!empty($item['discount'])) {
        $special_price = $this->currency->format($this->tax->calculate($item['special'] * $price_modifier, $item['tax_class_id']), $currency, false, false);
      }
      
      $tax_rate = 0;
      $tax_rates = $this->cart->tax->getRates(0, $item['tax_class_id']);
      
      foreach ($tax_rates as $rate) {
        if ($rate['type'] == 'P') {
          $tax_rate = $rate['rate'];
        }
      }
      
      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);
      }
      
      $priceNoVat = $this->currency->format($price_value * $price_modifier, $currency, false, false);
      
      $taxQuery = $this->db->query("SELECT * FROM " . DB_PREFIX . "tax_class WHERE tax_class_id = '" . (int)$item['tax_class_id'] . "'")->row;
      $tax_class = isset($taxQuery['title']) ? $taxQuery['title'] : '';
      
      $line = array(
        'name' => $item['name'],
        'url' => $this->url->link('product/product', 'product_id=' . $item['product_id']),
        'price' => $price,
        'categoryId' => $item['category_id'],
        'vendor' => $item['manufacturer'],
        'image' => $item['image'],
        'description' => $item['meta_description'] ? $item['meta_description'] : $this->model_tool_universal_feed->truncate($this->model_tool_universal_feed->sanitize($item['description']), 5000),
      );
      
      $output = $this->xml_tools->openXmlNode('item', $depth++, array('id' => $item['product_id']));
      
      foreach ($line as $k => $v) {
        $output .= $this->xml_tools->getXmlNode($k, $v, $depth);
      }
      
      /*
      if (!empty($item['product_attribute'])) {
        $output .= $this->xml_tools->openXmlNode('attributes', $depth++);
        
        foreach ($item['product_attribute'] as $attr) {
            if (!empty($attr[$this->config->get('config_language_id')])) {
              $attributes = $attr[$this->config->get('config_language_id')];
              
              $output .= $this->xml_tools->openXmlNode('attribute', $depth++);
              
              if (isset($attributes['group'])) {
                $output .= $this->xml_tools->getXmlNode('group', $attributes['group'], $depth);
              }
              
              if (isset($attributes['attribute'])) {
                $output .= $this->xml_tools->getXmlNode('name', $attributes['attribute'], $depth);
              }
              
              if (isset($attributes['value'])) {
                $output .= $this->xml_tools->getXmlNode('value', $attributes['value'], $depth);
              }
              
              $output .= $this->xml_tools->closeXmlNode('attribute', --$depth);
            }
        }
        
        $output .= $this->xml_tools->closeXmlNode('attributes', --$depth);
      } else {
        $output .= $this->xml_tools->getXmlNode('attributes', '', $depth);
      }
      
      if (!empty($item['product_option'])) {
        $variant_count = 0;
        
        $output .= $this->xml_tools->openXmlNode('options', $depth++);
        foreach ($item['product_option'] as $option) {
          if (empty($config['price_tax'])) {
            $option_price = $this->currency->format($this->tax->calculate(($price_value + $option['price']) * $price_modifier, $item['tax_class_id']), $currency, false, false);
          } else {
            $option_price = $this->currency->format(($price_value + $option['price']) * $price_modifier, $currency, false, false);
          }
          
          $output .= $this->xml_tools->openXmlNode('option', $depth++);
          $output .= $this->xml_tools->getXmlNode('code', $item['model'] . '-' . str_pad($variant_count+1, 2, '0', STR_PAD_LEFT), $depth);
          $output .= $this->xml_tools->getXmlNode('name', $option['name'], $depth);
          $output .= $this->xml_tools->getXmlNode('value', $option['value'], $depth);
          $output .= $this->xml_tools->getXmlNode('price', $option_price, $depth);
          if (!empty($option['image'])) {
            $output .= $this->xml_tools->getXmlNode('image', @$this->model_tool_image->resize($option['image'], 1000, 1000), $depth);
          }
          $output .= $this->xml_tools->closeXmlNode('option', --$depth);
        }
        $output .= $this->xml_tools->closeXmlNode('options', --$depth);
      } else {
        $output .= $this->xml_tools->getXmlNode('options', '', $depth);
      }
      
      $images = $this->model_tool_universal_feed->getProductImages($item['product_id']);
      
      foreach ($images as $i => $image) {
        $output .= $this->xml_tools->getXmlNode('additional_image_'.($i+1), @$this->model_tool_image->resize($image['image'], 1000, 1000), $depth);
        if ($i >= 9) break; // limit is to 10 images
      }
      */
      
      $output .= $this->xml_tools->closeXmlNode('item', --$depth);
      
      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.glami_ro_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['glami_ro_cat'])) {
        return array(
          'id' => $category['glami_ro_cat'],
          'name' => $category['name'],
        );
      }
		}
	}
}