<?php
define('COMMERCE_COMPONENT_PRICE_ORDER','commerce_component_price_order');
define('COMMERCE_COMPONENT_PRICE_SETTINGS','commerce_component_price_settings');
/**
 * Alter ommerce_price component before printing
 * This will change weight and titles or components
 **/   
function commerce_price_extra_commerce_price_formatted_components_alter(&$components, $item, $entity) {
  
  $types = variable_get(COMMERCE_COMPONENT_PRICE_ORDER,array());
  foreach ($components as $name => $component) {
    if (array_key_exists($name,$types)) {
       $components[$name]['weight'] = $types[$name]['weight'];
    } 
    if (preg_match('/^(discount_)/', $name)) {
      $vars = variable_get(COMMERCE_COMPONENT_PRICE_SETTINGS,array());
      $components[$name]['title'] = $vars[$name]['title'];
      if (array_key_exists('discount',$types)) {
         $components[$name]['weight'] = $types['discount']['weight'];
      } 
    }
  }
}

/**
 * Implements hook_form_<FORM>_alter
 * 
 * Add setting to print discount in its own line
 **/    
function commerce_price_extra_form_commerce_discount_form_alter(&$form, &$form_state,$form_id) {
  $commerce_discount = $form_state['commerce_discount'];
  $vars = variable_get(COMMERCE_COMPONENT_PRICE_SETTINGS,array());
  $form['show_in_own_line'] = array(
    '#title' => t('Show this discount in its own line'),
    '#type' => 'radios',
    '#options' => array(
      1 => t('Yes'),
      0 => t('No'),
    ),
    '#required' => FALSE,
    '#default_value' => (array_key_exists($commerce_discount->name, $vars) ? $vars[$commerce_discount->name]['show_in_own_line'] :0),
  );
  $form["#submit"][] = 'commerce_price_extra_form_commerce_discount_form_submit'; 

}

/**
 * Submit callback for commerce_discount_form
 * Store settings to variables
 **/    
function commerce_price_extra_form_commerce_discount_form_submit($form, $form_state) {
  $commerce_discount = $form_state['commerce_discount'];
  $vars = variable_get(COMMERCE_COMPONENT_PRICE_SETTINGS,array());
  $vars[$commerce_discount->name] = array("title" => $form_state['values']['label'], "show_in_own_line" => $form_state['values']['show_in_own_line']); 
  variable_set(COMMERCE_COMPONENT_PRICE_SETTINGS, $vars);
}


/**
 * Implements hook_entity_presave
 * 
 * Change titles and line item types for discount in own line 
 * */    
function commerce_price_extra_entity_presave($entity, $type) {
  $vars = variable_get(COMMERCE_COMPONENT_PRICE_SETTINGS,array());
  if (($type == "commerce_line_item" && $entity->type == "commerce_discount") || ($type == "commerce_order" && $entity->type == "commerce_order")) {
    if ($entity->type == "commerce_discount") {
        $field = &$entity->commerce_unit_price;
    }
    else {
       $field = &$entity->commerce_order_total;
    } 
    foreach ($field['und'][0]['data']['components'] as $key => $component) {
        if (is_array($component['price']['data']) && array_key_exists("discount_name", $component['price']['data'])) {
            $name = $component['price']['data']['discount_name'];
            if (array_key_exists($name, $vars) && $vars[$name]['show_in_own_line']) {
              $field['und'][0]['data']['components'][$key]['name'] = $component['price']['data']['discount_name'];
              $entity->commerce_total['und'][0]['data']['components'][$key]['name'] = $component['price']['data']['discount_name'];
            }
        }
    }
  }
 
}

/**
 * Implements hook_form_<FORM>_alter
 * 
 * Add draggable table to cart pane to reorder component_price components
 **/    

function commerce_price_extra_form_commerce_checkout_pane_settings_form_alter(&$form, &$form_state) {
  if ($form['checkout_pane']['#value']['base'] == 'commerce_cart_contents_pane') {
    $form['settings']['reorder_price_components'] = array(
      '#type' => 'item',
      '#title' => 'Order price components',
      '#tree' => TRUE,
      '#weight' => 5,
      '#theme' => 'reorder_price_components_table'
    );
    $types = commerce_price_component_types();  
    $orders = variable_get(COMMERCE_COMPONENT_PRICE_ORDER,array());
    foreach ($orders as $name => $order) {
        $types[$name]['weight'] = $order['weight'];
    }
    uasort($types,"drupal_sort_weight");  
    foreach($types as $key => $component) {
      $form['settings']['reorder_price_components'][$key]['name'] = array(
      '#markup' => $component['title'],
    );
    $form['settings']['reorder_price_components'][$key]['weight'] = array(
      '#type' => 'textfield',
      '#default_value' => $component['weight'],
      '#size' => 3,
      '#attributes' => array('class' => array('rank-weight')), // needed for table dragging
    );
    }
   $form['submit']['#submit'][] = "commerce_price_extra_form_commerce_cart_contents_pane_submit";
  }
}

/**
 * Submit callback for  commerce_checkout_pane_settings_form
 * Store new order in variables
 **/   
function commerce_price_extra_form_commerce_cart_contents_pane_submit(&$form, &$form_state) {
    $types = $form_state['values']['reorder_price_components'];
    uasort($types,"drupal_sort_weight");
    variable_set(COMMERCE_COMPONENT_PRICE_ORDER,$types);
}

/**
 *Implements hook_theme
 **/ 
function commerce_price_extra_theme($existing, $type, $theme, $path) {
  return array(
    'reorder_price_components_table' => array(
      'render element' => 'element'
    ),
  );
}

/**
 * Theme for rendering component prices ordering
 **/ 
function theme_reorder_price_components_table($vars) {
  $element = $vars['element'];
  drupal_add_tabledrag('reorder_price_form', 'order', 'sibling', 'rank-weight'); // needed for table dragging
  
  $header = array(
    'name' => t('Name'), 
    'weight' => t('Rank'),
  );
  
  $rows = array();
  foreach (element_children($element) as $key) {
    $row = array();
    
    $row['data'] = array();
    foreach ($header as $fieldname => $title) {
      $row['data'][] = drupal_render($element[$key][$fieldname]);
      $row['class'] = array('draggable'); // needed for table dragging
    }
    $rows[] = $row;
  }
  
  return theme('table', array(
    'header' => $header, 
    'rows' => $rows,
    'attributes' => array('id' => 'reorder_price_form'), // needed for table dragging
  ));
}
