<?php
@set_time_limit(1800);

class ModelUniversalFeedN11 extends Model {

  public function __construct($registry) {
		parent::__construct($registry);
    $this->xml_tools = $this->model_tool_universal_feed;
  }

  public function writeHeader($fh, $config) {
    fwrite($fh, '<?xml version="1.0" encoding="UTF-8"?>'.
                $this->xml_tools->openXmlNode('Urunler', 0));
  }
  
  public function writeFooter($fh) {
    fwrite($fh, $this->xml_tools->closeXmlNode('Urunler', 0));
  }
  
  public function writeBody($fh, $config) {
    $config['attributeAsArray'] = true;
    $config['optionAsArray'] = true;
    $config['one_category'] = true;
    
    $config['filter_store'] = $this->config->get('config_store_id');
    // if (!empty($config['option_size']) || !empty($config['option_color'])) {
      // $config['option_row'] = 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;
    
    $depth = 1;
    
    foreach ($products as $item) {
      if ($this->config->get('univfeed_sleep')) {
        usleep((int) $this->config->get('univfeed_sleep') * 1000); // 1 000 000 = 1s
      }
      
      $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;
        } 
      }
      
      $discount_price = '';
      if (!empty($item['discount'])) {
        $discount_price = $this->currency->format($this->tax->calculate($item['discount'] * $price_modifier, $item['tax_class_id']), $currency, false, false);
      }
      
      $special_price = '';
      if (!empty($item['discount'])) {
        $special_price = $this->currency->format($this->tax->calculate($item['special'] * $price_modifier, $item['tax_class_id']), $currency, false, false);
      }
      
      $tax_rate = 0;
      $tax_rates = $this->cart->tax->getRates(0, $item['tax_class_id']);
      
      foreach ($tax_rates as $rate) {
        if ($rate['type'] == 'P') {
          $tax_rate = $rate['rate'];
        }
      }
      
      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);
      }
      
      $priceNoVat = $this->currency->format($price_value * $price_modifier, $currency, false, false);
      
      $taxQuery = $this->db->query("SELECT * FROM " . DB_PREFIX . "tax_class WHERE tax_class_id = '" . (int)$item['tax_class_id'] . "'")->row;
      $tax_class = isset($taxQuery['title']) ? $taxQuery['title'] : '';
      
      $item['category_shortest'] = '';
      $item['category_largest'] = '';
      
      $categories = explode('|', $item['product_category']);
      
      if (count($categories)) {
        usort($categories, array($this, 'sortBySubcatNumber'));
        $item['category_shortest'] = reset($categories);
        $item['category_largest'] = end($categories);
      }
      
     
    
   
    /* feed example:
    <Urun>
      <!--Zorunlu Alan-->
      <Kod>URUN-1</Kod>
      <!--Zorunlu Alan-->
      <Baslik>Ürünün başlığı</Baslik>
      <!--Zorunlu Alan-->
      <AltBaslik>Ürünün alt başlığı</AltBaslik>
      <!--Zorunlu Alan-->
      <Aciklama><![CDATA[<b>Açıklama</b>]]></Aciklama>
      <UrunOnayi>1</UrunOnayi>
      <!--Zorunlu Alan-->
      <HazirlamaSuresi>1</HazirlamaSuresi>
      <!--Zorunlu Alan-->
      <Kategori no="1002051" isim="Çocuk Giyim &amp; Aksesuar &gt; Erkek Çocuk &gt; Tişört">
        <Ozellikler>
          <!--Zorunlu Alan-->
          <Ozellik no="354079940" isim="Beden">1 Yaş</Ozellik>
          <Ozellik no="354079937" isim="Renk">Altın</Ozellik>
          <Ozellik no="354079936" isim="Marka">10 Is Shoes</Ozellik>
          <Ozellik no="354102994" isim="Desen / Figür">Balıksırtı</Ozellik>
          <Ozellik no="354079943" isim="Yaka">Bisiklet</Ozellik>
        </Ozellikler>
      </Kategori>
      <!--Zorunlu Alan-->
      <Fiyat>0</Fiyat>
      <UretimTarihi>03/04/2019</UretimTarihi>
      <SonTuketimTarihi>03/04/2020</SonTuketimTarihi>
      <SatisBaslangicTarihi>03/04/2019</SatisBaslangicTarihi>
      <SatisBitisTarihi>03/04/2020</SatisBitisTarihi>
      <Stoklar>
        <Stok>
          <!--Zorunlu Alan-->
          <Ozellik isim="Seçenek 1">Değer 1</Ozellik>
          <Ozellik isim="Seçenek 2">Değer 2</Ozellik>
          <Miktar>1</Miktar>
          <StokKodu/>
          <StokFiyati>0</StokFiyati>
          <Gtin>Gtin 1</Gtin>
          <Mpn>Mpn 1</Mpn>
          <Bundle>false</Bundle>
        </Stok>
      </Stoklar>
      <IndirimTuru>1</IndirimTuru>
      <IndirimTutari>10.00</IndirimTutari>
      <IndirimBaslangicTarihi>03/07/2019</IndirimBaslangicTarihi>
      <IndirimBitisTarihi>03/01/2020</IndirimBitisTarihi>
      <!--Zorunlu Alan-->
      <TeslimatSablonu>Teslimat Şablonu Adı</TeslimatSablonu>
      <!--Zorunlu Alan-->
      <Resimler>
        <Resim>https://n11scdn1.akamaized.net/a1/org/ornek-urun-1.jpg</Resim>
        <Resim>https://n11scdn2.akamaized.net/a1/org/ornek-urun-2.jpg</Resim>
      </Resimler>
      <ParaBirimi>TL</ParaBirimi>
    </Urun>
    */
    
      $line = array(
        'Kod' => $item['model'],
        'Baslik' => $item['name'],
        'AltBaslik' => !empty($item['meta_title']) ? $item['meta_title'] : '',
        'Aciklama' => $item['meta_description'] ? $item['meta_description'] : $item['description'],
        'UrunOnayi' => $item['status'],
        'StokAdedi' => $item['quantity'],
        'Marka' => $item['manufacturer'],
        'Renk' => isset($item['option_value']) ? $item['option_value'] : '',
        'Fiyat' => $priceNoVat,
        'KdvFiyat' => $price,
        'PiyasaFiyat' => $discount_price,
        'Maliyet' => $price,
        'KDV' => $tax_rate,
        'Barkod' => $item['ean'],
        'Kur' => $currency,
        'Kategori' => $item['category'],
        'KategoriTree' => $item['category_largest'],
        'UrunUrl' => $this->url->link('product/product', 'product_id=' . $item['product_id'] . (!empty($config['force_currency']) ? '&currency='.$currency : '')),
      );
      
      $output = $this->xml_tools->openXmlNode('Urun', $depth++);
      
      foreach ($line as $k => $v) {
        $output .= $this->xml_tools->getXmlNode($k, $v, $depth);
      }
      
      if (!empty($item['product_attribute'])) {
        $output .= $this->xml_tools->openXmlNode('TeknikDetaylar', $depth++);
        
        foreach ($item['product_attribute'] as $attr) {
            if (!empty($attr[$this->config->get('config_language_id')])) {
              $attributes = $attr[$this->config->get('config_language_id')];
              
              $output .= $this->xml_tools->openXmlNode('attribute', $depth++);
              
              if (isset($attributes['group'])) {
                $output .= $this->xml_tools->getXmlNode('group', $attributes['group'], $depth);
              }
              
              if (isset($attributes['attribute'])) {
                $output .= $this->xml_tools->getXmlNode('name', $attributes['attribute'], $depth);
              }
              
              if (isset($attributes['value'])) {
                $output .= $this->xml_tools->getXmlNode('value', $attributes['value'], $depth);
              }
              
              $output .= $this->xml_tools->closeXmlNode('attribute', --$depth);
            }
        }
        
        $output .= $this->xml_tools->closeXmlNode('TeknikDetaylar', --$depth);
      } else {
        $output .= $this->xml_tools->getXmlNode('TeknikDetaylar', '', $depth);
      }
      
      if (!empty($item['product_option'])) {
        $variant_count = 0;
        
        $output .= $this->xml_tools->openXmlNode('UrunSecenek', $depth++);
        foreach ($item['product_option'] as $option) {
          if (empty($config['price_tax'])) {
            $option_price = $this->currency->format($this->tax->calculate(($price_value + $option['price']) * $price_modifier, $item['tax_class_id']), $currency, false, false);
          } else {
            $option_price = $this->currency->format(($price_value + $option['price']) * $price_modifier, $currency, false, false);
          }
          
          $output .= $this->xml_tools->openXmlNode('Secenek', $depth++);
          $output .= $this->xml_tools->getXmlNode('VaryasyonID', $item['model'] . '-' . str_pad($variant_count+1, 2, '0', STR_PAD_LEFT), $depth);
          if (!empty($option['sku'])) {
            $output .= $this->xml_tools->getXmlNode('StokKodu', $option['sku'], $depth);
          }
          if (!empty($option['ean'])) {
            $output .= $this->xml_tools->getXmlNode('Barkod', $option['ean'], $depth);
          }
          $output .= $this->xml_tools->getXmlNode('AlisFiyati', $option_price, $depth);
          $output .= $this->xml_tools->getXmlNode('SatisFiyati', $option_price, $depth);
          $output .= $this->xml_tools->getXmlNode('IndirimliFiyat', $option_price, $depth);
          $output .= $this->xml_tools->getXmlNode('StokAdedi', $option['quantity'], $depth);
          $output .= $this->xml_tools->getXmlNode('ParaBirimi', $option['name'], $depth);
          $output .= $this->xml_tools->getXmlNode('Desi', $option['value'], $depth);
          if (!empty($option['image'])) {
            $output .= $this->xml_tools->openXmlNode('Resimler', $depth++);
            $output .= $this->xml_tools->getXmlNode('Resim', @$this->model_tool_image->resize($option['image'], 1000, 1000), $depth);
            $output .= $this->xml_tools->closeXmlNode('Resimler', --$depth);
          }
          $output .= $this->xml_tools->closeXmlNode('Secenek', --$depth);
        }
        $output .= $this->xml_tools->closeXmlNode('UrunSecenek', --$depth);
      } else {
        $output .= $this->xml_tools->getXmlNode('UrunSecenek', '', $depth);
      }
      
      //var_dump($item); die;
      $images = $this->model_tool_universal_feed->getProductImages($item['product_id']);
      
      if (!empty($images)) {
        $output .= $this->xml_tools->openXmlNode('Resimler', $depth++);
        
        foreach ($images as $i => $image) {
          $output .= $this->xml_tools->getXmlNode('Resim', @$this->model_tool_image->resize($image['image'], 1000, 1000), $depth);
          //if ($i >= 9) break; // limit is to 10 images
        }
        
        $output .= $this->xml_tools->closeXmlNode('Resimler', --$depth);
      } else {
        $output .= $this->xml_tools->getXmlNode('Resimler', '', $depth);
      }
      
      $output .= $this->xml_tools->closeXmlNode('Urun', --$depth);
      
      fwrite($fh, $output);
      
      $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 getCategory($product_id) {
		$gcats = array();
		$categories = $this->db->query("SELECT c.glami_ro_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['glami_ro_cat'])) {
        return array(
          'id' => $category['glami_ro_cat'],
          'name' => $category['name'],
        );
      }
		}
	}
  
  private function sortBySubcatNumber($a, $b) {
    if (substr_count($a, '>') == substr_count($b, '>')) {
        return 0;
    }
    return (substr_count($a, '>') < substr_count($a, '>')) ? -1 : 1;
  }
}