<?php
set_time_limit(1800);

class ModelUniversalFeedKelkooCsv extends Model {

  public function writeHeader($fh, $config) {
    $config['limit'] = 1;
    //$this->writeBody($fh, $config, true);
  }
  
  public function writeFooter($fh) {}
  
  public function writeBody($fh, $config, $header = false) {
    $config['filter_store'] = $this->config->get('config_store_id');
    $config['one_category'] = 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;
    
    // if(!empty($products[0])) {
      // $this->write_csv($fh, array_keys($products[0]), ',');
    // }
    
    foreach ($products as $item) {
      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);
      }
      
      if ($item['special']) {
        if (empty($config['price_tax'])) {
          $regular_price = $this->currency->format($this->tax->calculate($item['price'] * $price_modifier, $item['tax_class_id']), $currency, false, false);
        } else {
          $regular_price = $this->currency->format($item['price'] * $price_modifier, $currency, false, false);
        }
      } else {
        $regular_price = '';
      }
      
      $additional_images = explode('|', $item['additional_images']);
       
      $line = array(
        'title' => $item['name'],
        'product-url' => $this->url->link('product/product', 'product_id='.$item['product_id']),
        'price' => $price,
        'brand' => $item['manufacturer'],
        'description' => strip_tags($item['description']),
        'image-url' => $item['image'],
        'ean' => $item['ean'],
        'merchant-category' => str_replace(array('-','>'), array(' ', '-'), $item['product_category']),
        'availability' => $item['quantity'] ? '1' : '0',
        'delivery-cost' => isset($config['shipping_cost']) ? $config['shipping_cost'] : '',
        'delivery-time' => isset($config['shipping_time']) ? $config['shipping_time'] : '',
        'condition' => '',
        'ecotax' => '',
        'warranty' => '',
        'mobile-url' => '',
        'kelkoo-category-id' => '',
        'mpn' => $item['mpn'],
        'sku' => $item['sku'],
        'colour' => '',
        'unit-price' => '',
        'offer-type' => '',
        'merchant-info' => '',
        'currency' => $currency,
        'image-url-2' => isset($additional_images[0]) ? $additional_images[0] : '',
        'image-url-3' => isset($additional_images[1]) ? $additional_images[1] : '',
        'image-url-4' => isset($additional_images[2]) ? $additional_images[2] : '',
        'green-product' => '',
        'green-label' => '',
        'sales-rank' => '',
        'unit-quantity' => '',
        'made-in' => '',
        'occasion' => '',
        'keywords' => '',
        'shipping-method' => '',
        'delivery-cost-2' => '',
        'shipping-method-2' => '',
        'delivery-cost-3' => '',
        'shipping-method-3' => '',
        'delivery-cost-4' => '',
        'shipping-method-4' => '',
        'zip-code' => '',
        'stock-quantity' => '',
        'shipping-weight' => '',
        'payment-methods' => '',
        'voucher-title' => '',
        'voucher-description' => '',
        'voucher-url' => '',
        'voucher-code' => '',
        'voucher-start-date' => '',
        'voucher-end-date' => '',
        'price-no-rebate' => $regular_price,
        'percentage-promo' => '',
        'promo-start-date' => '',
        'promo-end-date' => '',
        'user-rating' => '',
        'nb-reviews' => '',
        'user-review-link' => '',
        'video-link' => '',
        'video-title' => '',
      );
      
      if (!empty($header)) {
        $this->write_csv($fh, array_keys($line), ';');
        return;
      }
      
      $this->write_csv($fh, $line, ';');
      
      $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 write_csv($fh, array $fields, $delimiter = ',', $enclosure = '"', $mysql_null = false) {
    fputcsv($fh, array_map(array($this, 'escapeLineBreaks'), $fields), $delimiter, $enclosure);
    return;
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $output = array();
    foreach ($fields as $field) {
      if ($field === null && $mysql_null) {
        $output[] = 'NULL';
        continue;
      }

      $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? (
        $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure
      ) : $field;
    }

    fwrite($fh, join($delimiter, $output) . "\n");
  }
  
  private function escapeLineBreaks($v) {
    return html_entity_decode(str_replace(array("\r\n","\n"), '', $v), ENT_QUOTES);
    //return preg_replace("/\r*\n/", "\\n", $v);
  }
}