<?php

/**
 * Implements hook_commerce_payment_method_info().
 */
function commerce_kickstart_payment_commerce_payment_method_info() {
  $payment_methods = array();

  $payment_methods['commerce_kickstart_payment'] = array(
    'title' => t('Kickstart example payment'),
    'description' => t('Demonstrates credit card payment during checkout and serves as a development example.'),
    'active' => TRUE,
  );

  return $payment_methods;
}

/**
 * Payment method callback: submit form.
 */
function commerce_kickstart_payment_submit_form($payment_method, $pane_values, $checkout_pane, $order) {
  module_load_include('inc', 'commerce_payment', 'includes/commerce_payment.credit_card');
  $fields = array(
    'type' => array(
      'visa',
      'mastercard',
      'amex',
    ),
  );
  $default = array(
    'number' => '4111111111111111',
  );
  return commerce_payment_credit_card_form($fields, $default);
}

/**
 * Payment method callback: submit form validation.
 */
function commerce_kickstart_payment_submit_form_validate($payment_method, $pane_form, $pane_values, $order, $form_parents = array()) {
  // Validate the credit card fields.
  module_load_include('inc', 'commerce_payment', 'includes/commerce_payment.credit_card');
  $settings = array(
    'form_parents' => array_merge($form_parents, array('credit_card')),
  );

  if (!commerce_payment_credit_card_validate($pane_values['credit_card'], $settings)) {
    return FALSE;
  }
}

/**
 * Payment method callback: submit form submission.
 */
function commerce_kickstart_payment_submit_form_submit($payment_method, $pane_form, $pane_values, $order, $charge) {
  $order->data['commerce_kickstart_payment'] = $pane_values;

  commerce_kickstart_payment_transaction($payment_method, $order, $charge);
}

/**
 * Creates an example payment transaction for the specified charge amount.
 *
 * @param $payment_method
 *   The payment method instance object used to charge this payment.
 * @param $order
 *   The order object the payment applies to.
 * @param $charge
 *   An array indicating the amount and currency code to charge.
 * @param $name
 *   The name entered on the submission form.
 */
function commerce_kickstart_payment_transaction($payment_method, $order, $charge) {
  $transaction = commerce_payment_transaction_new('commerce_kickstart_payment', $order->order_id);
  $transaction->instance_id = $payment_method['instance_id'];
  $transaction->amount = $charge['amount'];
  $transaction->currency_code = $charge['currency_code'];
  $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
  $transaction->message = 'Name: @name';
  $transaction->message_variables = array('@name' => 'Kickstart example payment');

  commerce_payment_transaction_save($transaction);
  return $transaction;
}
