<?php

/**
 * @file
 * Install, update and uninstall functions for the Simplenews RealName module.
 */

/**
 * Implementation of hook_schema().
 */
function simplenews_realname_schema() {
  $schema['simplenews_realname'] = array(
    'description' => 'Subscriber real names.',
    'fields' => array(
      'mail' => array(
        'description' => 'The subscriber email address.',
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
        'default' => '',
      ),
      'realname' => array(
        'description' => 'The subscriber real name.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'indexes' => array(
      'realname' => array('realname'),
    ),
    'primary key' => array('mail'),
  );
  return $schema;
}

/**
 * Implementation of hook_install().
 */
function simplenews_realname_install() {
  drupal_install_schema('simplenews_realname');
}

/**
 * Implementation of hook_uninstall().
 */
function simplenews_realname_uninstall() {
  drupal_uninstall_schema('simplenews_realname');
}

/**
 * Create a new table to store real names and move the data there.
 */
function simplenews_realname_update_6201() {
  $ret = array();

  $schema['simplenews_realname'] = array(
    'description' => 'Subscriber real names.',
    'fields' => array(
      'mail' => array(
        'description' => 'The subscriber email address.',
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
        'default' => '',
      ),
      'realname' => array(
        'description' => 'The subscriber real name.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'indexes' => array(
      'realname' => array('realname'),
    ),
    'primary key' => array('mail'),
  );

  if (!db_table_exists('simplenews_realname')) {
    db_create_table($ret, 'simplenews_realname', $schema['simplenews_realname']);
    $ret[] = update_sql("INSERT INTO {simplenews_realname} (mail, realname) SELECT ss.mail, ss.realname FROM {simplenews_subscriptions} ss");
    db_drop_field($ret, 'simplenews_subscriptions', 'realname');
  }

  return $ret;
}
