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

/**
 * Get the database entries and display them as a table.
 */
function popup_question_redirect_get_entries_page() {

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

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

  // Get the clear form.
  $build['popup_question_redirect_clear_database_form'] = drupal_get_form('popup_question_redirect_clear_database_form');

  // The table header.
  $header = array(
    array('data' => t('Id'), 'field' => 'p.id'),
    array('data' => t('Ip'), 'field' => 'p.ip', 'sort' => 'desc'),
    array('data' => t('Type'), 'field' => 'p.type', 'sort' => 'desc'),
    array('data' => t('Created'), 'field' => 'p.created', 'sort' => 'desc'),
  );

  // Query the popup question redirect table.
  $query = db_select('popup_question_redirect', 'p')
    ->fields('p')
    ->extend('PagerDefault')
    ->extend('TableSort');

  // Add the limit and order and execute.
  $result = $query
    ->limit(50)
    ->orderByHeader($header)
    ->execute();

  // Loop through the results.
  foreach ($result as $entry) {
    $rows[] = array(
      'data' =>
        array(
          // Cells
          $entry->id,
          $entry->ip,
          popup_question_redirect_type_to_string($entry->type),
          format_date($entry->created, 'short'),
        ),
    );
  }

  // Build the table.
  $build['popup_question_redirect_table'] = array(
    '#theme'      => 'table',
    '#header'     => $header,
    '#rows'       => $rows,
    '#attributes' => array('id' => 'admin-popup-question-redirect'),
    '#empty'      => t('No entries available.'),
  );

  // Add the pager.
  $build['popup_question_redirect_pager'] = array('#theme' => 'pager');

  // Return the build.
  return $build;
}
