<?php
class ModelUniversalFeedGoogleMerchantCsv extends Model {

  public function writeHeader($fh, $config) {
    $data = array(
      'id',
      'title',
      'description',
      'link',
      'image',
      'condition',
      'availability',
      'price',
      'gtin',
      'brand',
      'mpn',
      'identifier_exists',
      'google_product_category',
      'product_type',
      'additional_image_link',
    );
    
    $this->model_tool_universal_feed->write_csv($fh, $data, ';');
  }
  
  public function writeFooter($fh) {}
  
  public function writeBody($fh, $config) {
    $config['filter_store'] = $this->config->get('config_store_id');

    $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;

    foreach ($products as $product) {
      $this->session->data['ufeed_lastItem'] = $product['product_id'];

      $output = array();
      $output[] = $product['model'];
      $output[] = $product['name'];
      $output[] = $this->model_tool_universal_feed->truncate($this->model_tool_universal_feed->sanitize($product['description']), 5000);
      $output[] = $this->url->link('product/product', 'product_id=' . $product['product_id']);
      
      if ($product['image']) {
        $output[] = $this->model_tool_image->resize($product['image'], 250, 250);
      } else {
        $output[] = '';
      }
      
      $output[] = 'new';
      $output[] = $product['quantity'] ? 'in stock' : 'out of stock';
      
      if (empty($config['price_tax'])) {
        $price = $this->currency->format($this->tax->calculate(($product['special'] ? $product['special'] : $product['price']) * $price_modifier, $product['tax_class_id']), $currency, false, false);
      } else {
        $price = $this->currency->format(($product['special'] ? $product['special'] : $product['price']) * $price_modifier, $currency, false, false);
      }
      
      $output[] = $price . ' ' . $currency;
      
      $has_identifier = 0;
      
			//<!-- 2 of the following 3 attributes are required fot this item according to the Unique Product Identifier Rules -->
      if (!empty($product[$gtin])) {
        $has_identifier++;
        $output[] = $product[$gtin];
      } else {
        $output[] = '';
      }

      if ($product['manufacturer']) {
        $has_identifier++;
        $output[] = $product['manufacturer'];
      } else {
        $output[] = '';
      }
      
      if ($product['mpn']) {
        $has_identifier++;
        $output[] = $product['mpn'];
      } else {
        $output[] = '';
      }
			
      if ($has_identifier < 2) {
        $output[] = 'FALSE';
      } else {
        $output[] = 'TRUE';
      }
      
      $category = $this->getGoogleCategory($product['product_id']);
      
      if (!empty($category['id'])) {
        $output[] = $category['id'];
      } else {
        $output[] = '';
      }
      
      if (!empty($config['store_category']) && !empty($category['name'])) {
        $output[] = $category['name'];
      } else {
        $output[] = '';
      }

      $images = $this->model_tool_universal_feed->getProductImages($product['product_id']);
      
      $img_array = array();
      foreach ($images as $image) {
        $img_array[] = $this->model_tool_image->resize($image['image'], 250, 250);
      }
      
      $output[] = implode(';', $img_array);
      
      
      $this->model_tool_universal_feed->write_csv($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'],
        );
      }
		}
	}
}