<?php
/**
 * @file
 * Defines a product feature to tweak the add to cart form behavior.
 */


/**
 * Implements hook_form_alter().
 *
 * Summary of alterations:
 * 1) Alters the product feature add form to restrict multiple Add to Cart
 *      Tweak features from being added to a single product.
 * 2) Alters the add to cart form for variable priced products.
 * 3) Alter the product class form to set default add to cart tweaks.
 */
function uc_atctweaks_form_alter(&$form, &$form_state, $form_id) {
  // 1) Alter the product feature add form.
  if ($form_id == 'uc_product_feature_add_form') {
    // If an add to cart tweak has already been added to this product...
    if (db_query("SELECT COUNT(*) FROM {uc_product_features} WHERE nid = :nid AND fid = :fid", array(':nid' => arg(1), ':fid' => 'atctweaks'))->fetchField()) {
      // Remove Add to Cart Tweak from the available list of features to add.
      unset($form['feature']['#options']['atctweaks']);
    }
  }

  // 2) Alters the add to cart form for variable priced products.
  if (strpos($form_id, 'uc_product_add_to_cart_form_') === 0) {
    $data = uc_atctweaks_product_load($form['nid']['#value']);

    if ($data) {
      $form['atctweaks_data'] = array(
        '#type' => 'value',
        '#value' => $data,
      );
      $form['#submit'] = array_merge(array('uc_atctweaks_add_to_cart_pre_submit'), $form['#submit']);
      $form['#submit'][] = 'uc_atctweaks_add_to_cart_post_submit';
    }
  }

  // 3) Alter the product class form to set default add to cart tweaks.
  if ($form_id == 'uc_product_class_form') {
    $data = FALSE;
    if (!empty($form['pcid']['#value'])) {
      $class_defaults = variable_get('ucatc_class_def_' . $form['pcid']['#value'], array());
      if (!empty($class_defaults)) {
        $data = (object) unserialize($class_defaults);
      }
    }

    $form['atctweaks'] = array(
      '#type' => 'fieldset',
      '#title' => t('Default Add to Cart Tweaks'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#weight' => 5,
    );
    $form['atctweaks']['default_atctweaks'] = array(
      '#type' => 'checkbox',
      '#title' => t('Check this box to add default Add to Cart Tweaks to every product of this class using these settings.'),
      '#default_value' => $data === FALSE ? FALSE : TRUE,
    );
    $form['atctweaks'] += _uc_atctweaks_feature_form($data);

    $form['#submit'][] = 'uc_atctweaks_product_class_submit';

    $form['submit']['#weight'] = 10;
  }
}

/**
 * Submit handler for the add to cart form to process after the normal handler.
 */
function uc_atctweaks_add_to_cart_pre_submit($form, &$form_state) {
  if (!empty($form_state['values']['atctweaks_data'])) {
    $data = $form_state['values']['atctweaks_data'];

    // Empty the shopping cart if the feature specifies to do so.
    if ($data->cart_empty) {
      uc_cart_empty(uc_cart_get_id());
    }
  }
}

/**
 * Submit handler for the add to cart form to process after the normal handler.
 */
function uc_atctweaks_add_to_cart_post_submit($form, &$form_state) {
  if (!empty($form_state['values']['atctweaks_data'])) {
    $data = $form_state['values']['atctweaks_data'];

    switch ($data->redirect) {
      case 'cart':
        $form_state['redirect'] = 'cart';
        break;
      case 'checkout':
        $form_state['redirect'] = 'cart/checkout';
        break;
      case 'none':
        $form_state['redirect'] = 'node/' . $form_state['values']['nid'];
        break;
      case 'global':
      default:
        break;
    }
  }
}

/**
 * Submit handler for the product class form for default Variable Price features.
 */
function uc_atctweaks_product_class_submit($form, &$form_state) {
  if ($form_state['values']['default_atctweaks']) {
    $data = array(
      'cart_empty' => $form_state['values']['cart_empty'],
      'redirect' => $form_state['values']['redirect'],
    );

    variable_set('ucatc_class_def_' . $form_state['values']['pcid'], serialize($data));
  }
  else {
    variable_del('ucatc_class_def_' . $form_state['values']['pcid']);
  }
}

/**
 * Implements hook_node_insert().
 * Inserts add to cart tweak product feature on product node creation.
 */
function uc_atctweaks_node_insert($node) {
  if (uc_product_is_product($node)) {
    $data = variable_get('ucatc_class_def_' . $node->type, array());

    // If the product class has default Add to Cart Tweaks...
    if ($data) {
      // Prepare the data as if it were from a form submission.
      $data = unserialize($data);
      $data['nid'] = $node->nid;
      $data['pfid'] = '';
      $form_state = array('values' => $data);

      // Add the feature to the product by spoofing the normal form submission.
      uc_atctweaks_feature_form_submit(array(), $form_state);
    }
  }
}

/**
 * Implements hook_uc_product_feature().
 */
function uc_atctweaks_uc_product_feature() {
  $features = array();

  $features[] = array(
    'id' => 'atctweaks',
    'title' => t('Add to cart tweaks'),
    'callback' => 'uc_atctweaks_feature_form',
    'delete' => 'uc_atctweaks_feature_delete',
    'multiple' => FALSE,
  );

  return $features;
}

/**
 * Settings form for individual Add to Cart Tweaks.
 */
function uc_atctweaks_feature_form($form, &$form_state, $node, $feature) {
  // Load the Add to Cart Tweaks specific to this product.
  if (!empty($feature)) {
    $atctweaks_feature = db_query('SELECT * FROM {uc_atctweaks_products} WHERE pfid = :pfid', array(':pfid' => $feature['pfid']))->fetchObject();
  }
  else {
    $atctweaks_feature = new stdClass();
    $atctweaks_feature->pfid = '';
    $atctweaks_feature->cart_empty = FALSE;
    $atctweaks_feature->redirect = 'global';
  }

  $form['nid'] = array(
    '#type' => 'value',
    '#value' => $node->nid,
  );
  $form['pfid'] = array(
    '#type' => 'value',
    '#value' => $atctweaks_feature->pfid,
  );

  $form += _uc_atctweaks_feature_form($atctweaks_feature);

  return $form;
}

function _uc_atctweaks_feature_form($atctweaks_feature = FALSE) {
  $form = array();

  $form['cart_empty'] = array(
    '#type' => 'checkbox',
    '#title' => t('Empty the shopping cart of all other items when this product is added to it.'),
    '#default_value' => $atctweaks_feature ? $atctweaks_feature->cart_empty : FALSE,
  );
  $form['redirect'] = array(
    '#type' => 'radios',
    '#title' => t('Add to cart form redirect'),
    '#options' => array(
      'global' => t('Global default'),
      'cart' => t('Cart view page'),
      'checkout' => t('Checkout form'),
      'none' => t('No redirect'),
    ),
    '#default_value' => $atctweaks_feature ? $atctweaks_feature->redirect : 'global',
  );

  return $form;
}

/**
 * @see uc_atctweaks_feature_form()
 */
function uc_atctweaks_feature_form_submit($form, &$form_state) {
  // Build an array of Add to Cart Tweaks data from the form submission.
  $atctweaks_data = array(
    'pfid' => $form_state['values']['pfid'],
    'cart_empty' => $form_state['values']['cart_empty'],
    'redirect' => $form_state['values']['redirect'],
  );

  // Build the product feature description.
  $tweaks_form = _uc_atctweaks_feature_form();

  $description = array(
    t('<b>Add to cart form redirect:</b> @redirect', array('@redirect' => $tweaks_form['redirect']['#options'][$atctweaks_data['redirect']])),
  );

  if ($atctweaks_data['cart_empty']) {
    $description[] = t('The cart will be emptied prior to adding this item to it.');
  }

  // Save the basic product feature data.
  $data = array(
    'pfid' => $atctweaks_data['pfid'],
    'nid' => $form_state['values']['nid'],
    'fid' => 'atctweaks',
    'description' => implode('<br />', $description),
  );

  $form_state['redirect'] = uc_product_feature_save($data);

  $atctweaks_data['pfid'] = $data['pfid'];

  // Insert or update the data in the Variable Price products table.
  $key = array();
  if ($vpid = _uc_atctweaks_get_vpid($atctweaks_data['pfid'])) {
    $key = 'vpid';
    $atctweaks_data['vpid'] = $vpid;
  }

  drupal_write_record('uc_atctweaks_products', $atctweaks_data, $key);
}

/**
 * Add to Cart Tweaks product feature delete function.
 */
function uc_atctweaks_feature_delete($feature) {
  db_delete('uc_atctweaks_products')
    ->condition('pfid', $feature['pfid'])
    ->execute();
}

/**
 * Load the product feature data for a given node.
 */
function uc_atctweaks_product_load($nid) {
  return db_query('SELECT atc.* FROM {uc_product_features} AS pf
                   LEFT JOIN {uc_atctweaks_products} AS atc ON pf.pfid = atc.pfid
                   WHERE pf.fid = :pf_fid AND pf.nid = :pf_nid',
                   array(':pf_fid' => 'atctweaks', ':pf_nid' => $nid))->fetchObject();
}

/**
 * Gets a uc_atctweaks id from a product feature id.
 */
function _uc_atctweaks_get_vpid($pfid) {
  return db_query('SELECT vpid FROM {uc_atctweaks_products} WHERE pfid = :pfid', array(':pfid' => $pfid))->fetchField();
}
