<?php

/**
 * @file
 * Contains hook implementations for the CiviCRM module.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\user\UserInterface;
use Drupal\Core\Url;
use Symfony\Component\Routing\Route;
use Drupal\Core\Render\Markup;

require_once 'civicrm.user.inc';

/**
 * Implements hook_page_attachments().
 *
 * Inject arbitrary html into the head region.
 */
function civicrm_page_attachments(array &$page) {
  // Only do anything if CiviCRM is bootstrapped.
  // @codingStandardsIgnoreStart
  global $civicrm_root;
  // @codingStandardsIgnoreEnd
  if (empty($civicrm_root)) {
    return;
  }

  // Always add core styles (even if not on a /civicrm page).
  CRM_Core_Resources::singleton()->addCoreStyles();

  // Merge CiviCRM stuff into HTML header.
  if ($region = \CRM_Core_Region::instance('html-header', FALSE)) {
    \CRM_Utils_System::addHTMLHead($region->render(''));
  }

  /** @var \Drupal\civicrm\CivicrmPageState $page_state */
  $page_state = \Drupal::service('civicrm.page_state');

  // Attach CSS and JS.
  foreach ($page_state->getCSS() as $counter => $css) {
    $page['#attached']['html_head'][] = [$css, 'civicrm-css-' . $counter];
  }
  foreach ($page_state->getJS() as $counter => $js) {
    $page['#attached']['html_head'][] = [$js, 'civicrm-js-' . $counter];
  }

  // Any other miscellaneous headers.
  $headers = $page_state->getHtmlHeaders();
  $markup = [
    '#type'   => 'markup',
    '#weight' => -99,
    '#markup' => Markup::create($headers),
  ];
  $page['#attached']['html_head'][] = [$markup, 'civicrm-headers'];
}

/**
 * Implements hook_toolbar().
 *
 * Injects a link into the Drupal toolbar to /civicrm for users with
 * 'access civicrm' permission.
 */
function civicrm_toolbar() {
  $items = [];

  // Always return it with right cache context even if it's empty so that the
  // permissions can control it's visibility.
  $items['civicrm'] = [
    '#cache' => [
      'contexts' => ['user.permissions', 'url.path'],
    ],
  ];

  $user = \Drupal::currentUser();
  if ($user->hasPermission('access CiviCRM')) {
    $items['civicrm'] += [
      '#type' => 'toolbar_item',
      'tab' => [
        '#type' => 'link',
        '#title' => t('CiviCRM'),
        '#url' => Url::fromRoute('civicrm.civicrm'),
        '#options' => [
          'attributes' => [
            'title' => t('CiviCRM'),
            'class' => [
              'toolbar-item',
              'toolbar-icon',
              'toolbar-icon-civicrm',
            ],
          ],
        ],
      ],
      '#attached' => [
        'library' => [
          'civicrm/civicrm-icons',
        ],
      ],
    ];
    // Add tray if we are on a CiviCRM screen
    $path = ltrim(\Drupal::service('path.current')->getPath(), '/');
    if (strpos($path, 'civicrm') === 0) {
      $items['civicrm']['tray'] = [
        '#wrapper_attributes' => [
          'id' => 'toolbar-tray-civicrm',
        ],
        'content' => [
          '#markup' => ' ',
        ],
      ];
    }
  }

  return $items;
}

/**
 * Implements hook_entity_extra_field_info().
 *
 * Add additional pseudo-fields to the user display. This allows the UI to
 * control the order in which these are displayed, or whether they are displayed
 * at all.
 *
 * @Todo: set these fields are visible ONLY for the 'full' user display.
 */
function civicrm_entity_extra_field_info() {
  $extra['user']['user']['display']['civicrm_record'] = [
    'label' => t('CiviCRM record link'),
    'description' => t('Link to user’s CiviCRM record.'),
    'weight' => 0,
    'visible' => FALSE,
  ];
  $extra['user']['user']['display']['civicrm_dashboard'] = [
    'label' => t('CiviCRM dashboard link'),
    'description' => t('Link to user’s CiviCRM dashboard.'),
    'weight' => 0,
    'visible' => FALSE,
  ];
  $extra['user']['user']['display']['civicrm_profiles'] = [
    'label' => t('CiviCRM profile summaries'),
    'description' => t('A list CiviCRM profile summaries.'),
    'weight' => 0,
    'visible' => FALSE,
  ];

  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 *
 * We use this hook to add the pseudo-fields we've added in
 * civicrm_entity_extra_field_info() to the user display.
 */
function civicrm_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display, $view_mode) {
  \Drupal::service('civicrm')->initialize();

  // We need the $contact_id so that we know what data to pull out of Civicrm.
  // And we need the contact_id of the current user ($current_contact_id) so
  // that we can perform proper access checks.
  $current_user = \Drupal::currentUser();
  $contact_id = \CRM_Core_BAO_UFMatch::getContactId($account->id());
  $current_contact_id = \CRM_Core_BAO_UFMatch::getContactId($current_user->id());
  if (!$contact_id || !$current_contact_id) {
    return;
  }

  // Contact record link.
  if (($conf = $display->getComponent('civicrm_record')) && $current_user->hasPermission('access CiviCRM') && \CRM_Contact_BAO_Contact_Permission::allow($current_contact_id)) {
    $build['civicrm_record'] = [
      '#type' => 'item',
      '#weight' => $conf['weight'],
      0 => [
        '#type' => 'link',
        '#title' => t('View contact record'),
        '#url' => Url::fromRoute('civicrm.civicrm_contact_view', [
          'reset' => 1,
          'cid' => $contact_id,
        ]),
        '#prefix' => '<span class="user-page-link" id="user-page-contact" ><span class="user-page-bullet">&raquo;</span> ',
        '#suffix' => '</span>',
      ],
    ];
  }

  // Contact dashboard link.
  if (($conf = $display->getComponent('civicrm_dashboard')) && $current_user->hasPermission('access Contact Dashboard') && \CRM_Contact_BAO_Contact_Permission::allow($current_contact_id)) {
    $build['civicrm_dashboard'] = [
      '#type' => 'item',
      '#weight' => $conf['weight'],
      0 => [
        '#type' => 'link',
        '#title' => t('View contact dashboard'),
        '#url' => Url::fromRoute('civicrm.civicrm_user', [
          'reset' => 1,
          'id' => $contact_id,
        ]),
        '#prefix' => '<span class="user-page-link" id="user-page-dashboard" ><span class="user-page-bullet">&raquo;</span> ',
        '#suffix' => '</span>',
      ],
    ];
  }

  // Add profile summaries.
  // @Todo Do we need to check permissions before viewing each profile?
  if (($conf = $display->getComponent('civicrm_profiles')) && $current_user->hasPermission('profile view')) {
    $build['civicrm_profiles'] = [
      '#weight' => $conf['weight'],
    ];

    // We need the CiviCRM core Javascript.
    CRM_Core_Resources::singleton()->addCoreResources();

    foreach (_civicrm_get_profiles($contact_id) as $id => $profile) {
      $html = (new \CRM_Profile_Page_Dynamic($contact_id, $id, NULL))->run();
      $build['civicrm_profiles']["civicrm_profile_{$id}"] = [
        '#theme' => 'civicrm_user_profile',
        '#title' => $profile['title'],
        0 => [
          '#markup' => Markup::create($html),
        ],
        // @Todo Check access to this route before displaying the link
        1 => [
          '#type' => 'link',
          '#options' => ['html' => TRUE],
          '#title' => t('Edit %profile_name', ['%profile_name' => $profile['title']]),
          '#url' => Url::fromRoute('civicrm.user_profile', [
            'user' => $account->id(),
            'profile' => $id,
          ]),
          '#prefix' => '<span class="user-page-link" id="user-page-profile-' . substr($profile['title'], 0, 3) . '" ><span class="user-page-bullet">&raquo;</span> ',
          '#suffix' => '</span>',
        ],
      ];
    }
  }
}

/**
 * Get 'User Account' profiles.
 *
 * We return a list of profiles filtered down to only those that are Contact
 * based on the $contact_id's contact type.
 */
function _civicrm_get_profiles($contact_id) {
  \Drupal::service('civicrm')->initialize();
  $profiles = [];
  $ctype = \CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contact_id, 'contact_type');

  foreach (\CRM_Core_BAO_UFGroup::getModuleUFGroup('User Account') as $id => $uf_group) {
    $fieldType = CRM_Core_BAO_UFField::getProfileType($id);
    if (CRM_Contact_BAO_ContactType::isaSubType($fieldType)) {
      $fieldType = CRM_Contact_BAO_ContactType::getBasicType($fieldType);
    }

    // Filter profiles.
    if ($fieldType == 'Contact' || $fieldType == $ctype) {
      $profiles[$id] = $uf_group;
    }
  }
  return $profiles;
}

/**
 * Implements hook_form_user_form_alter().
 */
function civicrm_form_user_form_alter(&$form, &$form_state, $form_id) {
  // Email is required because otherwise synchronization with contacts
  // doesn't work.
  $form['account']['mail']['#required'] = TRUE;
}

/**
 * Implements hook_form_TAG_ID_alter().
 *
 * Attach any relevant profile form fields to user registration form.
 */
function civicrm_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $civicrm = \Drupal::service('civicrm');
  $civicrm->initialize();
  civicrm_key_disable();
  $html = \CRM_Core_BAO_UFGroup::getEditHTML(NULL, '', NULL, TRUE, TRUE, NULL, FALSE, $civicrm->getCtype());

  if (str_contains($html, 'type="file"')) {
    // If Drupal doesn't set the enctype, CiviCRM will not be able to upload
    // the file. Drupal only add this if the form has a file upload field. it
    // does not look at the civicrm elements.
    $form['#attributes']['enctype'] = 'multipart/form-data';
  }

  // Need to disable the page cache.
  \Drupal::service('page_cache_kill_switch')->trigger();

  // We need the CiviCRM core Javascript.
  CRM_Core_Resources::singleton()->addCoreResources();

  // Email is required because otherwise synchronization with contacts
  // doesn't work.
  $form['account']['mail']['#required'] = TRUE;

  $form['civicrm_profile_register'] = [
    '#markup' => Markup::create($html),
    '#cache' => [
      'max-age' => 0,
    ],
  ];
  $form['#validate'][] = '_civicrm_user_register_form_validate';
}

/**
 * Validation function for additional profile fields on user registration.
 */
function _civicrm_user_register_form_validate(&$form, FormStateInterface $form_state) {
  \Drupal::service('civicrm')->initialize();
  civicrm_key_disable();
  $errors = CRM_Core_BAO_UFGroup::isValid(NULL, '', TRUE);

  if (is_array($errors)) {
    foreach ($errors as $name => $message) {
      $form_state->setErrorByName($name, $message);
    }
  }
}

/**
 * Determine if the user is on a CiviCRM generated page.
 *
 * i.e. does the form have some civicrm unique token?
 */
function civicrm_on_user_page() {
  return isset($_POST['_qf_default']);
}

/**
 * Implements hook_theme().
 */
function civicrm_theme() {
  return [
    'civicrm_contact' => [
      'render element' => 'elements',
      'template' => 'civicrm-contact',
    ],
    'civicrm_user_profile' => [
      'render element' => 'elements',
      'template' => 'civicrm-user-profile',
    ],
  ];
}

/**
 * Implements hook_preprocess_html().
 */
function civicrm_preprocess_html(array &$variables) {
  // Get current route name and CiviCRM args parameter.
  $name = \Drupal::routeMatch()->getRouteName();
  $args = \Drupal::routeMatch()->getParameter('args');

  // Get module from route name.
  $segments = explode('.', $name);
  $module = $segments[0];

  // Is this a CiviCRM route and are arguments given?
  if (($module == 'civicrm') && $args) {
    $args = is_array($args) ? $args : explode('/', $args);

    // Since the body class of a sub-page inherits the args of its
    // parent page(s) a prefix is initiated.
    $prefix = '';

    // Generate classes from arguments.
    foreach ($args as &$arg) {
      $page = (empty($prefix) ? $arg : $prefix . '-' . $arg);
      $class = 'page-' . $page;

      // Add body class to variables.
      $variables['attributes']['class'][] = $class;

      // Update prefix.
      $prefix = $page;
    }
  }
}

/**
 * Prepares variables for civicrm_contact templates.
 *
 * Default template: civicrm-contact.html.twig.
 */
function template_preprocess_civicrm_contact(&$vars) {
  $vars['civicrm_contact'] = $vars['elements']['#civicrm_contact'];
}

/**
 * Disable civicrm key for all forms that interact with the CMS.
 *
 * We do not control the CMS form generation and hence should suppress
 * qfKey
 */
function civicrm_key_disable() {
  \CRM_Core_Config::singleton()->keyDisable = TRUE;
}

/**
 * Alter metatags generated by metatag module.
 */
function civicrm_metatags_alter(array &$metatags, array &$context) {
  $route_object = \Drupal::routeMatch()->getRouteObject();
  if ($route_object instanceof Route) {
    $routeDetails = $route_object->getDefaults();
    // If this is a CiviCRM Route.
    if (isset($routeDetails['_controller']) && $routeDetails['_controller'] === 'Drupal\civicrm\Controller\CivicrmController::main') {

      /** @var \Drupal\civicrm\CivicrmPageState $page_state */
      $page_state = \Drupal::service('civicrm.page_state');
      $metatags['title'] = str_replace('[current-page:title]', $page_state->getTitle(), $metatags['title']);
    }
  }
}
