<?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) {
    $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 (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);
      }
      
      $line = array(
        'Name' => $item['name'],
        'Model' => $item['model'],
        'Link' => $this->url->link('product/product', 'product_id='.$item['product_id']),
        'Price' => $price,
        //'Currency' => $currency,
        'Category' => $item['product_category'],
        'Description' => $item['description'],
        'Tags' => $item['tag'],
        'Status' => $item['quantity'] ? 'in stock' : 'out of stock',
        '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), ',');
        return;
      }
      
      $this->write_csv($fh, $line, ',');
      
      // 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);
    //return preg_replace("/\r*\n/", "\\n", $v);
  }
}