<?php

/**
 * @file
 * Coupon with percentage field.
 */

/**
 * Implements hook_commerce_coupon_type_configure().
 */
function commerce_coupon_pct_commerce_coupon_type_configure($bundle, $reset = FALSE) {
  // Skip all $bundles except the pct coupon type
  if ($bundle != 'commerce_coupon_pct') {
    return;
  }

  $entity_type = 'commerce_coupon';

  // If a field type we know should exist isn't found, clear the Field cache.
  if (!field_info_field_types('commerce_price')) {
    field_cache_clear();
  }

  // Look for or add the specified percentage amount.
  $field_name = 'commerce_coupon_percent_amount';
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle);

  if (empty($field) || $reset) {
    $field_data = array(
      'field_name' => $field_name,
      'type' => 'number_decimal',
      'label' => t('Percentage Amount'),
      'cardinality' => 1,
      'entity_types' => array($entity_type),
      'translatable' => FALSE,
      'locked' => FALSE,
      'settings' => array(
        'decimal_separator' => '.',
        'precision' => '10',
        'scale' => '2',
      ),
    );

    if (empty($field)) {
      $field = field_create_field($field_data);
    }
    else {
      $field = field_update_field($field_data);
    }
  }

  if (empty($instance) || $reset) {
    $instance_data = array(
      'field_name' => $field_name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
      'label' => t('Percentage Amount'),
      'required' => TRUE,
      'display' => array(),
      'settings' => array(
        'min' => '0',
        'max' => '100',
        'suffix' => '%',
      ),
    );

    if (empty($instance)) {
      field_create_instance($instance_data);
    }
    else {
      field_update_instance($instance_data);
    }
  }
}

/**
 * Implements hook_commerce_coupon_granted_amount_alter().
 *
 * Gets the right amount value to display it in the coupon "log" view.
 */
function commerce_coupon_pct_commerce_coupon_granted_amount_alter(&$amount, $coupon, $order) {
  // Get the price component.
  if ($coupon->type == 'commerce_coupon_pct') {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $coupon_wrapper = entity_metadata_wrapper('commerce_coupon', $coupon);

    $amount = 0;
    $components = commerce_price_component_load($order_wrapper->commerce_order_total->value(), $coupon_wrapper->price_component_name->value());
    foreach ($components as $component) {
      $amount += $component['price']['amount'] * -1;
    }

    $amount = commerce_currency_format($amount, $order_wrapper->commerce_order_total->currency_code->value(), $coupon);
  }
}
