<?php
class ModelUniversalFeedShareasaleCsv 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]), ',');
    // }
    
    if (empty($config['merchant'])) {
      die('Error: You must define your Merchant ID.');
    }
    
    foreach ($products as $item) {
        $this->load->model('tool/image');
        
        $categories = explode('|', $item['product_category']);
        
        $main_category = '';
        $sub_category = '';
        
        if (isset($categories[0])) {
          $main_category = $categories[0];
        }
        
        if (isset($categories[1])) {
          $sub_category = $categories[1];
        }
        
        if ($item['image']) {
          $thumb = $this->model_tool_image->resize($item['image_path'], 400, 400);
        } else {
          $thumb = '';
        }
        
        $category = $this->getFeedCategory($item['product_id']);
      
        if (!empty($category['id'])) {
          list($feed_cat, $feed_subcat) = explode('|', $category['id']);
        } else {
          //die('Error: All items must have a defined shareasale category. Make sure to configure all category bindings in module options. Binding not found for:'.$item['product_category']);
          die('Error: All items must have a defined shareasale category. Make sure to configure all category bindings in module options. Binding not found for product with product id: '.$item['product_id'].' or this product is not related to any category.');
        }
        
        if (empty($item['sku'])) {
          die('Error: All items must have an SKU. Product without SKU: '.$item['name']);
        }
        
        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(
          'SKU' => $item['sku'], // mandatory
          'Name' => $item['name'],
          'URL to product' => $this->url->link('product/product', 'product_id='.$item['product_id']), // mandatory
          'Price' => $price, // mandatory
          'Retail Price' => $item['special'] ? $item['price'] : '',
          'URL to image' => $item['image'],
          'URL to thumbnail image' => $thumb,
          'Commission' => '',
          'Category' => $feed_cat, // mandatory
          'SubCategory' => $feed_subcat, // mandatory
          'Description' => $item['description'],
          'SearchTerms' => $item['tag'],
          'Status' => $item['quantity'] ? 'instock' : 'sold out', //instock, backorder, cancelled, sold out
          'Your MerchantID' => $config['merchant'], // mandatory
          'Custom 1' => '',
          'Custom 2' => '',
          'Custom 3' => '',
          'Custom 4' => '',
          'Custom 5' => '',
          'Manufacturer' => $item['manufacturer'],
          'PartNumber' => '',
          'MerchantCategory' => $main_category,
          'MerchantSubcategory' => $sub_category,
          'ShortDescription' => $item['meta_description'],
          'ISBN' => $item['isbn'],
          'UPC' => $item['upc'],
          'CrossSell' => '',
          'MerchantGroup' => '',
          'MerchantSubgroup' => '',
          'CompatibleWith' => '',
          'CompareTo' => '',
          'QuantityDiscount' => '',
          'Bestseller' => '',
          'AddToCartURL' => '',
          'ReviewsRSSURL' => '',
          'Option1' => '',
          'Option2' => '',
          'Option3' => '',
          'Option4' => '',
          'Option5' => '',
          'customCommissions' => '',
          'customCommissionIsFlatRate' => '',
          'customCommissionNewCustomerMultiplier' => '',
          'mobileURL' => '',
          'mobileImage' => '',
          'mobileThumbnail' => '',
          'ReservedForFutureUse' => '',
          'ReservedForFutureUse' => '',
          'ReservedForFutureUse' => '',
          'ReservedForFutureUse' => '',
        );
      
      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);
  }
  
  private function getFeedCategory($product_id) {
		$gcats = array();
		$categories = $this->db->query("SELECT c.shareasale_cat, cd.name FROM " . DB_PREFIX . "product_to_category p2c LEFT JOIN " . DB_PREFIX . "category c ON (p2c.category_id = c.category_id) LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) AND cd.language_id = " . $this->config->get('config_language_id') . " WHERE product_id = '" . (int)$product_id . "'")->rows;
		
		foreach($categories as $category) {
      if (!empty($category['shareasale_cat'])) {
        return array(
          'id' => $category['shareasale_cat'],
          'name' => $category['name'],
        );
      }
		}
	}
}