<?php

/**
 * @file
 * Contains d_p_subscribe module.
 */

use Drupal\Core\Render\Markup;
use Drupal\d_p_subscribe_file\Forms\SubscribeFileForm;

/**
 * Implements hook_preprocess_HOOK().
 */
function d_p_subscribe_file_preprocess_paragraph__d_p_subscribe_file(array &$variables) {
  $paragraph = $variables['paragraph'];

  $form_class = \Drupal::service('class_resolver')
    ->getInstanceFromDefinition(SubscribeFileForm::class);
  $form_class->setParagraph($paragraph);

  $variables['subscribe_file_form'] = \Drupal::formBuilder()->getForm($form_class);
}

/**
 * Implements hook_theme().
 */
function d_p_subscribe_file_theme($existing, $type, $theme, $path) {
  return [
    'paragraph__d_p_subscribe_file' => [
      'base hook' => 'paragraph',
    ],
    'd_p_subscribe_file_download_page' => [
      'variables' => ['body' => NULL],
    ],
    'd_p_subscribe_file_mail' => [
      'variables' => ['body' => NULL],
    ],
  ];
}

/**
 * Implements hook_mail().
 */
function d_p_subscribe_file_mail($key, &$message, $params) {
  switch ($key) {
    case 'subscribe_form':
      $config = \Drupal::config('system.site');
      $message['from'] = $config->get('mail');
      $message['subject'] = t('Hi, @name, Your @site Download Link', [
        '@name' => $params['name'],
        '@site' => $config->get('name'),
      ]);
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      $rendered = \Drupal::service('renderer')->render($params['body']);
      $message['body'][0] = Markup::create($rendered);
      break;
  }
}

/**
 * Implements hook_d_p_centered_ckeditor_widget_paragraphs().
 */
function d_p_subscribe_file_d_p_centered_ckeditor_widget_paragraphs(array &$paragraph_types) {
  $paragraph_types[] = 'd_p_subscribe_file';
}
