<?php

/**
 * @file
 * Allows store owners to create links to add products to carts and send
 * customers on to checkout.
 */


/**
 * Implements hook_help().
 */
function uc_cart_links_help($section = 'admin/help#uc_cart_links', $arg = NULL) {
  switch ($section) {
    case 'admin/store/settings/cart-links':
      if (module_exists('help')) {
        return '<p>' . t('<a href="!url">View the help page</a> to learn how to create Cart Links.', array('!url' => url('admin/help/uc_cart_links'))) . '</p>';
      }
      break;

    case 'admin/help#uc_cart_links':
    case 'admin/help/cart-links':
      module_load_include('inc', 'uc_cart_links', 'uc_cart_links.admin');
      $build = uc_cart_links_creation_help();
      return drupal_render($build);
  }
}

/**
 * Implements hook_menu().
 */
function uc_cart_links_menu() {
  $items['admin/store/settings/cart-links'] = array(
    'title' => 'Cart links',
    'description' => 'Configure and craft special links to add products directly to the cart.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('uc_cart_links_settings_form'),
    'access arguments' => array('administer cart links'),
    'file' => 'uc_cart_links.admin.inc',
  );
  $items['admin/store/reports/cart-links'] = array(
    'title' => 'Cart links',
    'description' => 'Track clicks through Cart Links.',
    'page callback' => 'uc_cart_links_report',
    'access arguments' => array('view cart links report'),
    'file' => 'uc_cart_links.admin.inc',
  );
  $items['cart/add/%'] = array(
    'title' => 'Add to cart',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('uc_cart_links_form', 2),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'uc_cart_links.pages.inc',
  );

  return $items;
}

/**
 * Implements hook_permission().
 */
function uc_cart_links_permission() {
  return array(
    'administer cart links' => array(
      'title' => t('Administer cart links'),
    ),
    'view cart links report' => array(
      'title' => t('View cart links report'),
    ),
  );
}

/**
 * Implements hook_uc_add_to_cart().
 */
function uc_cart_links_uc_add_to_cart($nid, $qty, $data) {
  if (user_access('administer cart links') &&
      variable_get('uc_cart_links_add_show', FALSE)) {
    $cart_link = 'p' . $nid . '_q' . $qty;
    if (!empty($data['attributes'])) {
      foreach ($data['attributes'] as $attribute => $option) {
        if (is_array($option)) {
          // Checkbox options are stored in an array.
          foreach ($option as $oid => $ovalue) {
            if ($ovalue != 0) {
              $cart_link .= '_a' . $attribute . 'o' . $oid;
            }
          }
        }
        else {
          // Textfield, Select, or Radio options.
          $cart_link .= '_a' . $attribute . 'o' . $option;
        }
      }
    }
    drupal_set_message(t('Cart Link product action: @cart_link', array('@cart_link' => $cart_link)));
  }
}
