<?php
@set_time_limit(1800);

class ModelUniversalFeedTrovaprezziItCsv 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 ($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, false);
      } else {
        $price = $this->currency->format($price_value * $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 = '';
      }
      
      $line = array(
        'name' => $item['name'],
        'brand' => $item['manufacturer'],
        'description' => strip_tags($item['description']),
        'price' => $price,
        'model' => $item['model'],
        'link' => $this->url->link('product/product', 'product_id=' . $item['product_id'] . (!empty($config['force_currency']) ? '&currency='.$currency : '')),
        'in_stock' => $item['quantity'] ? 'DISPONIBILE' : 'N',
        'category' => $item['product_category'],
        'image' => $item['image'],
        'shipping' => number_format($item['weight'], 2),
        'model' => $item['sku'] ? $item['sku'] : $item['model'],
        'ean' => $item['ean'],
      );
      
      $additional_images = explode('|', $item['additional_images']);
      
      for ($i = 0; $i < 2; $i++) {
        $line['Image'.($i+1)] = isset($additional_images[$i]) ? $additional_images[$i] : '';
      }
      
      // add regular price
      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);
      }
      
      $line['regular_price'] = $regular_price;
      
      $line['<endrecord>'] = '<endrecord>';
      
      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;
      }
      
      $field = $this->escapeLineBreaks($field);
      $field = str_replace('"', ' ', strip_tags($field));
      
      $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc})/", $field) ? (
        $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure
      ) : $field;
    }

    fwrite($fh, join($delimiter, $output) . "\n");
  }
  
  private function write_csv_old($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);
  }
}