<?php
set_time_limit(1800);

class ModelUniversalFeedBingCsv 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 = '';
      }
      
      $line = array(
        'MPID' => $item['model'],
        'Title' => $item['name'],
        'BrandorManufacturer' => $item['manufacturer'],
        'MPN' => $item['mpn'],
        'UPC' => $item['upc'],
        'ISBN' => $item['isbn'],
        'MerchantSKU' => $item['sku'],
        'ProductURL' => $this->url->link('product/product', 'product_id='.$item['product_id']),
        'Price' => $price,
        'availability' => $item['quantity'] ? 'In stock' : 'Out of stock',
        'Description' => strip_tags($item['description']),
        'ImageURL' => $item['image'],
        'Shipping' => isset($config['shipping_cost']) ? $config['shipping_cost'] : '',
        'MerchantCategory' => $item['product_category'],
        'BingCategory' => $item['product_category'],
        'ShippingWeight' => '',
        'Condition' => 'NEW',
      );
      
      if (!empty($header)) {
        $this->write_csv($fh, array_keys($line), "\t");
        return;
      }
      
      $this->write_csv($fh, $line, "\t");
      
      $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);
  }
}