<?php
/**
 * @file
 * Discount coupon recurring payment integration.
 *
 * Allows coupons to apply to recurring payments
 */

/**
 * Implements hook_module_implements_alter().
 *
 * Ensures that coupons are applied to recurring orders last.
 */
function uc_coupon_recurring_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'recurring_renewal_pending') {
    $group = $implementations['uc_coupon_recurring'];
    unset($implementations['uc_coupon_recurring']);
    $implementations['uc_coupon_recurring'] = $group;
  }
}

/**
 * Implements hook_form_FORM_ID_alter() for the uc_coupon_add_form.
 */
function uc_coupon_recurring_form_uc_coupon_add_form_alter(&$form, &$form_state) {
  $active = !empty($form['#uc_coupon']->data['recurring_payments']);
  $form['uc_coupon_recurring'] = array(
    '#type' => 'fieldset',
    '#title' => t('Recurring payment settings'),
    '#description' => t('Controls the way this coupon is applied to recurring payments.'),
    '#collapsible' => TRUE,
    '#collapsed' => !$active,
  );
  $form['uc_coupon_recurring']['recurring_payments'] = array(
    '#type' => 'textfield',
    '#title' => t('Maximum number of recurring payments to discount'),
    '#description' => t('Specify the maximum number of payments (after the initial order) to which the discount should be applied. Leave blank (or enter 0) to apply only to the initial order. Enter -1 to apply to all recurring payments. Please note this will be ignored if recurring payments are processed via Paypal WPS.'),
    '#default_value' => !empty($form['#uc_coupon']->data['recurring_payments']) ? $form['#uc_coupon']->data['recurring_payments'] : '',
  );
  $form['#entity_builders'][] = 'uc_coupon_recurring_build_coupon';
}

/**
 * Entity builder callback.
 */
function uc_coupon_recurring_build_coupon($type, $coupon, $form, $form_state) {
  if ($type == 'uc_coupon') {
    if (!empty($form_state['values']['recurring_payments'])) {
      $coupon->data['recurring_payments'] = $form_state['values']['recurring_payments'];
    }
  }
}

/**
 * Implements hook_recurring_renewal_pending().
 *
 * Reapplies any coupons that were originally valid for this order.
 */
function uc_coupon_recurring_recurring_renewal_pending(&$order, $fee) {
  $coupons = array();
  if (!empty($order->data['coupons'])) {
    $codes = array_keys($order->data['coupons']);
    $order->data['coupons'] = array();
    foreach ($codes as $code) {
      $coupon = uc_coupon_find($code);
      $limit = empty($coupon->data['recurring_payments']) ? 0 : $coupon->data['recurring_payments'];
      if ($coupon && ($limit < 0 || $limit > $fee->charged_intervals)) {
        uc_coupon_prepare($coupon, $code, uc_coupon_calculate_discounts($coupon, $order));
        $coupons[] = $coupon;
        $order->data['coupons'][$code] =  $coupon->discounts;
      }
    }
    if (!empty($coupons)) {
      uc_coupon_apply_to_order($order, $coupons);
    }
  }
}