<?php
/**
 * @file
 * Spider Video Player module tags.
 */

/**
 * Menu loader callback. Load tags.
 */
function spider_video_player_tags() {
  global $user;
  $form = array();
  $free_version = '
    <a href="http://web-dorado.com/files/fromSVPDrupal.php" target="_blank" style="color:red; text-decoration:none; float:right;">
      <img src="' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/header.png" border="0" alt="www.web-dorado.com" width="215"><br />
    <div style="float:right;">' . t('Get the full version') . '&nbsp;&nbsp;&nbsp;&nbsp;</div>
    </a>';
  $form['fieldset_tag_buttons'] = array(
    '#prefix' => $free_version,
    '#type' => 'fieldset',
  );
  $form['fieldset_tag_buttons']['publish_tag'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_tags_publish'),
    '#value' => t('Publish'),
  );
  $form['fieldset_tag_buttons']['unpublish_tag'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_tags_unpublish'),
    '#value' => t('Unpublish'),
  );
  $form['fieldset_tag_buttons']['required_tag'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_tags_set_required'),
    '#value' => t('Set required'),
  );
  $form['fieldset_tag_buttons']['not_required_tag'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_tags_set_not_required'),
    '#value' => t('Set not required'),
  );
  $form['fieldset_tag_buttons']['delete_tag'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_tags_delete'),
    '#value' => t('Delete'),
    '#attributes' => array('onclick' => 'if (!confirm(Drupal.t("Do you want to delete selected tags?"))) {return false;}'),
  );
  $form['fieldset_tag_buttons']['save_order'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_save_ordering'),
    '#value' => t('Save order'),
  );
  $form['fieldset_tag_buttons']['new_tag'] = array(
    '#prefix' => l(t('New'), url('admin/settings/spider_video_player/tags/edit', array('absolute' => TRUE))),
  );
  $form['fieldset_search_tags_name'] = array(
    '#type' => 'fieldset',
    '#title' => t('Search tags by name'),
    '#collapsible' => TRUE,
    '#collapsed' => ((variable_get('spider_video_player_search_tags_name', '') == '') ? TRUE : FALSE),
  );
  $form['fieldset_search_tags_name']['search_tags_name'] = array(
    '#type' => 'textfield',
    '#size' => 25,
    '#default_value' => variable_get('spider_video_player_search_tags_name', ''),
  );
  $form['fieldset_search_tags_name']['search_tags'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_search_tags_name'),
    '#value' => t('Go'),
  );
  $form['fieldset_search_tags_name']['reset_tags'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('spider_video_player_reset_tags_name'),
  );
  drupal_add_tabledrag('tags_table-components', 'order', 'sibling', 'weight');
  $header = array(
    'checkbox' => array('class' => 'select-all'),
    'id' => array('data' => t('ID'), 'field' => 'n.id'),
    'name' => array('data' => t('Name'), 'field' => 'n.name', 'style' => 'width:400px;'),
    'order' => array('data' => t('Order'), 'field' => 'n.ordering', 'sort' => 'asc'),
    'required' => array('data' => t('Required'), 'field' => 'n.required'),
    'published' => array('data' => t('Published'), 'field' => 'n.published'),
    'delete' => array('data' => t('Delete')),
  );
  $options = array();
  $query = db_select('spider_video_player_tag', 'n')
    ->fields('n', array('id'))
    ->condition('n.name', '%' . db_like(variable_get('spider_video_player_search_tags_name', '')) . '%', 'LIKE')
    ->extend('TableSort')
    ->orderByHeader($header)
    ->extend('PagerDefault')
    ->limit(20);
  // Allow users edit only own tags.
  if (($user->uid != 1) && (user_access('access Spider Video Player user tags administration'))) {
    $query = $query
      ->condition(
        db_or()
        ->condition('n.uid', $user->uid, '=')
        ->condition('n.uid', 1, '=')
      );
  }
  $tags_ids = $query->execute()->fetchCol();
  foreach ($tags_ids as $tag_id) {
    $row = db_query("SELECT * FROM {spider_video_player_tag} WHERE id=:id", array(':id' => $tag_id))->fetchObject();
    if ($row->published) {
      $publish_unpublish_png = 'publish.png';
      $publish_unpublish_function = 'unpublish';
    }
    else {
      $publish_unpublish_png = 'unpublish.png';
      $publish_unpublish_function = 'publish';
    }
    if ($row->required) {
      $required = '<p style="color:#268055">' . t('Required') . '</p>';
      $required_function = 'not_required';
    }
    else {
      $required = '<p style="color:#FF0000">' . t('Not Required') . '</p>';
      $required_function = 'required';
    }
    $options[$tag_id] = array(
      'checkbox' => array(
        'data' => array(
          '#type' => 'checkbox',
          '#attributes' => array('name' => 'checkbox' . $tag_id),
        ),
      ),
      'id' => $tag_id,
      'name' => array(
        'data' => array(
          '#type' => 'link',
          '#title' => $row->name,
          '#href' => url('admin/settings/spider_video_player/tags/edit', array('query' => array('tag_id' => $tag_id), 'absolute' => TRUE)),
        ),
      ),
      'order' => array(
        'data' => array(
          '#type' => 'textfield',
          '#size' => 3,
          '#value' => $row->ordering,
          '#attributes' => array('name' => 'spider_video_player_tags_order_' . $tag_id, 'class' => array('weight')),
        ),
      ),
      'required' => l($required, url('admin/settings/spider_video_player/tags/' . $required_function, array('query' => array('tag_id' => $tag_id), 'absolute' => TRUE)), array('html' => TRUE)),
      'published' => l(t('<img src="' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/' . $publish_unpublish_png . '" />'), url('admin/settings/spider_video_player/tags/' . $publish_unpublish_function, array('query' => array('tag_id' => $tag_id), 'absolute' => TRUE)), array('html' => TRUE)),
      'delete' => array(
        'data' => array(
          '#type' => 'link',
          '#title' => t('Delete'),
          '#href' => url('admin/settings/spider_video_player/tags/delete', array('query' => array('tag_id' => $tag_id), 'absolute' => TRUE)),
        ),
      ),
    );
    $options[$tag_id]['#attributes'] = array('class' => array('draggable'));
  }
  $form['tags_table'] = array(
    '#type' => 'tableselect',
    '#js_select' => TRUE,
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No tags available.'),
    '#suffix' => theme('pager', array('tags' => array())),
    '#attributes' => array('id' => 'tags_table-components'),
  );
  foreach ($tags_ids as $tag_id) {
    $form['tags_table'][$tag_id]['#disabled'] = TRUE;
  }
  return $form;
}

/**
 * Search in tags.
 */
function spider_video_player_search_tags_name($form, &$form_state) {
  if ($form_state['values']['search_tags_name'] != '') {
    variable_set('spider_video_player_search_tags_name', $form_state['values']['search_tags_name']);
  }
  else {
    variable_set('spider_video_player_search_tags_name', '');
  }
}

/**
 * Reset tags.
 */
function spider_video_player_reset_tags_name($form, &$form_state) {
  variable_set('spider_video_player_search_tags_name', '');
}

/**
 * Publish selected tags.
 */
function spider_video_player_tags_publish($form, &$form_state) {
  if (db_query("SELECT id FROM {spider_video_player_tag}")) {
    $tag_ids_col = db_query("SELECT id FROM {spider_video_player_tag}")->fetchCol();
    $flag = FALSE;
    foreach ($tag_ids_col as $tag_id) {
      if (isset($_POST['checkbox' . $tag_id])) {
        $flag = TRUE;
        db_query("UPDATE {spider_video_player_tag} SET published=:published WHERE id=:id", array(':published' => 1, ':id' => $tag_id));
      }
    }
    if ($flag == FALSE) {
      drupal_set_message(t('You must select at least one tag.'), 'warning', FALSE);
    }
    else {
      drupal_set_message(t('Tags successfully published.'), 'status', FALSE);
    }
  }
}

/**
 * Publish tag.
 */
function spider_video_player_tag_publish() {
  if (isset($_GET['tag_id'])) {
    $tag_id = check_plain($_GET['tag_id']);
    db_query("UPDATE {spider_video_player_tag} SET published=:published WHERE id=:id", array(':published' => 1, ':id' => $tag_id));
  }
  drupal_set_message(t('Tag successfully published.'), 'status', FALSE);
  drupal_goto(url('admin/settings/spider_video_player/tags', array('absolute' => TRUE)));
}

/**
 * Unpublish selected tags.
 */
function spider_video_player_tags_unpublish($form, &$form_state) {
  if (db_query("SELECT id FROM {spider_video_player_tag}")) {
    $tag_ids_col = db_query("SELECT id FROM {spider_video_player_tag}")->fetchCol();
    $flag = FALSE;
    foreach ($tag_ids_col as $tag_id) {
      if (isset($_POST['checkbox' . $tag_id])) {
        $flag = TRUE;
        db_query("UPDATE {spider_video_player_tag} SET published=:published WHERE id=:id", array(':published' => 0, ':id' => $tag_id));
      }
    }
    if ($flag == FALSE) {
      drupal_set_message(t('You must select at least one tag.'), 'warning', FALSE);
    }
    else {
      drupal_set_message(t('Tags successfully unpublished.'), 'status', FALSE);
    }
  }
}

/**
 * Unpublish tag.
 */
function spider_video_player_tag_unpublish() {
  if (isset($_GET['tag_id'])) {
    $tag_id = check_plain($_GET['tag_id']);
    db_query("UPDATE {spider_video_player_tag} SET published=:published WHERE id=:id", array(':published' => 0, ':id' => $tag_id));
  }
  drupal_set_message(t('Tag successfully unpublished.'), 'status', FALSE);
  drupal_goto(url('admin/settings/spider_video_player/tags', array('absolute' => TRUE)));
}

/**
 * Set required selected tags.
 */
function spider_video_player_tags_set_required($form, &$form_state) {
  if (db_query("SELECT id FROM {spider_video_player_tag}")) {
    $tag_ids_col = db_query("SELECT id FROM {spider_video_player_tag}")->fetchCol();
    $flag = FALSE;
    foreach ($tag_ids_col as $tag_id) {
      if (isset($_POST['checkbox' . $tag_id])) {
        $flag = TRUE;
        db_query("UPDATE {spider_video_player_tag} SET required=:required WHERE id=:id", array(':required' => 1, ':id' => $tag_id));
      }
    }
    if ($flag == FALSE) {
      drupal_set_message(t('You must select at least one tag.'), 'warning', FALSE);
    }
    else {
      drupal_set_message(t('Tags successfully set required.'), 'status', FALSE);
    }
  }
}

/**
 * Set required tag.
 */
function spider_video_player_tag_set_required() {
  if (isset($_GET['tag_id'])) {
    $tag_id = check_plain($_GET['tag_id']);
    db_query("UPDATE {spider_video_player_tag} SET required=:required WHERE id=:id", array(':required' => 1, ':id' => $tag_id));
  }
  drupal_set_message(t('Tag successfully sets required.'), 'status', FALSE);
  drupal_goto(url('admin/settings/spider_video_player/tags', array('absolute' => TRUE)));
}

/**
 * Set not required selected tags.
 */
function spider_video_player_tags_set_not_required($form, &$form_state) {
  if (db_query("SELECT id FROM {spider_video_player_tag}")) {
    $tag_ids_col = db_query("SELECT id FROM {spider_video_player_tag}")->fetchCol();
    $flag = FALSE;
    foreach ($tag_ids_col as $tag_id) {
      if (isset($_POST['checkbox' . $tag_id])) {
        $flag = TRUE;
        db_query("UPDATE {spider_video_player_tag} SET required=:required WHERE id=:id", array(':required' => 0, ':id' => $tag_id));
      }
    }
    if ($flag == FALSE) {
      drupal_set_message(t('You must select at least one tag.'), 'warning', FALSE);
    }
    else {
      drupal_set_message(t('tags successfully set not required.'), 'status', FALSE);
    }
  }
}

/**
 * Set not required tag.
 */
function spider_video_player_tag_set_not_required() {
  if (isset($_GET['tag_id'])) {
    $tag_id = check_plain($_GET['tag_id']);
    db_query("UPDATE {spider_video_player_tag} SET required=:required WHERE id=:id", array(':required' => 0, ':id' => $tag_id));
  }
  drupal_set_message(t('Tag successfully sets not required.'), 'status', FALSE);
  drupal_goto(url('admin/settings/spider_video_player/tags', array('absolute' => TRUE)));
}

/**
 * Delete selected tags.
 */
function spider_video_player_tags_delete($form, &$form_state) {
  if (db_query("SELECT id FROM {spider_video_player_tag}")) {
    $tag_ids_col = db_query("SELECT id FROM {spider_video_player_tag}")->fetchCol();
    $flag = FALSE;
    foreach ($tag_ids_col as $tag_id) {
      if (isset($_POST['checkbox' . $tag_id])) {
        $flag = TRUE;
        db_query("DELETE FROM {spider_video_player_tag} WHERE id=:id", array(':id' => $tag_id));
        $ids_col = db_query("SELECT id,params FROM {spider_video_player_video}")->fetchAllKeyed();
        foreach ($ids_col as $key => $params) {
          $param = explode('#***#', $params);
          foreach ($param as $param_id) {
            if (($param_id != '') && (strpos($param_id, $tag_id) === 0)) {
              db_query("UPDATE {spider_video_player_video} SET params=:params WHERE id=:id", array(':params' => str_replace($param_id . '#***#', '', $params), ':id' => $key));
            }
          }
        }
      }
    }
    if ($flag == FALSE) {
      drupal_set_message(t('You must select at least one tag.'), 'warning', FALSE);
    }
    else {
      drupal_set_message(t('Selected tags successfully deleted.'), 'status', FALSE);
    }
  }
}

/**
 * Delete tag.
 */
function spider_video_player_tag_delete() {
  if (isset($_GET['tag_id'])) {
    $tag_id = check_plain($_GET['tag_id']);
    db_query("DELETE FROM {spider_video_player_tag} WHERE id=:id", array(':id' => $tag_id));
    $ids_col = db_query("SELECT id,params FROM {spider_video_player_video}")->fetchAllKeyed();
    foreach ($ids_col as $key => $params) {
      $param = explode('#***#', $params);
      foreach ($param as $param_id) {
        if (($param_id != '') && (strpos($param_id, $tag_id) === 0)) {
          db_query("UPDATE {spider_video_player_video} SET params=:params WHERE id=:id", array(':params' => str_replace($param_id . '#***#', '', $params), ':id' => $key));
        }
      }
    }
  }
  drupal_set_message(t('Tag successfully deleted.'), 'status', FALSE);
  drupal_goto(url('admin/settings/spider_video_player/tags', array('absolute' => TRUE)));
}

/**
 * Save ordering.
 */
function spider_video_player_save_ordering($form, &$form_state) {
  $tags_ids = db_query("SELECT id FROM {spider_video_player_tag}")->fetchCol();
  foreach ($tags_ids as $tag_id) {
    if (isset($_POST['spider_video_player_tags_order_' . $tag_id])) {
      $ordering = check_plain($_POST['spider_video_player_tags_order_' . $tag_id]);
      db_query("UPDATE {spider_video_player_tag} SET ordering=:ordering WHERE id=:id", array(':ordering' => $ordering, ':id' => $tag_id));
    }
    drupal_set_message(t('Tag ordering successfully saved.'), 'status', FALSE);
  }
}

/**
 * Add or edit tag.
 */
function spider_video_player_tag_edit() {
  if (isset($_GET['tag_id'])) {
    $tag_id = check_plain($_GET['tag_id']);
    $row = db_query("SELECT * FROM {spider_video_player_tag} WHERE id=:id", array(':id' => $tag_id))->fetchObject();
    $tag_name = $row->name;
    $tag_required = $row->required;
    $tag_published = $row->published;
  }
  else {
    $tag_id = '';
    $tag_name = '';
    $tag_required = 1;
    $tag_published = 1;
  }
  $form = array();
  $form['tag_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => TRUE,
    '#default_value' => $tag_name,
    '#size' => 15,
  );
  $form['tag_required'] = array(
    '#type' => 'radios',
    '#title' => t('Required'),
    '#default_value' => $tag_required,
    '#options' => array('1' => t('Yes'), '0' => t('No')),
  );
  $form['tag_published'] = array(
    '#type' => 'radios',
    '#title' => t('Published'),
    '#default_value' => $tag_published,
    '#options' => array('1' => t('Yes'), '0' => t('No')),
  );
  $form['tag_save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#submit' => array('spider_video_player_tag_save'),
  );
  $form['tag_apply'] = array(
    '#type' => 'submit',
    '#value' => t('Apply'),
    '#submit' => array('spider_video_player_tag_apply'),
  );
  $form['tag_cancel'] = array(
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#attributes' => array('onclick' => 'document.getElementById("edit-tag-name").setAttribute("style", "color:rgba(255, 0, 0, 0)");document.getElementById("edit-tag-name").setAttribute("value", "cancel");'),
    '#submit' => array('spider_video_player_tag_cancel'),
  );
  return $form;
}

/**
 * Save tag.
 */
function spider_video_player_tag_save($form, &$form_state) {
  global $user;
  $tag_name = $form_state['values']['tag_name'];
  $tag_required = $form_state['values']['tag_required'];
  $tag_published = $form_state['values']['tag_published'];
  if (isset($_GET['tag_id'])) {
    $tag_id = check_plain($_GET['tag_id']);
    db_query("UPDATE {spider_video_player_tag} SET 
      uid=:uid,
      name=:name,
      required=:required,
      published=:published WHERE id=:id", array(
      ':uid' => $user->uid,
      ':name' => $tag_name,
      ':required' => $tag_required,
      ':published' => $tag_published,
      ':id' => $tag_id));
  }
  else {
    db_insert('spider_video_player_tag')
      ->fields(array(
        'uid' => $user->uid,
        'name' => $tag_name,
        'required' => $tag_required,
        'ordering' => 0,
        'published' => $tag_published,
        ))
      ->execute();
    // Adding new tag to all videos.
    $tag_id = db_query("SELECT MAX(id) FROM {spider_video_player_tag}")->fetchField();
    $ids_col = db_query("SELECT id,params FROM {spider_video_player_video}")->fetchAllKeyed();
    foreach ($ids_col as $key => $params) {
      db_query("UPDATE {spider_video_player_video} SET params=:params WHERE id=:id", array(':params' => $params . $tag_id . '#===##***#', ':id' => $key));
    }
  }
  drupal_set_message(t('Your tag successfully saved.'), 'status', FALSE);
  $form_state['redirect'] = url('admin/settings/spider_video_player/tags', array('absolute' => TRUE));
}

/**
 * Apply tag.
 */
function spider_video_player_tag_apply($form, &$form_state) {
  global $user;
  $tag_name = $form_state['values']['tag_name'];
  $tag_required = $form_state['values']['tag_required'];
  $tag_published = $form_state['values']['tag_published'];
  if (isset($_GET['tag_id'])) {
    $tag_id = check_plain($_GET['tag_id']);
    db_query("UPDATE {spider_video_player_tag} SET 
      uid=:uid,
      name=:name,
      required=:required,
      published=:published WHERE id=:id", array(
      ':uid' => $user->uid,
      ':name' => $tag_name,
      ':required' => $tag_required,
      ':published' => $tag_published,
      ':id' => $tag_id));
    drupal_set_message(t('Your tag successfully updated.'), 'status', FALSE);
  }
  else {
    db_insert('spider_video_player_tag')
      ->fields(array(
        'uid' => $user->uid,
        'name' => $tag_name,
        'required' => $tag_required,
        'ordering' => 0,
        'published' => $tag_published,
        ))
      ->execute();
    $tag_id = db_query("SELECT MAX(id) FROM {spider_video_player_tag}")->fetchField();
    // Adding new tag to all videos.
    $ids_col = db_query("SELECT id,params FROM {spider_video_player_video}")->fetchAllKeyed();
    foreach ($ids_col as $key => $params) {
      db_query("UPDATE {spider_video_player_video} SET params=:params WHERE id=:id", array(':params' => $params . $tag_id . '#===##***#', ':id' => $key));
    }
    drupal_set_message(t('Your tag successfully saved.'), 'status', FALSE);
  }
  $form_state['redirect'] = url('admin/settings/spider_video_player/tags/edit', array('query' => array('tag_id' => $tag_id), 'absolute' => TRUE));
}

/**
 * Cancel tag save.
 */
function spider_video_player_tag_cancel($form, &$form_state) {
  $form_state['redirect'] = url('admin/settings/spider_video_player/tags', array('absolute' => TRUE));
}
