<?php

/**
 * @file
 * Primary module hooks for Commerce TouchNet uPay module.
 */

/**
 * Implements hook_workflows_alter().
 */
function commerce_touchnet_upay_workflows_alter(array &$workflows) {
  foreach ($workflows as $key => $workflow) {
    // Let canceled state go to completed state in every order workflow.
    if ($workflow['group'] === 'commerce_order') {
      foreach ($workflow['transitions'] as $transition_key => $transition) {
        if ($transition['to'] === 'completed') {
          $from = $workflows[$key]['transitions'][$transition_key]['from'];
          $from[] = 'canceled';
          $workflows[$key]['transitions'][$transition_key]['from'] = array_unique($from);
        }
      }
    }

    // Add refunded state to every order workflow.
    switch ($key) {
      case 'order_default':
      case 'order_default_validation':
        $from_transition = ['completed'];
        break;

      case 'order_fulfillment':
      case 'order_fulfillment_validation':
        $from_transition = ['fulfillment', 'completed'];
        break;

      default:
        $from_transition = '';
        break;
    }
    if ($from_transition) {
      $workflows[$key]['states']['refunded'] = ['label' => 'Refunded'];
      $workflows[$key]['transitions']['refund'] = [
        'label' => 'Refund order',
        'from' => $from_transition,
        'to' => 'refunded',
      ];
    }
  }
}