<?php
@set_time_limit(1800);

class ModelUniversalFeedAkakce extends Model {

  public function writeHeader($fh, $config) {
    fwrite($fh, '<?xml version="1.0" encoding="UTF-8"?>'."\n".
                '<products>'."\n");
  }
  
  public function writeFooter($fh) {
    fwrite($fh, '</products>');
  }
  
  public function writeBody($fh, $config) {
    $config['attributeAsArray'] = true;
    $config['optionAsArray'] = true;
    $config['one_category'] = true;
    $config['option_row'] = 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);
    // echo '<pre>';
    // var_dump($products); die;
    
    //$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
      }
      
      $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);
      }
      
      $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);
      
      $line = array(
        'sku' => $item['sku'] ? $item['sku'] : $item['product_id'],
        'name' => $item['name'],
        'url' => $this->url->link('product/product', 'product_id=' . $item['product_id'] . (!empty($config['force_currency']) ? '&currency='.$currency : '')),
        'image' => $item['image'],
        'additionalimages' => '{additional_images}',
        'description' => $item['meta_description'],
        'distributor' => '',
        'price' => $price,
        'shipPrice' => isset($config['shipping_cost']) ? $config['shipping_cost'] : '',
        'shipmentVolume' => '',
        'dayOfDelivery' => isset($config['shipping_time']) ? $config['shipping_time'] : '',
        'expressDeliveryTime' => '',
        'quantity' => $item['quantity'],
        'productBrand' => $item['manufacturer'],
        'productCategory' => $item['product_category'],
        'barcode' => $item['ean'],
      );
      
      //$images = $this->model_tool_universal_feed->getProductImages($item['product_id']);
      $additional_images = '';
      
      if ($item['additional_images']) {
        $additional_images .= "\n";
        $images = explode('|', $item['additional_images']);
        
        foreach ($images as $i => $v) {
          if (strpos($v, '<') !== false || strpos($v, '&') !== false) {
            $additional_images .= "\t\t\t".'<imgUrl><![CDATA['.html_entity_decode($v, ENT_QUOTES, 'UTF-8').']]></imgUrl>'."\n";
          } else if ($v) {
            $additional_images .= "\t\t\t".'<imgUrl>'.html_entity_decode($v, ENT_QUOTES, 'UTF-8').'</imgUrl>'."\n";
          }
        }
        
        $additional_images .= "\t\t";
      }
      
      $output = "\t".'<product>'."\n";
      
      foreach ($line as $k => $v) {
        if (strpos($v, '<') !== false || strpos($v, '&') !== false) {
          $output .= "\t\t".'<'.$k.'><![CDATA['.html_entity_decode($v, ENT_QUOTES, 'UTF-8').']]></'.$k.'>'."\n";
        } else if ($v !== '') {
          $output .= "\t\t".'<'.$k.'>'.html_entity_decode($v, ENT_QUOTES, 'UTF-8').'</'.$k.'>'."\n";
        } else {
          $output .= "\t\t".'<'.$k.'/>'."\n";
        }
      }
      
      $output = str_replace('{additional_images}', $additional_images, $output);
      
      $output .= "\t".'</product>' . "\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.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'],
        );
      }
		}
	}
}