<?php

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

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

  $schema['uc_product_classes'] = array(
    'description' => 'The list of product node types.',
    'fields' => array(
      'pcid' => array(
        'description' => 'The node type identifier.',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
      'name' => array(
        'description' => 'The human-readable name.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'description' => array(
        'description' => 'The description of the node type.',
        'type' => 'text',
      ),
    ),
    'primary key' => array('pcid'),
  );

  $schema['uc_product_features'] = array(
    'description' => 'Stores information of features added to products.',
    'fields' => array(
      'pfid' => array(
        'description' => 'Primary key: the product feature id.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'nid' => array(
        'description' => 'The {node}.nid of the product that has this feature.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'fid' => array(
        'description' => 'The type of feature.',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
      'description' => array(
        'description' => 'The description of the feature.',
        'type' => 'text',
      ),
    ),
    'indexes' => array(
      'nid' => array('nid'),
    ),
    'primary key' => array('pfid'),
    'foreign keys' => array(
      'uc_product' => array(
        'table' => 'uc_product',
        'columns' => array('nid' => 'nid'),
      ),
    ),
  );

  $schema['uc_products'] = array(
    'description' => 'Product information for nodes.',
    'fields' => array(
      'vid' => array(
        'description' => 'The {node}.vid of the product.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'nid' => array(
        'description' => 'The {node}.nid of the product.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'model' => array(
        'description' => 'SKU or model number.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'list_price' => array(
        'description' => 'Suggested retail price.',
        'type' => 'numeric',
        'precision' => 16,
        'scale' => 5,
        'not null' => TRUE,
        'default' => 0.0,
      ),
      'cost' => array(
        'description' => 'The amount the store pays to sell the product.',
        'type' => 'numeric',
        'precision' => 16,
        'scale' => 5,
        'not null' => TRUE,
        'default' => 0.0,
      ),
      'sell_price' => array(
        'description' => 'The amount the customer pays for the product.',
        'type' => 'numeric',
        'precision' => 16,
        'scale' => 5,
        'not null' => TRUE,
        'default' => 0.0,
      ),
      'weight' => array(
        'description' => 'Physical weight.',
        'type' => 'float',
        'not null' => TRUE,
        'default' => 0.0,
      ),
      'weight_units' => array(
        'description' => 'Unit of measure for the weight field.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => 'lb',
      ),
      'length' => array(
        'description' => 'Physical length of the product or its packaging.',
        'type' => 'float',
        'not null' => TRUE,
        'default' => 0.0,
      ),
      'width' => array(
        'description' => 'Physical width of the product or its packaging.',
        'type' => 'float',
        'not null' => TRUE,
        'default' => 0.0,
      ),
      'height' => array(
        'description' => 'Physical height of the product or its packaging.',
        'type' => 'float',
        'not null' => TRUE,
        'default' => 0.0,
      ),
      'length_units' => array(
        'description' => 'Unit of measure for the length, width, and height.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => 'in',
      ),
      'pkg_qty' => array(
        'description' => 'The number of this product that fit in one package.',
        'type' => 'int',
        'size' => 'small',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 1,
      ),
      'default_qty' => array(
        'description' => 'The default value for the quantity field in the "Add to Cart" form.',
        'type' => 'int',
        'size' => 'small',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 1,
      ),
      'ordering' => array(
        'description' => 'The sort criteria for products.',
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 0,
      ),
      'shippable' => array(
        'description' => 'Boolean flag signifying that the product can be shipped.',
        'type' => 'int',
        'size' => 'tiny',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 1,
      ),
    ),
    'indexes' => array(
      'nid' => array('nid'),
    ),
    'primary key' => array('vid'),
    'foreign keys' => array(
      'node' => array(
        'table' => 'node',
        'columns' => array(
          'nid' => 'nid',
          'vid' => 'vid',
        ),
      ),
    ),
  );

  return $schema;
}

/**
 * Implements hook_enable().
 *
 * Sets up the body and a default image field for products.
 */
function uc_product_enable() {
  $body_label = t('Description');

  node_types_rebuild();
  $types = node_type_get_types();
  foreach ($types as $type) {
    if ($type->module == 'uc_product') {
      node_add_body_field($type, $body_label);
      uc_product_set_teaser_display($type->type);
    }
  }

  uc_product_add_default_image_field();
}

/**
 * Implements hook_uninstall().
 */
function uc_product_uninstall() {
  db_delete('variable')
    ->condition(db_or()
      ->condition('name', 'uc_product_shippable_%', 'LIKE')
      ->condition('name', 'uc_image_%', 'LIKE'))
    ->execute();

  variable_del('uc_product_nodes_per_page');
  variable_del('uc_product_add_to_cart_qty');
}

/**
 * Implements hook_update_last_removed().
 */
function uc_product_update_last_removed() {
  return 6009;
}

/**
 * Renames node permissions for the Product type.
 */
function uc_product_update_7000() {
  db_update('role_permission')
    ->fields(array(
      'permission' => 'create product products',
    ))
    ->condition('permission', 'create products')
    ->execute();

  db_update('role_permission')
    ->fields(array(
      'permission' => 'edit own product products',
    ))
    ->condition('permission', 'edit own products')
    ->execute();

  db_update('role_permission')
    ->fields(array(
      'permission' => 'edit all product products',
    ))
    ->condition('permission', 'edit all products')
    ->execute();

  db_update('role_permission')
    ->fields(array(
      'permission' => 'delete own product products',
    ))
    ->condition('permission', 'delete own products')
    ->execute();

  db_update('role_permission')
    ->fields(array(
      'permission' => 'delete all product products',
    ))
    ->condition('permission', 'delete all products')
    ->execute();

  return t('Renamed node permissions for the Product type.');
}

/**
 * Use actual node permissions for product types.
 */
function uc_product_update_7001() {
  $types = db_query("SELECT pcid FROM {uc_product_classes}")->fetchCol();
  array_unshift($types, 'product');
  foreach ($types as $type) {
    $node_perms = array_keys(node_list_permissions($type));

    foreach ($node_perms as $node_perm) {
      $product_perm = str_replace(array('any', 'content'), array('all', 'products'), $node_perm);

      foreach (user_roles(FALSE, $product_perm) as $rid => $role) {
        db_merge('role_permission')
          ->key(array(
            'rid' => $rid,
            'permission' => $node_perm,
          ))
          ->fields(array(
            'module' => 'node',
          ))
          ->execute();
      }

      // Clean up.
      db_delete('role_permission')
        ->condition('permission', $product_perm)
        ->execute();
    }
  }

  return t('Changed product node permissions to the actual node permissions.');
}

/**
 * Makes sure Image is enabled.
 */
function uc_product_update_7002() {
  if (module_exists('uc_product') && !module_exists('image')) {
    module_enable(array('file', 'image'), FALSE);

    return t('Enabled Image module.');
  }
}

/**
 * Set default display settings for product teasers.
 */
function uc_product_update_7003() {
  $types = db_query("SELECT pcid FROM {uc_product_classes}")->fetchCol();
  array_unshift($types, 'product');
  foreach ($types as $type) {
    uc_product_set_teaser_display($type);
  }

  variable_del('uc_product_field_enabled');
  variable_del('uc_product_field_weight');

  return t('Set display settings for product teasers.');
}

/**
 * Remove unused variables.
 */
function uc_product_update_7004() {
  variable_del('uc_product_add_to_cart_teaser');
  variable_del('uc_teaser_add_to_cart_text');
  variable_del('uc_product_add_to_cart_text');
}

/**
 * Remove unused unique hash column.
 */
function uc_product_update_7300() {
  db_drop_field('uc_products', 'unique_hash');
}

/**
 * Sets default display settings for product teasers.
 */
function uc_product_set_teaser_display($type) {
  $settings = field_bundle_settings('node', $type);
  $settings['view_modes']['teaser']['custom_settings'] = TRUE;

  $fields = array('model', 'list_price', 'cost', 'weight', 'dimensions');
  foreach ($fields as $field) {
    $settings['extra_fields']['display'][$field]['teaser'] = array(
      'weight' => 0,
      'visible' => FALSE,
    );
  }

  field_bundle_settings('node', $type, $settings);
}
