<?php
@set_time_limit(1800);

class ModelUniversalFeedCommonFeedCsv 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) {
    $delimiter = ',';
    
    if ($config['format'] == 'tsv') {
      $delimiter = "\t";
    }
    
    $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;
    
    // if(!empty($products[0])) {
      // $this->write_csv($fh, array_keys($products[0]), ',');
    // }
    
    foreach ($products as $item) {
      if ($this->config->get('univfeed_sleep')) {
        usleep((int) $this->config->get('univfeed_sleep') * 1000); // 1 000 000 = 1s
      }
      
      // 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;
        } 
      }
      
      if (empty($config['price_tax'])) {
        $price = $this->currency->format($this->tax->calculate($price_value * $price_modifier, $item['tax_class_id']), $currency, false, !empty($config['price_format']));
      } else {
        $price = $this->currency->format($price_value * $price_modifier, $currency, false, !empty($config['price_format']));
      }
      
      if (empty($config['price_format'])) {
        $price = number_format($price, 2);
      }

      $line = array(
        'Name' => $item['name'],
        'Model' => $item['model'],
        'Link' => $this->url->link('product/product', 'product_id=' . $item['product_id'] . (!empty($config['force_currency']) ? '&currency='.$currency : '')),
        'Price' => $price,
        //'Currency' => $currency,
        'Category' => $item['product_category'],
        'Description' => $item['description'],
        'Tags' => $item['tag'],
        'Status' => $item['stock_status'],
        '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);
      }
      
      //if (in_array($config['feed_type'], array())) {}
      
      $additional_images = explode('|', $item['additional_images']);
      
      for ($i = 0; $i < 10; $i++) {
        $line['Image'.($i+1)] = isset($additional_images[$i]) ? $additional_images[$i] : '';
      }
      
      if (!empty($header)) {
        $this->write_csv($fh, array_keys($line), $delimiter);
        return;
      }
      
      $this->write_csv($fh, $line, $delimiter);
      
      // unset($item['image_path'], $item['import_batch'], $item['manufacturer_id'], $item['stock_status_id'], $item['shipping'], $item['tax_class_id'],
        // $item['length_class_id'], $item['status'], $item['points'], $item['subtract'], $item['viewed'], $item['sort_order'], $item['meta_robots'], $item['public_download'], $item['language_id'],
        // $item['product_filter']);
      
      // $this->write_csv($fh, $item, ',');
      
      $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, 'UTF-8');
    //return preg_replace("/\r*\n/", "\\n", $v);
  }
}