<?php

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

/**
 * Implements hook_schema().
 */
function uc_stock_schema() {
  $schema = array();

  $schema['uc_product_stock'] = array(
    'description' => 'Stock levels for Ubercart products.',
    'fields' => array(
      'sku' => array(
        'description' => 'SKU (Stock Keeping Unit) of a product.',
        'type' => 'varchar',
        'length' => '255',
        'not null' => TRUE,
        'default' => '',
      ),
      'nid' => array(
        'description' => 'Node ID of a product.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'active' => array(
        'description' => 'Boolean flag indicating whether stock is being tracked for this product. 1 => Yes. 0 => No.',
        'type' => 'int',
        'size' => 'tiny',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'stock' => array(
        'description' => 'Quantity in stock.',
        'type' => 'int',
        'size' => 'medium',
        'not null' => TRUE,
        'default' => 0,
      ),
      'threshold' => array(
        'description' => 'Minimum quantity threshold level.',
        'type' => 'int',
        'size' => 'medium',
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'indexes' => array(
      'nid' => array('nid'),
    ),
    'primary key' => array('sku'),
    'foreign keys' => array(
      'nid' => array('uc_products' => 'nid'),
    ),
  );

  return $schema;
}

/**
 * Implements hook_uninstall().
 */
function uc_stock_uninstall() {
  db_delete('variable')
    ->condition('name', 'uc_stock_%', 'LIKE')
    ->execute();

  variable_del('uc_stock_threshold_notification');
  variable_del('uc_stock_threshold_notification_recipients');
  variable_del('uc_stock_threshold_notification_subject');
  variable_del('uc_stock_threshold_notification_message');
  variable_del('uc_stock_threshold_notification_message_format');
}

/**
 * Implements hook_update_last_removed().
 */
function uc_stock_update_last_removed() {
  return 6000;
}

/**
 * Changes name of a format variable.
 */
function uc_stock_update_7000() {
  $format = variable_get('uc_stock_threshold_notification_format');

  if ($format) {
    variable_set('uc_stock_threshold_notification_message_format', $format);
  }

  variable_del('uc_stock_threshold_notification_format');
}
