<?php
@set_time_limit(1800);

class ModelUniversalFeedSkroutz extends Model {

  public function writeHeader($fh, $config) {
    fwrite($fh, '<?xml version="1.0" encoding="UTF-8"?>'."\n".
                '<mywebstore>'."\n".
                '<created_at>'.date($this->language->get('datetime_format')).'</created_at>'."\n".'<products>');
  }
  
  public function writeFooter($fh) {
    fwrite($fh, '</products></mywebstore>');
  }
  
  public function writeBody($fh, $config) {
    $config['filter_store'] = $this->config->get('config_store_id');
    
    $products = $this->model_universal_feed_driver_product->getItems($config);

    //$products = $this->model_tool_universal_feed->getProducts($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;

    $this->load->model('localisation/order_status');
    $stockStatuses = array();
    
    foreach ($this->db->query("SELECT * FROM " . DB_PREFIX . "stock_status WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'")->rows as $stockStatus) {
      $stockStatuses[$stockStatus['stock_status_id']] = $stockStatus['name'];
    }
    
//checking of mpn filled
    $mpn_arr = array();

    foreach ($products as $p => $p_v) {
      if(empty($p_v['mpn'])){
        array_push($mpn_arr, $p_v['product_id'] . ' - ' . $p_v['name']);
      }
    }

    if(empty($mpn_arr)){
      foreach ($products as $item) {
      if ($this->config->get('univfeed_sleep')) {
        usleep((int) $this->config->get('univfeed_sleep') * 1000); // 1 000 000 = 1s
      }
      

/*
     UNCOMMENT OPTIONS AND SET TYPE AND NAME OF THE FIELD
*/
        /*$options = explode('|',$item['product_option']);
        $sizes = '';
        foreach ($options as $option) {
            $opt_data = explode(':',$option);
            if($opt_data[0] == 'radio' && $opt_data[1] == 'Διαθέσιμα Nούμερα'){
                $sizes .= $opt_data[2] . ',';
            }
        }
        $sizes = rtrim($sizes,',');*/
/* 
   uncomment this part to have mpn not empty
*/
        // if(empty($item['mpn'])){
        //     if(!empty($item['sku'])){
        //         $item['mpn'] = $item['sku'];
        //     } else if(!empty($item['model'])){
        //         $item['mpn'] = $item['model'];
        //     }
        // }
        // fix issues of some special chars in descriptions
        $item['description'] = preg_replace('~[^\P{Cc}\r\n]+~u', '', $item['description']);
        
        $this->session->data['ufeed_lastItem'] = $item['product_id'];
        
      // 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);
      }
        
        $output = '<product>'."\n";
        $output .= '<id>'.$item['product_id'].'</id>'."\n";
        $output .= '<name><![CDATA['.$item['name'].']]></name>'."\n";
        $output .= '<link><![CDATA['.$this->url->link('product/product','&product_id='.$item['product_id'], 'SSL').']]></link>'."\n";
        $output .= '<image><![CDATA['.$item['image'].']]></image>'."\n";
        if(!empty($item['additional_images'])){
            $add_img = array();
            $add_img = explode('|',$item['additional_images']);
            foreach ($add_img as $v) {
              $output .= '<additional_image><![CDATA['.$v.']]></additional_image>';
            }
        }
        $output .= '<category><![CDATA['.$item['product_category'].']]></category>'."\n";
        $output .= '<price>'.$price.'</price>'."\n";
        $output .= '<manufacturer><![CDATA['.$item['manufacturer'].']]></manufacturer>'."\n";
        $output .= '<mpn>'.$item['mpn'].'</mpn>'."\n";
        $output .= '<ean>'.$item['ean'].'</ean>'."\n";
        
/* UNCOMMENT IT TO INCLUDE OPTIONS */
        //$output .= '<size>'.$sizes.'</size>'."\n";
        

        $instock = ($item['quantity'] > 0)?'Y':'N';
        $output .= '<instock>'.$instock.'</instock>'."\n";
        $output .= '<availability>'.$stockStatuses[$item['stock_status_id']].'</availability>'."\n";
        $output .= '<weight>'.$item['weight'].'</weight>'."\n";
        $output .= '</product>'."\n";
        
        fwrite($fh, $output);
        
        $row++;
      }
    } else {
      echo "These products don't have MPN value:"."<br>";
      foreach ($mpn_arr as $value) {
        echo $value . "<br>";
      }
      die();
    }
    
    // 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 getGoogleCategory($product_id) {
        $gcats = array();
        $categories = $this->db->query("SELECT c.google_merchant_id, 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['google_merchant_id'])) {
        return array(
          'id' => $category['google_merchant_id'],
          'name' => $category['name'],
        );
      }
        }
    }
}