<?php

/**
 * Page callback: Diy product settings
 */
function diy_product_settings_form($form, &$form_state) {

  $form['diy_product_info'] = array(
    '#type' => 'fieldset',
    '#title' => t('Global (<a href="@view-link">Product View</a>, <a href="@view-link-price">Price View</a>)', array(
      '@view-link' => url('admin/external-products'),
      '@view-link-price' => url('admin/product-prices')
    )),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );

  $form['diy_product_info']['cron_info'] = array(
    '#markup' => '<div style="margin-bottom: 1em;">' . t('Last product price update run at @time', array('@time' => date('Y-m-d H:i:s', variable_get('diy_product_last_price_update', 0)))) . '</div>'
  );

  $form['diy_product_info']['diy_product_sync_logging'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable logging'),
    '#default_value' => variable_get('diy_product_sync_logging', false),
    '#required' => FALSE,
  );

  $form['diy_product_info']['diy_product_update_prices'] = array(
    '#type' => 'checkbox',
    '#title' => t('Update price items'),
    '#description' => t('Remove check for updated price items on next price-item update run (= update all price items). This checkbox will be automatically reset after one run.'),
    '#default_value' => variable_get('diy_product_update_prices', false),
    '#required' => FALSE,
  );

  $form['diy_product_bot'] = array(
    '#type' => 'fieldset',
    '#title' => t('Bot'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  /*
  $form['diy_product_bot']['diy_product_bot_enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable product data sync by cron'),
    '#default_value' => variable_get('diy_product_bot_enabled', true),
    '#required' => FALSE,
  );
  */

  $form['diy_product_bot']['diy_product_bot_trigger_job_sync'] = array(
    '#type' => 'submit',
    '#value' => t('BOT: Sync now'),
    '#submit' => array('diy_product_bot_trigger_product_sync_settings')
  );

  $form['diy_product_affilinet'] = array(
    '#type' => 'fieldset',
    '#title' => t('Affilinet'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  /*
  $form['diy_product_affilinet']['diy_product_affilinet_enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable product data sync by cron'),
    '#default_value' => variable_get('diy_product_affilinet_enabled', true),
    '#required' => FALSE,
  );
  */

  $form['diy_product_affilinet']['trigger_job_sync'] = array(
    '#type' => 'submit',
    '#value' => t('AFFILINET: Sync now'),
    '#submit' => array('diy_product_affilinet_trigger_product_sync_settings')
  );

  $form['diy_product_affilinet']['empty_cs'] = array(
    '#type' => 'item',
    '#title' => t('Empty categories within shops (shopid:categoryid)'),
    '#markup' => diy_product_print_empty_cs(),
    '#description' => t('Reset with hitting "Trigger product sync". Is set, when total-pages >= 1 and no products are provided from soap interface.')
  );

  $form['diy_product_dev'] = array(
    '#type' => 'fieldset',
    '#title' => t('DEV'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );

  $form['diy_product_dev']['dev_trigger'] = array(
    '#type' => 'submit',
    '#value' => 'Dev trigger',
    '#description' => t('Do not hit on live'),
    '#submit' => array('diy_product_dev_trigger')
  );

  return system_settings_form($form);
}

/**
 * Helper function, printing empty category and shop pairs from variable
 */
function diy_product_print_empty_cs() {
  $pairs_string = variable_get('diy_affilinet_empty_cs', '');
  $pairs_split = explode(';', $pairs_string);

  return implode('<br />', $pairs_split);
}

/**
 * Action button callback, settings form
 */
function diy_product_bot_trigger_product_sync_settings($form, &$form_state) {
  if($shop_count = diy_product_bot_trigger_sync()) {
    $msg = t('Product BOT: Triggered sync jobs for cron runs. %d shops total.', array('%d' => $shop_count));

    diy_product_log($msg);
    drupal_set_message($msg);
  }
}

/**
 * Action button callback, settings form
 */
function diy_product_affilinet_trigger_product_sync_settings($form, &$form_state) {

  if($shop_count = diy_product_affilinet_trigger_sync()) {
    $msg = t('Product AFFILINET: Triggered sync jobs for cron runs. %d shops total.', array('%d' => $shop_count));

    // clear variable store
    variable_del('diy_affilinet_empty_cs');

    diy_product_log($msg);
    drupal_set_message($msg);
  }
}

/**
 * Dev trigger
 */
function diy_product_dev_trigger() {
/*
  $products_db = db_select('diy_product', 'dp')
    ->fields('dp')
    ->condition('external_id', '16502', '=')
    ->condition('source', 'bot', '=')
    ->condition('shop_nid', '2737', '=')
    ->execute()
    ->fetchAll(PDO::FETCH_ASSOC);


  $product_db = reset($products_db);

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'product')
    ->fieldCondition('field_external_id', 'value', '16502', '=')
    ->fieldCondition('field_source', 'value', 'bot', '=')
    ->fieldCondition('field_shop_id', 'value', '2737', '=')
    ->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);
    }
  }*/


  /*
  $result= db_query("SELECT nid FROM {node} AS n WHERE n.type = 'product'");
  foreach ($result as $record) {
    node_delete($record->nid);
  }
  */

  /*
  if($shops = diy_product_bot_get_shops()) {
    $shop = reset($shops);

    if($field_bot_xml_link = field_get_items('node', $shop, 'field_bot_xml_link')) {
      $url = $field_bot_xml_link[0]['url'];
      $xml = simplexml_load_file($url);

      // there are items in here
      if(count($xml)) {

        $items = array();
        foreach($xml as $item) {
          array_push($items, $item->asXML());
        }

        $products = $items;
        // maybe there are huge xml files, so lets chunk it arrays of 100 items each
        #if($products = array_chunk($items, 1)) {

          $bot = new DiyBotHandler();

          if(is_array($products)) {

            $products = array_slice($products, 0, 50);
//dpm($products);

            foreach($products as $product) {
              $product = simplexml_load_string($product);
              $bot->handleProduct($product, $shop);
            }

          }
        #}
      }
    }
  }*/

  /*
  $data = array(
    'product' => node_load(1411)
  );

  diy_product_price_check_action($data);
  */

}