<?php
/**
 * @file
 * The module installation functions.
 */

/**
 * Implements hook_enable()
 */
function user_email_verification_install() {
  // TODO: Think of making this in batch operation cause if there are many users it will timeout the installation!
  $result  = db_select('users')->fields('users', array('uid'))->condition('uid', 1, '>')->execute();
  $query   = db_insert('user_email_verification')->fields(array('uid', 'verified'));
  $execute = FALSE;
  foreach ($result as $account) {
    $execute = TRUE;
    $query->values(array(
      'uid' => $account->uid,
      'verified' => 1,
    ));
  }
  if ($execute) {
    $query->execute();
  }
}

/**
 * Implements hook_schema().
 */
function user_email_verification_schema() {
  $schema['user_email_verification'] = array(
    'description' => 'The base table for email verification for specific user.',
    'fields' => array(
      'uid' => array(
        'description' => 'The user id from users table.',
        'type' => 'int',
        'not null' => TRUE,
        'unsigned' => TRUE,
        'default' => 0,
      ),
      'verified' => array(
        'description' => 'The verified flag.',
        'type' => 'int',
        'not null' => TRUE,
        'unsigned' => TRUE,
        'default' => 0,
      ),
      'last_reminder' => array(
        'type' => 'int',
        'description' => 'Last notification timestamp.',
        'not null' => TRUE,
        'unsigned' => TRUE,
        'default' => 0,
      ),
      'reminders' => array(
        'type' => 'int',
        'description' => 'Number of reminders sent.',
        'not null' => TRUE,
        'unsigned' => TRUE,
        'default' => 0,
      ),
    ),
    'indexes' => array(
      'inx_uid'      => array('uid'),
      'inx_verified'  => array('verified'),
      'inx_last_reminder'  => array('last_reminder'),
    ),
    'unique keys' => array(),
    'foreign keys' => array(
      'fk_verification_uid' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
    ),
    'primary key' => array('uid'),
  );
  return $schema;
}

/**
 * Modifies the schema to allow sending reminders.
 */
function user_email_verification_update_7001() {
  db_add_field('user_email_verification', 'last_reminder',
    array(
      'type' => 'int',
      'description' => 'Last notification timestamp.',
      'not null' => TRUE,
      'unsigned' => TRUE,
      'default' => 0,
    ),
    array(
      'indexes' => array(
        'inx_last_reminder' => array('last_reminder'),
      ),
    )
  );
  db_add_field('user_email_verification', 'reminders',
    array(
      'type' => 'int',
      'description' => 'Number of reminders sent.',
      'not null' => TRUE,
      'unsigned' => TRUE,
      'default' => 0,
    )
  );
}
