<?php
/**
 * @file
 * This file holds the functions for the module.
 */

/**
 * Check if the user wants a popup and display it.
 */
function popup_question_redirect_display_popup() {

  // Get the ip address of the visitor.
  $ip = ip_address();

  // Check the ip address of the visitor.
  if (!empty($ip)) {

    // Get the ip blacklist configuration.
    $blacklist = check_plain(variable_get('popup_question_redirect_ip_blacklist', ''));

    // Check the blacklist.
    if (!empty($blacklist)) {

      // Explode the configuration value on newlines.
      $blacklist_array = explode(PHP_EOL, $blacklist);

      // Check for the blacklisted ips.
      if (!in_array($ip, $blacklist_array)) {

        // Render the popup.
        popup_question_redirect_check_popup($ip);
      }
    }
    else {

      // Render the popup.
      popup_question_redirect_check_popup($ip);
    }
  }

  // Return FALSE if we can't get the ip.
  return FALSE;
}

/**
 * Check the popup.
 *
 * @param string $ip
 *   The ip address of the visitor.
 */
function popup_question_redirect_check_popup($ip) {

  // Include the database functions.
  module_load_include('inc', 'popup_question_redirect', 'includes/database');

  // Try to fetch the entry for the visitor.
  $entry = popup_question_redirect_select_entries($ip);

  // If there is no entry, display the popup.
  if (!$entry) {

    // Render the popup.
    popup_question_redirect_render_popup();
  }
  else {

    // Check for remind me later.
    if (!empty($entry->type) && $entry->type == 2) {

      // Get the timeout.
      $timeout = check_plain(variable_get('popup_question_redirect_reminder_timeout', '00_30'));
      $array = explode('_', $timeout);

      // Format to seconds.
      $time = ($array[0] * 60 * 60) + ($array[1] * 60);

      // Calculate time since the visitor clicked remind me later.
      if ((time() - $entry->created - $time) > 0) {

        // Render the popup.
        popup_question_redirect_render_popup();
      }
    }
  }
}

/**
 * Render the popup.
 *
 */
function popup_question_redirect_render_popup() {

  // Don't do anything on admin pages.
  if (!path_is_admin(current_path())) {

    // Get the configuration for showing the popup to logged in users.
    $show_logged_in = variable_get('popup_question_redirect_popup_show_logged_in', 0);

    // Get the user status.
    $user_logged_in = user_is_logged_in();

    // Check if the popup needs to be shown.
    if (($show_logged_in && $user_logged_in | !$user_logged_in) || (!$show_logged_in && !$user_logged_in)) {

      // Get the configuration for the popup message.
      $message = variable_get('popup_question_redirect_popup_message', '');

      // Check the message.
      if (!empty($message)) {

        // Initialize the variables.
        $variables = array();

        // Get the configuration for the popup title.
        $variables['title'] = check_plain(variable_get('popup_question_redirect_popup_title', t('Survey')));

        // Create a variable for the message.
        $variables['message'] = is_array($message) && array_key_exists('value', $message) ? $message['value'] : $message;

        // Get the configuration for the popup footer buttons.
        $variables['yes'] = check_plain(variable_get('popup_question_redirect_popup_button_yes', ''));
        $variables['hide'] = check_plain(variable_get('popup_question_redirect_popup_button_hide', ''));
        $variables['no'] = check_plain(variable_get('popup_question_redirect_popup_button_no', ''));

        // Theme the popup.
        $html = theme('popup_question_redirect_popup', $variables);

        // Add the css and javascript.
        popup_question_redirect_add_scripts($html);
      }
    }
  }
}

/**
 * Insert a database entry to no longer show the popup for someone.
 */
function popup_question_redirect_create_entry() {

  // Get the ip address of the visitor.
  $ip = ip_address();

  // Check for post values and check if the token is a valid token.
  if (isset($_POST['type']) && isset($_POST['token']) && drupal_valid_token($_POST['token'], '', TRUE)) {

    // Include the database functions.
    module_load_include('inc', 'popup_question_redirect', 'includes/database');

    // Select the record for the IP.
    $record = popup_question_redirect_select_entries($ip);

    // Check the record.
    if (!empty($record)) {

      // Update the record.
      popup_question_redirect_update_entry($ip, check_plain($_POST['type']));
    }
    else {

      // Insert an entry into the database.
      popup_question_redirect_insert_entry($ip, check_plain($_POST['type']));
    }
  }
}

/**
 * Add the css and javascript.
 *
 * @param string $html
 *   The html content for the popup.
 */
function popup_question_redirect_add_scripts($html) {

  // Check if there is content for the popup.
  if (!empty($html)) {

    // Add external jquery.
    drupal_add_js('//code.jquery.com/jquery-1.10.0.min.js', 'external');

    // Add bootstrap css + javascript from cdn.
    drupal_add_css('//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css', 'external');
    drupal_add_js('//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js', 'external');

    // Add the module javascript.
    drupal_add_js(drupal_get_path('module', 'popup_question_redirect') . '/assets/js/popup_question_redirect.js');

    // Add the data for the poll modal.
    drupal_add_js(array(
      'html'              => $html,
      'location'          => current_path(),
      'location_redirect' => variable_get('popup_question_redirect_popup_button_yes_location', ''),
      'token'             => drupal_get_token(),
    ), 'setting');
  }
}

/**
 * Convert the type to a string.
 *
 * @param int $type
 *   The numeric type.
 *
 * @return string
 *   Returns the text equivalent of the type.
 */
function popup_question_redirect_type_to_string($type) {

  // Initialize the string.
  $string = '';

  // Switch on the type.
  switch ($type) {
    case 1:
      $string = variable_get('popup_question_redirect_popup_button_yes', t('Yes'));
      break;
    case 2:
      $string = variable_get('popup_question_redirect_popup_button_hide', t('No, remind me later'));
      break;
    case 3:
      $string = variable_get('popup_question_redirect_popup_button_no', t("No, don't show again"));
      break;
  }

  // Return the string.
  return $string;
}
