<?php

/**
 * Implements hook_load_menu().
 */
function commerce_billy_mail_menu() {
  $items['admin/commerce/config/billy-invoice/billy-mail'] = array(
    'title' => 'Billy Mail',
    'description' => 'Configure Commerce Billy Mail settings.',
    'access arguments' => array('administer site configuration'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('commerce_billy_mail_settings_form'),
    'file' => 'commerce_billy_mail.admin.inc');
  $items['admin/commerce/orders/%commerce_order/resend-pdf-invoice'] = array(
    'title' => 'Resend invoice mail',
    'page callback' => 'commerce_billy_mail_resend_page',
    'page arguments' => array(3),
    'access callback' => 'commerce_billy_mail_resend_access',
    'access arguments' => array(3),
    'type' => MENU_LOCAL_ACTION,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'weight' => 10,
    'file' => 'commerce_billy_mail.module',
    'file path' => drupal_get_path('module', 'commerce_billy_mail') . '/',
  );
  return $items;
}

function commerce_billy_mail_permission() {
  return array(
    'commerce_billy_mail_resend_invoice_mail' => array(
      'title' => t('Resend invoice mail'),
      'description' => t('Resend invoice mails from the order details view. Requires further conditions besides this permission (e.g. order state & order access).'),
    ),
  );
}

/**
 * Access callback for the resending the invoice mail.
 *
 * Deny access if order is not in status 'invoiced' or the current user does not
 * have view access to the order itself.
 * Furthermore admins can access 'canceled' orders (credit memo).
 */
function commerce_billy_mail_resend_access($order) {
  return commerce_billy_pdf_view_access($order) && user_access('commerce_billy_mail_resend_invoice_mail');
}

function _commerce_billy_mail_mimemail_send_order_invoice($order) {
  if (empty($order) || !is_object($order)) {
    drupal_set_message('Given order was empty or no object. No invoice was sent!', 'error');
    watchdog('commerce_billy_mail', 'Given order was empty or no object. No invoice was sent!', WATCHDOG_ERROR);
    return false;
  }

  // Order user (customer):
  $order_account_uid = $order->uid;
  $order_account = user_load($order_account_uid);
  $order_account_language = user_preferred_language($order_account);

  // Sender:
  $from = variable_get('commerce_billy_mail_from', '');

  // Content:
  $subject = variable_get('commerce_billy_mail_subject', '');
  $body = variable_get('commerce_billy_mail_body', ''); //body text in HTML format
  // Attachments:
  if (variable_get('commerce_billy_mail_attach_pdf_invoice', TRUE)) {
    $attachments = _commerce_billy_mail_get_attachments($order);
  }
  else {
    $attachments = array();
  }

  // Replace tokens
  $subject = token_replace($subject, array('user' => $order_account, 'commerce_order' => $order), array('language' => $order_account_language));
  $body = token_replace($body, array('user' => $order_account, 'commerce_order' => $order), array('language' => $order_account_language));

  // Set values in mail:
  $plaintext = variable_get('commerce_billy_mail_plaintext', FALSE);
  $params = array(
    'subject' => $subject,
    'body' => $body,
    'plain' => !empty($plaintext),
    'attachments' => $attachments,
    'headers' => array(
      'Cc' => trim(variable_get('commerce_billy_mail_cc', '')),
      'Bcc' => trim(variable_get('commerce_billy_mail_bcc', '')),
    ),
    'context' => array(
      'subject' => $subject,
      'body' => $body,
      'order' => $order,
    ),
  );
  // Remove the Bcc and Cc headers if they are empty, else this will crash phpmailer and maybe other modules.
  if (empty($params['headers']['Cc'])) {
    unset($params['headers']['Cc']);
  }
  if (empty($params['headers']['Bcc'])) {
    unset($params['headers']['Bcc']);
  }

  $mailkey = 'commerce_billy_mimemail_send_order_invoice';
  $send = true;
  // Send!
  $message = drupal_mail('commerce_billy_mail', $mailkey, $order_account->mail, $order_account_language, $params, $from, $send);
  if (!$message['result']) {
    watchdog('commerce_billy_mail', 'Error sending e-mail (from %from to %to).', array('%from' => $message['from'], '%to' => $message['to']), WATCHDOG_ERROR);
    drupal_set_message(t('Unable to send e-mail. Contact the site administrator if the problem persists.'), 'error');
    return FALSE;
  }
  return TRUE;
}

function commerce_billy_mail_mail($key, &$message, $params) {
  switch ($key) {
    default:
      if (isset($params['subject'])) {
        $message['subject'] = $params['subject'];
      }
      if (isset($params['body'])) {
        $message['body'][] = $params['body'];
      }
      if (isset($params['headers']) && is_array($params['headers'])) {
        $message['headers'] = array_merge($message['headers'], $params['headers']);
      }
      if (isset($params['plain'])) {
        $message['plain'] = $params['plain'];
      }
      break;
  }
}

function _commerce_billy_mail_get_attachments($order) {
  $attachments = array();

  list($html, $filename) = commerce_billy_mail_pdf_prepare($order);
  $pdf_path = commerce_billy_mail_pdf_create($html, $filename);
  // Add a secong prefix slash as quickfix for this issue: https://drupal.org/node/760080
  // TODO - Solve cleanly, when the mimemail bug is fixed. TODO
  $pdf_path = '/' . $pdf_path;
  $attachments[] = array(
    'filepath' => $pdf_path, //you have to use relative paths.
    'filename' => basename($pdf_path), // can use any alias name here
    'filemime' => 'application/pdf', // mime file type
    'list' => TRUE,
  );

  // TODO - Delete files after sending!
  return $attachments;
}

function commerce_billy_mail_pdf_prepare($order) {
  // Currently a copy of the first part of
  // See: https://drupal.org/node/2099283
  if (module_exists('commerce_billy_pdf')) {
    module_load_include('module', 'commerce_billy_pdf');
  }
  else {
    drupal_set_message('PDF email attachment could not be createt, because commerce_billy_pdf is disabled.', 'error');
  }
  $html = commerce_billy_pdf_html($order);

  $filename = preg_replace('/[^a-z0-9]/', '_', drupal_strtolower('invoice_' . $order->order_number)) . '__' . time() . '.' . mt_rand(1, 999999999) . '.pdf';
  if (module_exists('transliteration')) {
    $filename = transliteration_clean_filename($filename);
  }
  return array(
    $html,
    $filename,
  );
}

/**
 * Transforms HTML to PDF and returns its path.
 */
function commerce_billy_mail_pdf_create($html, $filename) {
  $dompdf = commerce_billy_pdf_prepare_dompdf($html, $filename);
  $htmlData = $dompdf->output();

  // write the pdf content within that file.
  $file = file_save_data($htmlData, 'temporary://' . $filename);
  if ($file === FALSE) {
    drupal_set_message('Invoice PDF could not be saved correctly.', 'error');
  }

  // New part end
  return file_stream_wrapper_get_instance_by_uri($file->uri)->realpath();
}

/**
 * Page callback for pdf invoice mail resend.
 *
 * @param StdObject $order Commerce Order object
 */
function commerce_billy_mail_resend_page($order) {
  $success = _commerce_billy_mail_mimemail_send_order_invoice($order);
  if ($success) {
    drupal_set_message(t('The PDF invoice has been resent successfully.'), 'status');
  }
  else {
    drupal_set_message(t('The PDF could not be resent.'), 'error');
  }
  drupal_goto('admin/commerce/orders/' . $order->order_id);
}