<?php
/**
 * @file
 * Code for the Abbey Lodge Invoices feature.
 */

include_once 'abbey_lodge_invoices.features.inc';

/**
 * Implements hook_date_formats().
 */
function abbey_lodge_invoices_date_formats() {
  $formats = array();
  $types = array(
    'abbey_lodge_invoice' => 'd M Y',
  );
  foreach ($types as $type => $format) {
    $formats[] = array(
      'type' => $type,
      'format' => $format,
      'locales' => array(),
    );
  }
  return $formats;
}

/**
 * Implements hook_date_format_types().
 */
function abbey_lodge_invoices_date_format_types() {
  return array(
    'abbey_lodge_invoice' => t('Abbey Lodge Invoice'),
  );
}

/**
 * Implements hook_block_info().
 */
function abbey_lodge_invoices_block_info() {
  $blocks = array();
  $blocks['abbey_lodge_invoice_email'] = array(
    'info' => t('Invoice Email Form'),
  );
  return $blocks;
}
/**
 * Implements hook_block_view().
 */
function abbey_lodge_invoices_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'abbey_lodge_invoice_email':
      $block['subject'] = t('Email Invoice');
      $block['content'] = drupal_get_form('abbey_lodge_invoices_email_form');
      break;
  }
  return $block;
}

function abbey_lodge_invoices_email_form($form, &$form_state) {
  $node = menu_get_object('node');
  $customer = user_load($node->uid);

  $form['invoice_nid'] = array(
    '#type' => 'hidden',
    '#value' => $node->nid,
  );
  
  $form['email'] = array(
    '#title' => t('Email'),
    '#type' => 'textfield',
    '#default_value' => $customer->mail,
  );


  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Email Invoice'),
  );

  return $form;
}

function abbey_lodge_invoices_email_form_submit($form, &$form_state) {
  $invoice_nid = $form_state['values']['invoice_nid'];
  $mail_to = $form_state['values']['email'];
  $mail_from = variable_get('site_mail', '');

  $node = node_load($invoice_nid);
  $view = node_view($node, 'PDF');
  $html = drupal_render($view);

  $pdf_string = pdf_using_mpdf_api($html, 'name_of_file', array('dest' => 'S'));
  $attachment = 	array(
    'filecontent' => $pdf_string,
    'filename' => 'Invoice.pdf',
    'filemime' => 'application/pdf',
  );

  $module = 'abbey_lodge_invoices';
  $key = 'pdf_attach';
  $language = language_default();
  $send = TRUE;

  $params = array(
    'subject' => $node->title,
    'body' => t('Attached is a copy of your invoice.'),
    'attachment' => $attachment,
  );

  $result = drupal_mail($module, $key, $mail_to, $language, $params, $mail_from, $send);
}

/**
 * Implements hook_mail().
 */
function abbey_lodge_invoices_mail($key, &$message, $params) {
  $message['subject'] = $params['subject'];
  $message['body'][] = $params['body'];

  // Add attachment when available.
  if (isset($params['attachment'])) {
    $message['params']['attachments'][] = $params['attachment'];
  }
}

/**
 * Implements hook_field_extra_fields().
 */
function abbey_lodge_invoices_field_extra_fields() {
  $extra = array();
  // Define extra invoice fields
  $extra['node']['abbey_lodge_invoice'] = array(
    'display' => array(
      'invoice_subtotal' => array(
        'label' => t('Subtotal'),
        'description' => t('Invoice Subtotal'),
        'weight' => 0,
      ),
      'invoice_vat' => array(
        'label' => t('VAT'),
        'description' => t('Invoice VAT'),
        'weight' => 1,
      ),
      'invoice_total' => array(
        'label' => t('Total'),
        'description' => t('Invoice Total'),
        'weight' => 2,
      ),
    ),
  );
  // Define extra invoice line item fields
  $extra['field_collection_item']['field_invoice_line_item'] = array(
    'display' => array(
      'invoice_line_item_total' => array(
        'label' => t('Total'),
        'description' => t('Line Item Subtotal'),
        'weight' => 0,
      ),
    ),
  );

  return $extra;
}

/**
 * Implements hook_entity_view().
 */
function abbey_lodge_invoices_entity_view($entity, $type, $view_mode, $langcode) {
  $currency_code = 'GBP';
  $vat_rate = 0.2;
  if($type == 'node' && $entity->type == 'abbey_lodge_invoice') {
    $subtotal =  $vat = $total = 0;
    $collection_ids = array_column($entity->field_invoice_line_item[LANGUAGE_NONE], 'value');
    $line_items = entity_load('field_collection_item', array_values($collection_ids));
    foreach($line_items as $line_item) {
      $total = $total + $line_item->field_invoice_li_price['und'][0]['amount'] * $line_item->field_invoice_li_quantity['und'][0]['value'];
    }

    $subtotal = ($total / (1 + $vat_rate));
    $vat = $total - $subtotal;

    $entity->content['invoice_subtotal'] = array(
      '#markup' => commerce_currency_format($subtotal, $currency_code),
    );
    $entity->content['invoice_vat'] = array(
      '#markup' => commerce_currency_format($vat, $currency_code),
    );
    $entity->content['invoice_total'] = array(
      '#markup' => commerce_currency_format($total, $currency_code),
    );
  }

  if($type == 'field_collection_item' && $entity->field_name == 'field_invoice_line_item') {
    $unit = $entity->field_invoice_li_price['und'][0]['amount'];
    $qty = $entity->field_invoice_li_quantity['und'][0]['value'];
    $currency_code = $entity->field_invoice_li_price['und'][0]['currency_code'];
    $entity->content['invoice_line_item_total'] = array(
      '#title' => t('Total'),
      '#markup' => commerce_currency_format($unit * $qty, $currency_code),
      '#weight' => 5,
    );
  }

}
/**
 * Implements hook_node_insert().
 */
function abbey_lodge_invoices_node_insert($node) {
  static $cache;

  if (!isset($cache[$node->nid])) {
    if (!empty($node->field_customer_order[LANGUAGE_NONE])) {
      /* @var EntityDrupalWrapper $entity */
      $entity = entity_metadata_wrapper('node', $node);
      if ($entity->field_customer_order->value()) {
        $cache[$node->nid] = TRUE;
        foreach ($entity->field_customer_order->commerce_line_items as $line_item) {
          /* @var FieldCollectionItemEntity $fc_item */
          $fc_item = entity_create('field_collection_item', array('field_name' => 'field_invoice_line_item'));
          $fc_item->setHostEntity('node', $entity->raw());

          /* @var EntityDrupalWrapper $fc_wrapper */
          $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc_item);


          if ($line_item->type->value() == 'rooms_booking') {
            $fc_wrapper->field_invoice_li_date->set($line_item->rooms_booking_dates->value->value());
          }
          $fc_wrapper->field_invoice_li_description->set($line_item->line_item_label->value());
          $fc_wrapper->field_invoice_li_price->set($line_item->commerce_unit_price->value());
          $fc_wrapper->field_invoice_li_quantity->set($line_item->quantity->value());

          $fc_wrapper->save();
        }
        $entity->field_customer_order->set(NULL);
      }
      $entity->save();
      drupal_goto('node/' . $node->nid . '/edit');
    }
  }
}

/**
 * Implements hook_node_update().
 */
function abbey_lodge_invoices_node_update($node) {
  abbey_lodge_invoices_node_insert($node);
}

/**
 * Implements hook_module_implements_alter().
 */
function abbey_lodge_invoices_module_implements_alter(&$implementations, $hook) {
  // auto_nodetitle has two hooks for settings the node title, we need to disable
  // the node_submit and then reorder the node_presave one so it gets called
  // after the serial modules presave. This way the invoive number is available
  if ($hook == 'node_submit' && isset($implementations['auto_nodetitle'])) {
    unset($implementations['auto_nodetitle']);
  }
  if ($hook == 'node_presave' && isset($implementations['auto_nodetitle'])) {
    $auto_nodetitle_implementation = $implementations['auto_nodetitle'];
    unset($implementations['auto_nodetitle']);
    $implementations['auto_nodetitle'] = $auto_nodetitle_implementation;
  }
}
