<?php

/**
 * @file
 * Helps support Webform to Clientside Validation integration.
 */

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_webform_submission_form_alter().
 */
function webform_clientside_validation_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if (\Drupal::moduleHandler()->moduleExists('inline_form_errors')) {
    $form['#attached']['library'][] = 'webform_clientside_validation/webform_clientside_validation.ife';
  }
  if (isset($form['#attributes']['novalidate'])) {
    $form['#attributes']['data-webform-clientside-validation-novalidate'] = TRUE;
    $form['#attached']['library'][] = 'webform_clientside_validation/webform_clientside_validation.novalidate';
  }
}

/**
 * Implements hook_element_info_alter().
 */
function webform_clientside_validation_element_info_alter(array &$info) {
  if (isset($info['webform_email_confirm'])) {
    $info['webform_email_confirm']['#process'][] = '_webform_clientside_validation_webform_email_confirm_process';
  }
}

/**
 * Process 'webform_email_confirm' element and add 'equal_to' validation rules.
 *
 * @see \Drupal\webform\Element\WebformEmailConfirm::processWebformEmailConfirm
 */
function _webform_clientside_validation_webform_email_confirm_process(&$element, FormStateInterface $form_state, &$complete_form) {
  $validation_properties = [
    '#equal_to' => $element['#name'] . '[mail_1]',
    '#equal_to_error' => t('The specified email addresses do not match.'),
  ];
  if (empty($element['#flexbox'])) {
    $element['mail_2'] += $validation_properties;
  }
  else {
    $element['flexbox']['mail_2'] += $validation_properties;
  }
  return $element;
}
