<?php

define("UNSUBSCRIVE_SECRET_KEY", 'k;Yj>+kZ@CHBJQDs*G=2!uRXE+4;)H(M');
define("UNSUBSCRIVE_SECRET_IV", 'F5a:~+EQAj#:>zazNWN6GP3JEWX75h-@');
define("UNSUBSCRIVE_ENCRYPT_METHOD", 'AES-256-CBC');
define("UNSUBSCRIVE_KEY",  hash('sha256', UNSUBSCRIVE_SECRET_KEY));
define("UNSUBSCRIVE_IV", substr(hash('sha256', UNSUBSCRIVE_SECRET_IV), 0, 4));

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mkbh_comment_form_comment_form_alter(&$form, &$form_state, $form_id) {
  unset($form['comment_body'][LANGUAGE_NONE][0]['value']['#title']);

  // For AJAX requests, remove the author's label.
  if (is_xml_http_request() && current_path() !== 'system/ajax') {
    unset($form['author']['_author']);
  } else {
    $author = &$form['author']['_author'];
    $author['#title'] = t('Logged in as');
    $author['#markup'] = strip_tags($author['#markup']);
  }

  // Set the texts for the button and textarea.
  $form['actions']['submit']['#value'] = t('Post comment');
  $form['comment_body'][LANGUAGE_NONE][0]['value']['#attributes']['placeholder'] = t('Write your comment here ...');
  unset($form['field_parent_original']);
}

/**
 * Implements hook_preprocess_HOOK().
 */
function mkbh_comment_preprocess_comment_wrapper(&$variables) {

  $parents = [];
  foreach ($variables['content']['comments'] as &$comment) {

    if (isset($comment['#comment']) && is_object($comment['#comment']) && !$comment['#comment']->pid) {
      if ($comment['#comment']->cid) {
        $parents[$comment['#comment']->cid] = $comment;
      }
    }
  }

  $all_comments = [];
  foreach ($parents as $p_cid => $parent) {
    foreach ($variables['content']['comments'] as $_comment) {

      if (isset($_comment['#comment']) && $_comment['#comment']->pid == $p_cid) {
        $all_comments[$p_cid][] = $_comment;
      }
    }

    if (isset($all_comments[$p_cid]) && is_array($all_comments[$p_cid])) {
      $sort = $all_comments[$p_cid];
      usort($sort, "_sort_comments");
      $all_comments[$p_cid] = $parent;
      $all_comments[$p_cid]['children'] = $sort;
    }
    else {
      $all_comments[$p_cid] = $parent;
    }
  }
  uasort($all_comments, "_sort_comments_reverse");

  $render_comments = [];
  $render_comments = $all_comments;
  $render_comments['#sorted'] = $variables['content']['comments']['#sorted'];
  $render_comments['pager'] =& $variables['content']['comments']['pager'];

  $variables['content']['comments'] = $render_comments;

}

/**
 * Implements hook_preprocess_HOOK().
 */
function mkbh_comment_preprocess_comment(&$variables) {

  // Unset links under comments for unauthorized users.
  if (!user_is_logged_in()) {
    unset($variables['content']['links']['comment']['#links']['comment_forbidden']);
  }

  // Variable for comment post date.
  $variables['comment_date'] = ucwords(format_date($variables['comment']->created, 'comment_date_format'));

  // Variable for comment post user.
  $variables['user_name'] = $variables['comment']->name;

  // Add user picture for posted comment.
  $user = user_load($variables['comment']->uid);
  $default_user_picture_path = drupal_get_path('theme', 'mkbh') . '/assets/images/svg/icon_signin.svg';
  $variables['comment_author_picture'] = theme_image([
    'style_name' => '60x60',
    'path' => empty($user->picture) ? $default_user_picture_path : $user->picture->uri,
    'attributes' => [
      'width' => '60',
      'height' => '60',
      'class' => empty($user->picture) ? 'default-user-avatar' : 'avatar',
    ],
  ]);

  // Add parent comment author name for reply comment.
  $parts_of_body = explode("|", $variables['comment']->comment_body[LANGUAGE_NONE][0]['value']);
  $variables['content']['comment_body'][0]['#markup'] = $parts_of_body[0];

  $parts = explode("|", $variables['comment']->subject);

  if (!empty($parts[1])) {
    $variables['comment']->parent_id = $parts[1];
  } elseif (!empty($parts_of_body[1])) {
    $variables['comment']->parent_name = $parts_of_body[1];
  }

  //Remove parent_name from comment_body.
  $variables['comment']->comment_body[LANGUAGE_NONE][0]['value'] = $parts[0];
  $variables['comment']->comment_body[LANGUAGE_NONE][0]['safe_value'] = $parts[0];

  //Added Like button into variables to pass into template.
  $vars = [
    'label_like' => "",
    'tips_like' => t("Jeg kan lide"),
    'tips_unlike' => t("Fjern min 'like'"),
    'label_dislike' => "",
    'tips_dislike' => "",
    'tips_undislike' => "",
  ];

  $variables['like_button'] = votinglike_output('comment', $variables['comment']->cid, FALSE, $vars);
}

/**
 * Generate two level hierarchy for comments.
 * Implements hook_comment_presave().
 */
function mkbh_comment_comment_presave($comment) {
  global $language ;
  $lang_name = $language->language ;
  $node = node_load($comment->nid);
  $data = [];
  $data['node_title'] = $node->title;

  if ($comment->pid) {
    $parent = comment_load($comment->pid);
    $comment->subject .= "|$parent->name";

    if ($parent && $parent->pid != 0) {

      $parent_parent = comment_load($parent->pid);
      $comment->original_parent_id = $comment->pid;
      $comment->pid = $parent_parent->cid;
    }

    $parent_comment_author = user_load($parent->uid);
    $comment_author = user_load($comment->uid);

    if ($parent_comment_author->field_unsubscribe[LANGUAGE_NONE][0]['value'] != 1) {

      if ($comment->uid != $parent_comment_author->uid) {

        $body = $comment->comment_body[LANGUAGE_NONE][0]['value'];

        $data['mail'] = $parent_comment_author->mail;
        $data['username'] = $comment_author->name;
        $data['comment'] = $body;
        $data['language'] = $lang_name;
        $data['key'] = 'reply_comment_mail';
        $data['link'] = _mkbh_comment_generate_link_to_comment($comment);
        _mkbh_comment_send_email($data);
      }
    }
  }
  else {
    $cids = db_select('comment')
      ->fields('comment', array('cid'))
      ->condition('nid', $node->nid, '=')
      ->execute();
    $cids = $cids->fetchCol();

    $comments = comment_load_multiple($cids);
    $send_user_ids = [];
    $send_user_ids[] = $comment->uid;
    $origrnal_comment = $comment;

    foreach ($comments as $comment) {

      if (!in_array($comment->uid ,$send_user_ids)) {
        $comment_author = user_load($comment->uid);

        if ($comment_author->field_unsubscribe[LANGUAGE_NONE][0]['value'] != 1) {
          $data['mail'] = $comment_author->mail;
          $data['username'] = $origrnal_comment->name;
          $data['comment'] = $origrnal_comment->comment_body[LANGUAGE_NONE][0]['value'];
          $data['language'] = $lang_name;
          $data['key'] = 'new_comment_mail';
          $data['link'] = _mkbh_comment_generate_link_to_comment($origrnal_comment);
          _mkbh_comment_send_email($data);
          $send_user_ids[] = $comment->uid;
        }
      }
    }
  }
}

/*
 * Custom send email function.
 */
function _mkbh_comment_send_email($data) {
  $unsubscribe_link = _mkbh_comment_generate_unsubscribe_link($data['mail']);

  drupal_mail(
    'mkbh_comment',
    $data['key'],
    $data['mail'],
    $data['language'],
    [
      'username' => $data['username'],
      'node_title' => html_entity_decode($data['node_title']),
      'comment' => html_entity_decode($data['comment']),
      'link' => $data['link'],
      'unsubscribe' => $unsubscribe_link,
    ],
    $from = 'no-reply@magasinetkbh.dk',
    $send = TRUE
);
}

/*
 * Implements hook_mail().
 */
function mkbh_comment_mail($key, &$message, $params) {
  switch ($key) {
    case 'reply_comment_mail':

      // Set headers etc.
      $message['headers'] = [
        'MIME-Version' => '1.0',
        'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
        'Content-Transfer-Encoding' => '8Bit',
        'X-Mailer' => 'Drupal',
      ];
      $message['subject'] = t('Nyt svar på din kommentar');
      $message['body'][] = t('@username skrev et svar til dig på artiklen @node_title.',
        [
          '@username' => $params['username'],
          '@node_title' => $params['node_title'],
        ]);
      $message['body'][] = t('Kommentar:');
      $message['body'][] = $params['comment'];
      $message['body'][] = $params['link'];
      $message['body'][] = $params['unsubscribe'];
      break;
    case 'new_comment_mail':
      // Set headers etc.
      $message['subject'] = t('Ny kommentar');
      $message['body'][] = t('@username skrev en ny kommentar til artiklen @node_title.',
        [
          '@username' => $params['username'],
          '@node_title' => $params['node_title'],
        ]);
      $message['body'][] = t('Kommentar:');
      $message['body'][] = $params['comment'];
      $message['body'][] = $params['link'];
      $message['body'][] = $params['unsubscribe'];
      break;
  }
}

function _mkbh_comment_generate_link_to_comment($comment) {

  $comment_id = ($comment->cid) ? $comment->cid : $comment->pid;
  $nid = $comment->nid;
  $options = ['absolute' => TRUE];
  $url = url('node/' . $nid, $options);

  return ($comment_id)
    ? l('Gå til kommentaren', $url . '#comment-' . $comment_id)
    : l('Gå til kommentarer', $url . '#comments');
}

/*
 * Generate unsubscribe link.
 */
function _mkbh_comment_generate_unsubscribe_link($user_mail) {
  $encode = base64_encode(
    openssl_encrypt(
      $user_mail,
      UNSUBSCRIVE_ENCRYPT_METHOD,
      UNSUBSCRIVE_KEY,
      0,
      UNSUBSCRIVE_IV
    )
  );
  return l(t('Klik her hvis du ikke ønsker at modtage disse notifikationer'), 'unsubscribe-mail/' . $encode);
}

/**
 * Implements hook_ctools_plugin_directory().
 */
function mkbh_comment_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner == 'ctools' && in_array($plugin_type, ['access'])) {
    return 'ctools/plugins/' . $plugin_type;
  }
}

/**
 * Implements hook_preprocess_field().
 */
function mkbh_comment_preprocess_field(&$vars, $hook) {
  // Allow line breaks in the comment fields.
  if ($vars['element']['#entity_type'] == 'comment'
    && $vars['element']['#field_type'] == 'text_long'
    && $vars['element']['#items'][0]['format'] == null) {
    $vars['items'][0]['#markup'] = preg_replace("/^(.*)<br.*\/?>/m", '<p>$1</p>', nl2br($vars['items'][0]['#markup']));
  }
}

/**
 * Check whether the request is xml http request.
 *
 * @return bool
 */
function is_xml_http_request(): bool {
  return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

// Sort First level comments by created "Newer first".
function _sort_comments_reverse($a, $b) {

  if ($a == $b) {
    return 0;
  }
  return ($a['#comment']->created > $b['#comment']->created) ? -1 : 1;
}

// Sort Second level comments by created "Older first".
function _sort_comments($a, $b) {

  if ($a == $b) {
    return 0;
  }
  return ($a['#comment']->created < $b['#comment']->created) ? -1 : 1;
}

/*
 * Implements hook_menu().
 */
function mkbh_comment_menu() {
  $items['unsubscribe-comment/%'] = [
    'title' => 'Unsubscribe page',
    'page callback' => 'mkbh_comment_unsubscribe_callback',
    'page arguments' => [1],
    'access callback' => TRUE,
  ];

  return $items;
}

/*
 * Custom Unsubscribe page callback.
 */
function mkbh_comment_unsubscribe_callback($arg = 0) {
  $mail = openssl_decrypt(
    base64_decode($arg),
    UNSUBSCRIVE_ENCRYPT_METHOD,
    UNSUBSCRIVE_KEY,
    0,
    UNSUBSCRIVE_IV
  );
  $user = user_load_by_mail($mail);
  if ($user->uid != 0) {
    if ($user->field_unsubscribe[LANGUAGE_NONE][0]['value'] != 1) {
      return t('You have already unsubscribed from the newsletter..');
    }
    $user->field_unsubscribe[LANGUAGE_NONE][0]['value'] = 1;
    user_save($user);
    return t('You have successfully unsubscribed from the newsletter.');
  }
  else {
    drupal_not_found();
  }
}
