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

/**
 * Select a database entry for someone.
 *
 * @param string $ip
 *   The IP address of the visitor.
 *
 * @return array
 *   Returns an array of values based on the visitors ip address if found.
 */
function popup_question_redirect_select_entries($ip = '') {

  // Check if the table exists.
  if (db_table_exists('popup_question_redirect')) {

    // Query the entries.
    $entry = db_select('popup_question_redirect', 'p');

    // Select everything.
    $entry->fields('p');

    if (!empty($ip)) {

      // Match on ip.
      $entry->condition('p.ip', $ip, '=');

      // Return the object.
      return $entry->execute()->fetchObject();
    }
    else {

      // Return everything.
      return $entry->execute()->fetchAll();
    }
  }

  // Return FALSE if not.
  return FALSE;
}

/**
 * Insert an entry into the database.
 *
 * @param string $ip
 *   The IP address of the user.
 * @param $type
 *
 * @throws \Exception
 */
function popup_question_redirect_insert_entry($ip, $type) {

  // Try to insert the entry.
  try {

    // Insert the entry.
    db_insert('popup_question_redirect')
      ->fields(array(
        'ip'      => $ip,
        'type'    => $type,
        'created' => time(),
      ))
      ->execute();
  }
  // Catch any PDO exceptions.
  catch (\PDOException $e) {

    // Get the error message.
    $error = $e->getMessage();

    // Log the error message.
    watchdog_exception('popup_question_redirect', $e, t('Caught an error: ' . $error));
  }
}

/**
 * Update a database entry to hide the popup for a specific amount of time.
 *
 * @param string $ip
 *   The IP address of the visitor.
 * @param int $type
 *   The numeric type of the entry.
 */
function popup_question_redirect_update_entry($ip, $type) {

  // Try to update the entry.
  try {

    // Update the database with the new references.
    db_update('popup_question_redirect')
      ->fields(array('type' => $type, 'created' => time()))
      ->condition('ip', $ip, '=')
      ->execute();
  }
    // Catch any PDO exceptions.
  catch (\PDOException $e) {

    // Get the error message.
    $error = $e->getMessage();

    // Log the error message.
    watchdog_exception('popup_question_redirect', $e, t('Caught an error: ' . $error));
  }
}
