<?php

/**
 * @file
 * Allows sending emails with Symfony Mailer.
 */

declare(strict_types=1);

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Template\Attribute;

/**
 * Implements hook_theme().
 */
function symfony_mailer_theme($existing, $type, $theme, $path) {
  return [
    'email' => [
      'variables' => [
        'email' => NULL,
      ],
      'mail theme' => TRUE,
    ],
    'email_wrap' => [
      'variables' => [
        'email' => NULL,
        'body' => '',
        'is_html' => TRUE,
      ],
    ],
  ];
}

/**
 * Implements hook_theme_suggestions_HOOK() for email.
 */
function symfony_mailer_theme_suggestions_email(array $variables): array {
  return array_slice($variables['email']->getSuggestions('email', '__'), 1);
}

/**
 * Implements hook_theme_suggestions_HOOK() for email_wrap.
 */
function symfony_mailer_theme_suggestions_email_wrap(array $variables): array {
  return array_slice($variables['email']->getSuggestions('email_wrap', '__'), 1);
}

/**
 * Implements hook_preprocess_HOOK() for commerce_order.
 */
function symfony_mailer_preprocess_commerce_order(&$variables): void {
  if ($variables['elements']['#view_mode'] == 'email') {
    // Workaround for https://www.drupal.org/project/commerce/issues/2949726.
    unset($variables['order']['billing_information']);
  }
}

/**
 * Prepares variables for email template.
 *
 * Default template: email.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - email: Email object.
 */
function template_preprocess_email(array &$variables): void {
  $email = $variables['email'];
  $variables['body'] = $email->getBody();
  $variables['subject'] = $email->getSubject();
  $variables = array_merge($variables, $email->getVariables());
}

/**
 * Prepares variables for email wrap template.
 *
 * Default template: email-wrap.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - email: Email object.
 *   - body: Body string.
 *   - is_html: True if generating HTML output, false for plain text.
 */
function template_preprocess_email_wrap(array &$variables): void {
  $email = $variables['email'];
  $variables['subject'] = $email->getSubject();
  $variables['type'] = $email->getTag(0);
  $variables['sub_type'] = $email->getTag(1);
  $variables['attributes'] = new Attribute();
}

/**
 * Implements hook_help().
 */
function symfony_mailer_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'symfony_mailer.verify':
      return '<p>' . t('Verify your Mailer configuration by sending a test email.') . '</p>';
  }
}
