<?php


class DiyBotHandler {

  public function __construct() {

  }

  public function handleProduct($product, $shop) {

    // dont try to add products without external id or without title
    if(!isset($product->article_number) || !isset($product->title)) {
      return;
    }

    $result = db_select('diy_product', 'd')
      ->fields('d', array('external_id', 'updated'))
      ->condition('d.external_id', (string)$product->external_id, '=')
      ->condition('d.source', 'bot','=')
      ->condition('d.shop_nid', $shop->nid, '=')
      ->execute()
      ->fetchAssoc();

    if($result && isset($result['external_id'])) {
      // Check Change

      if(strtotime($product->updated) > $result['updated']) {
        // update Product
        $this->updateProduct($product, $shop->nid);

        // also check for price Items
        $this->updatePriceItems($product, $shop);
      } else {
        // product is up to date
      }

    } else {
      // insert new Product
      $this->insertProduct($product, $shop->nid);
    }

  }

  public function updatePriceItems($product, $shop) {
    // diy product row
    $products_db = db_select('diy_product', 'dp')
      ->fields('dp')
      ->condition('external_id', (string)$product->external_id, '=')
      ->condition('source', 'bot', '=')
      ->condition('shop_nid', $shop->nid, '=')
      ->execute()
      ->fetchAll(PDO::FETCH_ASSOC);
    
    if (count($products_db)) {
      $product_db = reset($products_db);

      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'product')
        ->fieldCondition('field_external_id', 'value', $product_db['external_id'], '=')
        ->fieldCondition('field_source', 'value', $product_db['source'], '=')
        ->fieldCondition('field_shop_id', 'value', $product_db['shop_nid'], '=')
        ->addMetaData('account', user_load(1));
      $result = $query->execute();

      if(isset($result['node'])) {
        $nids = array_keys($result['node']);

        foreach($nids as $nid) {

          $pp = new DiyProductPrice($nid);
          $pp->handleProductPriceItem($product_db);
        }
      }
    }

    //DiyProductPrice
  }

  public function updateProduct($product, $shop_nid) {
    $fields = $this->getProductFields($product, $shop_nid);

    $ProductId = db_update('diy_product')
      ->fields($fields)
      ->condition('external_id', (string)$product->external_id)
      ->condition('source', 'bot', '=')
      ->condition('shop_nid', $shop_nid, '=')
      ->execute();

    // additionally update drupal node, if one exists
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'product')
      ->fieldCondition('field_external_id', 'value', $fields['external_id'], '=')
      ->fieldCondition('field_source', 'value', $fields['source'], '=')
      ->fieldCondition('field_overwriten', 'value', 1, '!=')
      ->fieldCondition('field_last_change', 'value', $fields['updated'], '<')
      ->fieldCondition('field_shop_id', 'value', $shop_nid, '=')
      ->addMetaData('account', user_load(1));
    $result = $query->execute();

    if(isset($result['node'])) {
      $keys = array_keys($result['node']);
      foreach($keys as $nid) {
        $product_node = node_load($nid);

        $Product = new DiyProduct();
        $Product->data = $fields;
        $Product->updateProduct($product_node);
      }
    }
  }

  public function insertProduct($product, $shop_nid) {
    $fields = $this->getProductFields($product, $shop_nid);
    $fields['created'] = time();

    $ProductId = db_insert('diy_product')
      ->fields($fields)
      ->execute();
  }

  public function getProductFields($product, $shop_nid) {
    $fields = array(
      'external_id' => (string)$product->external_id,
      'article_number' => (string)$product->article_number,
      'description' => (string)$product->description,
      'title' => (string)$product->title,
      'deeplink' => (string)$product->deeplink . '?utm_source=diybook&utm_medium=pp&utm_campaign=ProductLink',
      'producer' => (string)$product->producer,
      'ean' => (string)$product->ean,
      'shop_nid' => (string)$shop_nid
    );

    $fields['source'] = 'bot';
    $fields['updated'] = strtotime($product->updated);

    if(isset($product->price)) {
      $fields['price'] = (string)$product->price;
    }

    if(isset($product->delivery_costs)) {
      $fields['delivery_costs'] = (string)$product->delivery_costs;
    }

    if(isset($product->image_url)) {
      $fields['image_url'] = (string)$product->image_url;
    }

    $fields['delivery_time'] = (string)$product->delivery_time;

    return $fields;
  }

  /*
  public function _transformDateTime($dateTime) {
    return date("Y-m-d H:m:s", strtotime($dateTime));
  }
  */

}