<?php
if (!defined('ABSPATH')) exit;


if (!function_exists('custausu_rm_client_enqueue_admin_assets')) {
  function custausu_rm_client_enqueue_admin_assets(): void {
    if (!is_admin() || !current_user_can('manage_options')) {
      return;
    }

    $remote_messages_css = CUSTAUSU_PLUGIN_DIR . 'inc/css/custausu-remote-messages.css';
    wp_enqueue_style(
      'custausu-remote-messages',
      CUSTAUSU_PLUGIN_URL . 'inc/css/custausu-remote-messages.css',
      [],
      file_exists($remote_messages_css)
        ? (string) filemtime($remote_messages_css)
        : (defined('CUSTAUSU_VERSION') ? CUSTAUSU_VERSION : '1.0.0')
    );

    $remote_messages_js = CUSTAUSU_PLUGIN_DIR . 'inc/assets/js/custausu-remote-messages.js';

    wp_enqueue_script(
      'custausu-remote-messages',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-remote-messages.js',
      [],
      file_exists($remote_messages_js) ? (string) filemtime($remote_messages_js) : (defined('CUSTAUSU_VERSION') ? CUSTAUSU_VERSION : '1.0.0'),
      true
    );

    wp_localize_script(
      'custausu-remote-messages',
      'CUSTAUSU_RM_EVENTS',
      custausu_rm_client_event_config()
    );
  }
}

add_action('admin_enqueue_scripts', 'custausu_rm_client_enqueue_admin_assets');

if (!function_exists('custausu_rm_client_endpoint')) {
  function custausu_rm_client_endpoint(): string {
    $default = 'https://customauthsuite.com/wp-json/cas-remote-messages/v1/messages';

    $endpoint = (string) apply_filters('custausu_remote_messages_endpoint', $default);

    return esc_url_raw($endpoint);
  }
}

if (!function_exists('custausu_rm_client_events_endpoint')) {
  function custausu_rm_client_events_endpoint(): string {
    $endpoint = custausu_rm_client_endpoint();

    if ($endpoint === '') {
      return '';
    }

    $events_endpoint = preg_replace('#/messages(?:\?.*)?$#', '/events', $endpoint);
    $events_endpoint = is_string($events_endpoint) ? $events_endpoint : '';

    return esc_url_raw((string) apply_filters('custausu_remote_messages_events_endpoint', $events_endpoint));
  }
}

if (!function_exists('custausu_rm_client_site_hash')) {
  function custausu_rm_client_site_hash(): string {
    $basis = strtolower(trim((string) home_url('/')));

    if ($basis === '') {
      $basis = strtolower(trim((string) site_url('/')));
    }

    if ($basis === '') {
      return '';
    }

    $salt = defined('AUTH_SALT') ? (string) AUTH_SALT : (defined('NONCE_SALT') ? (string) NONCE_SALT : 'custom-auth-suite');

    return substr(hash('sha256', $salt . '|' . $basis), 0, 64);
  }
}


if (!function_exists('custausu_rm_client_preferences_option_name')) {
  function custausu_rm_client_preferences_option_name(): string {
    return 'custausu_remote_messages_client_preferences';
  }
}

if (!function_exists('custausu_rm_client_settings')) {
  /**
   * Return Remote Messages client settings.
   *
   * Runtime preferences are stored in a dedicated option so they are not tied to
   * the large CAS settings sanitizer. Global settings are still read as fallback
   * for backwards compatibility.
   */
  function custausu_rm_client_settings(): array {
    $settings = get_option('custausu_global_settings', []);
    $settings = is_array($settings) ? $settings : [];

    $preferences = get_option(custausu_rm_client_preferences_option_name(), []);
    $preferences = is_array($preferences) ? $preferences : [];

    foreach (['custausu_rm_messages_enabled', 'custausu_rm_analytics_enabled'] as $key) {
      if (array_key_exists($key, $preferences)) {
        $settings[$key] = !empty($preferences[$key]) ? 1 : 0;
      }
    }

    return $settings;
  }
}


if (!function_exists('custausu_rm_client_messages_enabled')) {
  function custausu_rm_client_messages_enabled(): bool {
    $settings = custausu_rm_client_settings();
    $enabled = array_key_exists('custausu_rm_messages_enabled', $settings)
      ? !empty($settings['custausu_rm_messages_enabled'])
      : false;

    return (bool) apply_filters('custausu_remote_messages_enabled', $enabled);
  }
}


if (!function_exists('custausu_rm_client_analytics_enabled')) {
  function custausu_rm_client_analytics_enabled(): bool {
    $settings = custausu_rm_client_settings();

    $enabled = array_key_exists('custausu_rm_analytics_enabled', $settings)
      ? !empty($settings['custausu_rm_analytics_enabled'])
      : false;

    return (bool) apply_filters('custausu_remote_messages_events_enabled', $enabled);
  }
}

if (!function_exists('custausu_rm_client_event_config')) {
  function custausu_rm_client_event_config(): array {
    if (!custausu_rm_client_analytics_enabled()) {
      return [
        'enabled' => false,
        'endpoint' => '',
        'siteHash' => '',
        'casPlan' => '',
        'licenseStatus' => '',
        'clientVersion' => defined('CUSTAUSU_VERSION') ? (string) CUSTAUSU_VERSION : '',
        'source' => 'cas_plugin_admin',
      ];
    }

    $context = function_exists('custausu_rm_client_context') ? custausu_rm_client_context('admin_dashboard') : [];

    return [
      'enabled' => true,
      'endpoint' => custausu_rm_client_events_endpoint(),
      'siteHash' => custausu_rm_client_site_hash(),
      'casPlan' => isset($context['cas_plan']) && is_scalar($context['cas_plan']) ? sanitize_key((string) $context['cas_plan']) : '',
      'licenseStatus' => isset($context['license_status']) && is_scalar($context['license_status']) ? sanitize_key((string) $context['license_status']) : '',
      'clientVersion' => defined('CUSTAUSU_VERSION') ? (string) CUSTAUSU_VERSION : '',
      'source' => 'cas_plugin_admin',
    ];
  }
}

if (!function_exists('custausu_rm_client_enabled')) {
  function custausu_rm_client_enabled(): bool {
    return custausu_rm_client_messages_enabled();
  }
}

if (!function_exists('custausu_rm_client_site_host')) {
  function custausu_rm_client_site_host(): string {
    $host = wp_parse_url(home_url('/'), PHP_URL_HOST);

    return is_string($host) ? strtolower($host) : '';
  }
}

if (!function_exists('custausu_rm_client_license_days_left')) {
  function custausu_rm_client_license_days_left(array $state): int {
    $expires_at = isset($state['license']['expires_at']) && is_scalar($state['license']['expires_at'])
      ? trim((string) $state['license']['expires_at'])
      : '';

    if ($expires_at === '') {
      return 0;
    }

    $ts = strtotime($expires_at . ' UTC');

    if (!$ts) {
      return 0;
    }

    $diff = $ts - time();

    if ($diff <= 0) {
      return 0;
    }

    return (int) ceil($diff / DAY_IN_SECONDS);
  }
}


if (!function_exists('custausu_rm_client_license_is_active')) {
  function custausu_rm_client_license_is_active(array $state): bool {
    $license = isset($state['license']) && is_array($state['license'])
      ? $state['license']
      : [];

    $status = isset($license['status']) && is_scalar($license['status'])
      ? sanitize_key((string) $license['status'])
      : '';

    if ($status === 'active') {
      return true;
    }

    $mode = isset($state['entitlement_mode']) && is_scalar($state['entitlement_mode'])
      ? sanitize_key((string) $state['entitlement_mode'])
      : '';

    return in_array($mode, ['license', 'signed_override'], true);
  }
}

if (!function_exists('custausu_rm_client_upgrade_base_plan')) {
  function custausu_rm_client_upgrade_base_plan(array $state): string {
    $effective = isset($state['effective_plan']) && is_scalar($state['effective_plan'])
      ? sanitize_key((string) $state['effective_plan'])
      : 'freemium';

    if ($effective === 'base') {
      $effective = 'advanced';
    }

    if (!in_array($effective, ['freemium', 'advanced', 'premium'], true)) {
      $effective = 'freemium';
    }

    if (!custausu_rm_client_license_is_active($state)) {
      return 'freemium';
    }

    return $effective;
  }
}

if (!function_exists('custausu_rm_client_upgrade_targets')) {
  function custausu_rm_client_upgrade_targets(array $state): array {
    $base = custausu_rm_client_upgrade_base_plan($state);

    if ($base === 'premium') {
      return [];
    }

    if ($base === 'advanced') {
      return ['premium'];
    }

    return ['advanced', 'premium'];
  }
}

/**
 * CAS Free accepts operational Remote Admin Messages only.
 */
if (!function_exists('custausu_rm_client_is_public_free_build')) {
  function custausu_rm_client_is_public_free_build(): bool {
    if (function_exists('custausu_is_public_build') && custausu_is_public_build()) {
      return true;
    }

    $package = defined('CUSTAUSU_BUILD_PACKAGE_PLAN')
      ? sanitize_key((string) CUSTAUSU_BUILD_PACKAGE_PLAN)
      : '';

    return in_array($package, ['freemium', 'free', 'freemium_wporg', 'free_wporg', 'wporg', 'wordpress'], true);
  }
}


if (!function_exists('custausu_rm_client_public_free_support_renewal_allowed')) {
  function custausu_rm_client_public_free_support_renewal_allowed(
    array $message,
    string $placement,
    array $context
  ): bool {
    $placement = sanitize_key($placement);

    if ($placement !== 'admin_dashboard') {
      return false;
    }

    $role = isset($message['message_role']) && is_scalar($message['message_role'])
      ? sanitize_key((string) $message['message_role'])
      : '';

    $category = isset($message['category']) && is_scalar($message['category'])
      ? sanitize_key((string) $message['category'])
      : '';

    if ($role !== 'support_renewal' || $category !== 'support') {
      return false;
    }

    if (empty($message['support_renewal_authorized'])) {
      return false;
    }

    $support_status = isset($context['support_status']) && is_scalar($context['support_status'])
      ? sanitize_key((string) $context['support_status'])
      : '';

    if (!in_array($support_status, ['active', 'expiring'], true)) {
      return false;
    }

    $support_days_left = isset($context['support_days_left'])
      ? max(0, min(3650, (int) $context['support_days_left']))
      : 0;

    $renewal_window_days = isset($context['support_renewal_window_days'])
      ? max(0, min(365, (int) $context['support_renewal_window_days']))
      : 0;

    if (
      $support_days_left <= 0
      || $renewal_window_days <= 0
      || $support_days_left > $renewal_window_days
      || empty($context['support_has_history'])
      || empty($context['support_coupon_enabled'])
    ) {
      return false;
    }

    $tier = isset($context['support_coupon_tier']) && is_scalar($context['support_coupon_tier'])
      ? sanitize_key((string) $context['support_coupon_tier'])
      : '';

    $message_tier = isset($message['support_coupon_tier']) && is_scalar($message['support_coupon_tier'])
      ? sanitize_key((string) $message['support_coupon_tier'])
      : '';

    $bucket = isset($context['support_duration_bucket']) && is_scalar($context['support_duration_bucket'])
      ? sanitize_key((string) $context['support_duration_bucket'])
      : '';

    $message_bucket = isset($message['support_duration_bucket']) && is_scalar($message['support_duration_bucket'])
      ? sanitize_key((string) $message['support_duration_bucket'])
      : '';

    $tier_buckets = [
      'renewal_30d' => ['30d', 'standalone_30d'],
      'renewal_3m'  => ['3m'],
      'renewal_6m'  => ['6m'],
      'renewal_1y'  => ['1y'],
    ];

    if (
      !isset($tier_buckets[$tier])
      || $message_tier !== $tier
      || !in_array($bucket, $tier_buckets[$tier], true)
      || $message_bucket !== $bucket
      || empty($message['support_coupon_enabled'])
    ) {
      return false;
    }

    $coupon_code = isset($message['coupon_code']) && is_scalar($message['coupon_code'])
      ? trim((string) $message['coupon_code'])
      : '';

    return $coupon_code !== '' && !empty($message['dismissible']);
  }
}

if (!function_exists('custausu_rm_client_message_is_commercial')) {
  function custausu_rm_client_message_is_commercial(array $message, string $placement = '', array $context = []): bool {
    $placement = sanitize_key($placement);

    $role = isset($message['message_role']) && is_scalar($message['message_role'])
      ? sanitize_key((string) $message['message_role'])
      : '';

    if ($role === 'support_renewal') {
      return !custausu_rm_client_public_free_support_renewal_allowed(
        $message,
        $placement,
        $context
      );
    }
    // Deny-only commercial role identifiers for the public Free package.
    // They are rejected and never rendered.
    if (in_array($role, [
      'upgrade_offer',
      'license_promo',
      'license_renewal',
      'support_purchase',
    ], true)) {
      return true;
    }

    $category = isset($message['category']) && is_scalar($message['category'])
      ? sanitize_key((string) $message['category'])
      : '';

    if (in_array($category, [
      'upgrade',
      'commercial',
      'promotion',
      'promo',
      'sales',
      'offer',
      'license',
      'purchase',
      'renewal',
    ], true)) {
      return true;
    }

    $coupon_code = isset($message['coupon_code']) && is_scalar($message['coupon_code'])
      ? trim((string) $message['coupon_code'])
      : '';
    $cta_url = isset($message['cta_url']) && is_scalar($message['cta_url'])
      ? strtolower((string) $message['cta_url'])
      : '';

    if ($coupon_code !== '' || strpos($cta_url, 'cas_coupon=') !== false || strpos($cta_url, 'cas_offer=') !== false) {
      return true;
    }

    $message_id = isset($message['id']) && is_scalar($message['id'])
      ? sanitize_key((string) $message['id'])
      : '';

    foreach (['upgrade', 'support-buy', 'support-purchase', 'support-renew', 'license-renew', 'discount', 'coupon', 'purchase'] as $fragment) {
      if ($fragment !== '' && strpos($message_id, $fragment) !== false) {
        return true;
      }
    }

    return false;
  }
}

if (!function_exists('custausu_rm_client_filter_public_free_messages')) {
  function custausu_rm_client_filter_public_free_messages(array $messages, string $placement, array $context = []): array {
    if (!custausu_rm_client_is_public_free_build()) {
      return $messages;
    }

    return array_values(array_filter($messages, static function ($message) use ($placement, $context): bool {
      return is_array($message)
        && !custausu_rm_client_message_is_commercial($message, $placement, $context);
    }));
  }
}

if (!function_exists('custausu_rm_client_context')) {
  function custausu_rm_client_context(string $placement = 'admin_dashboard'): array {
    $state = function_exists('custausu_free_package_runtime_context') ? custausu_free_package_runtime_context() : [];

    $license = isset($state['license']) && is_array($state['license'])
      ? $state['license']
      : [];

    $support_context = isset($license['support_context']) && is_array($license['support_context'])
      ? $license['support_context']
      : [];

    $plan = isset($state['effective_plan']) && is_scalar($state['effective_plan'])
      ? sanitize_key((string) $state['effective_plan'])
      : 'freemium';

    $package = defined('CUSTAUSU_BUILD_PACKAGE_PLAN')
      ? sanitize_key((string) CUSTAUSU_BUILD_PACKAGE_PLAN)
      : $plan;

    $license_status = isset($license['status']) && is_scalar($license['status'])
      ? sanitize_key((string) $license['status'])
      : '';

    $license_type = isset($license['license_type']) && is_scalar($license['license_type'])
      ? sanitize_key((string) $license['license_type'])
      : '';

    if ($license_type === '' && isset($support_context['license_type']) && is_scalar($support_context['license_type'])) {
      $license_type = sanitize_key((string) $support_context['license_type']);
    }

    $context = [
      'placement'         => sanitize_key($placement),
      'site_host'         => custausu_rm_client_site_host(),
      'locale'            => function_exists('get_user_locale') ? get_user_locale() : get_locale(),
      'cas_version'       => defined('CUSTAUSU_VERSION') ? (string) CUSTAUSU_VERSION : '',
      'cas_package'       => $package,
      'cas_plan'          => $plan,
      'license_status'    => $license_status,
      'license_type'      => $license_type,
      'support_status'    => 'none',
      'support_days_left' => 0,
      'license_days_left' => custausu_rm_client_license_days_left($state),
      'upgrade_base_plan' => custausu_rm_client_upgrade_base_plan($state),
      'upgrade_targets'   => custausu_rm_client_upgrade_targets($state),
      'max_messages'      => 8,
    ];

    if (function_exists('custausu_free_package_runtime_context')) {
      $license_state = custausu_free_package_runtime_context();

      if (is_array($license_state)) {
        $license = is_array($license_state['license'] ?? null) ? $license_state['license'] : [];
        $support_context = is_array($license['support_context'] ?? null) ? $license['support_context'] : [];

        if (empty($support_context)) {
          $client_state = isset($license_state['client_state']) && is_array($license_state['client_state'])
            ? $license_state['client_state']
            : [];

          if (isset($client_state['support_context']) && is_array($client_state['support_context'])) {
            $support_context = $client_state['support_context'];
          }
        }

        if (!empty($support_context)) {
          $support_status = isset($support_context['support_status']) && is_scalar($support_context['support_status'])
            ? sanitize_key((string) $support_context['support_status'])
            : '';

          if (in_array($support_status, ['none', 'active', 'expired', 'expiring', 'inactive', 'limited'], true)) {
            $context['support_status'] = $support_status;
          }

          if (isset($support_context['support_days_left'])) {
            $context['support_days_left'] = max(0, min(3650, (int) $support_context['support_days_left']));
          }

          if (!empty($support_context['support_coupon_code']) && is_scalar($support_context['support_coupon_code'])) {
            $context['coupon_code'] = substr(trim(wp_strip_all_tags((string) $support_context['support_coupon_code'])), 0, 80);
          }

          $support_key_fields = [
            'support_kind',
            'support_source',
            'support_priority_level',
            'support_duration_bucket',
            'support_coupon_tier',
            'support_entitlement_source_type',
          ];

          foreach ($support_key_fields as $field) {
            if (!empty($support_context[$field]) && is_scalar($support_context[$field])) {
              $context[$field] = substr(sanitize_key((string) $support_context[$field]), 0, 80);
            }
          }

          $support_int_fields = [
            'support_duration_days'       => [0, 3650],
            'support_renewal_window_days' => [0, 365],
            'support_has_history'         => [0, 1],
            'support_coupon_enabled'      => [0, 1],
            'support_discount_percent'    => [0, 95],
          ];

          foreach ($support_int_fields as $field => $range) {
            if (isset($support_context[$field])) {
              $context[$field] = max($range[0], min($range[1], (int) $support_context[$field]));
            }
          }
        }
      }
    }


    return (array) apply_filters('custausu_remote_messages_context', $context, $placement, $state);
  }
}

if (!function_exists('custausu_rm_get_placement_config')) {
  function custausu_rm_get_placement_config(string $placement): array {

    if (!function_exists('custausu_rm_registered_placements')) {
      return [];
    }

    $placements = custausu_rm_registered_placements();

    if (
      empty($placements[$placement])
      || !is_array($placements[$placement])
    ) {
      return [];
    }

    return (array) apply_filters(
      'custausu_rm_get_placement_config',
      $placements[$placement],
      $placement
    );
  }
}

if (!function_exists('custausu_rm_message_text')) {
  function custausu_rm_message_text(array $message, string $key): string {
    $value = $message[$key] ?? '';

    if (is_scalar($value)) {
      return trim((string) $value);
    }

    return '';
  }
}

if (!function_exists('custausu_rm_png_fallback_url')) {
  function custausu_rm_png_fallback_url(string $url): string {
    $url = trim($url);

    if ($url === '') {
      return '';
    }

    $parts = explode('?', $url, 2);
    $clean_url = $parts[0];
    $query = isset($parts[1]) && $parts[1] !== '' ? '?' . $parts[1] : '';

    if ($clean_url === '' || !preg_match('/\.webp$/i', $clean_url)) {
      return '';
    }

    $png_url = (string) preg_replace('/\.webp$/i', '.png', $clean_url);

    return $png_url . $query;
  }
}

if (!function_exists('custausu_rm_client_event_attrs')) {
  function custausu_rm_client_event_attrs(array $message, string $placement, string $title = '', string $cta_label = ''): string {
    $attrs = [
      'data-custausu-rm-event-card' => '1',
      'data-custausu-rm-message-id' => isset($message['id']) && is_scalar($message['id']) ? (string) $message['id'] : '',
      'data-custausu-rm-placement' => $placement,
      'data-custausu-rm-category' => isset($message['category']) && is_scalar($message['category']) ? (string) $message['category'] : '',
      'data-custausu-rm-message-role' => isset($message['message_role']) && is_scalar($message['message_role']) ? (string) $message['message_role'] : '',
      'data-custausu-rm-delivery-group' => isset($message['delivery_group']) && is_scalar($message['delivery_group']) ? (string) $message['delivery_group'] : '',
      'data-custausu-rm-dismiss-hash' => isset($message['dismiss_hash']) && is_scalar($message['dismiss_hash']) ? (string) $message['dismiss_hash'] : '',
      'data-custausu-rm-title' => $title !== '' ? $title : (isset($message['title']) && is_scalar($message['title']) ? (string) $message['title'] : ''),
      'data-custausu-rm-subtitle' => isset($message['subtitle']) && is_scalar($message['subtitle']) ? (string) $message['subtitle'] : '',
      'data-custausu-rm-cta-label' => $cta_label !== '' ? $cta_label : (isset($message['cta_label']) && is_scalar($message['cta_label']) ? (string) $message['cta_label'] : ''),
    ];

    $html = '';

    foreach ($attrs as $name => $value) {
      $html .= ' ' . $name . '="' . esc_attr((string) $value) . '"';
    }

    return $html;
  }
}

if (!function_exists('custausu_rm_render_picture')) {
  function custausu_rm_render_picture(string $desktop_url, string $mobile_url, string $class_base): void {
    $desktop_url = esc_url_raw($desktop_url);
    $mobile_url  = esc_url_raw($mobile_url);

    if ($desktop_url === '' && $mobile_url === '') {
      return;
    }

    $desktop_png = $desktop_url !== '' ? custausu_rm_png_fallback_url($desktop_url) : '';
    $mobile_png  = $mobile_url !== '' ? custausu_rm_png_fallback_url($mobile_url) : '';

    $img_src = $desktop_png !== ''
      ? $desktop_png
      : ($desktop_url !== '' ? $desktop_url : ($mobile_png !== '' ? $mobile_png : $mobile_url));

    echo '<picture class="' . esc_attr($class_base . '__picture') . '">';

    if ($mobile_url !== '') {
      echo '<source media="(max-width: 782px)" srcset="' . esc_url($mobile_url) . '">';
    }

    if ($desktop_url !== '') {
      echo '<source srcset="' . esc_url($desktop_url) . '">';
    }

    echo '<img'
      . ' class="' . esc_attr($class_base . '__img') . '"'
      . ' src="' . esc_url($img_src) . '"'
      . ($desktop_png !== '' ? ' data-custausu-rm-fallback-desktop-src="' . esc_url($desktop_png) . '"' : '')
      . ($mobile_png !== '' ? ' data-custausu-rm-fallback-mobile-src="' . esc_url($mobile_png) . '"' : '')
      . ($desktop_png !== '' ? ' data-custausu-rm-fallback-src="' . esc_url($desktop_png) . '"' : '')
      . ' alt=""'
      . ' loading="lazy"'
      . '>';

    echo '</picture>';
  }
}

if (!function_exists('custausu_rm_render_doctor_summary')) {
  function custausu_rm_render_doctor_summary(array $messages, array $config = []): void {
    if (empty($messages)) {
      return;
    }

    $message = is_array($messages[0] ?? null) ? $messages[0] : [];

    if (empty($message)) {
      return;
    }

    $title = custausu_rm_message_text($message, 'title');
    $subtitle = custausu_rm_message_text($message, 'subtitle');
    $body = custausu_rm_message_text($message, 'body');

    $image_desktop = !empty($message['image_desktop']) && is_scalar($message['image_desktop']) ? esc_url_raw((string) $message['image_desktop']) : '';
    $image_mobile = !empty($message['image_mobile']) && is_scalar($message['image_mobile']) ? esc_url_raw((string) $message['image_mobile']) : '';

    echo '<div class="custausu-rm-placement custausu-rm-placement--doctor_summary custausu-rm-layout--compact" data-custausu-rm-placement="doctor_summary" data-custausu-rm-layout="compact">';
    echo '<article class="custausu-rm-doctor-summary-card">';

    if ($image_desktop !== '' || $image_mobile !== '') {
      echo '<div class="custausu-rm-doctor-summary-card__media" aria-hidden="true">';
      custausu_rm_render_picture($image_desktop, $image_mobile, 'custausu-rm-doctor-summary-card');
      echo '</div>';
    }

    echo '<div class="custausu-rm-doctor-summary-card__content">';

    if ($subtitle !== '') {
      echo '<div class="custausu-rm-doctor-summary-card__kicker">' . esc_html($subtitle) . '</div>';
    }

    if ($title !== '') {
      echo '<strong class="custausu-rm-doctor-summary-card__title">' . esc_html($title) . '</strong>';
    }

    if ($body !== '') {
      echo '<span class="custausu-rm-doctor-summary-card__body">' . esc_html($body) . '</span>';
    }

    echo '</div>';

    echo '</article>';
    echo '</div>';
  }
}

if (!function_exists('custausu_rm_render_doctor_support')) {
  function custausu_rm_render_doctor_support(array $messages, array $config = []): void {
    if (empty($messages)) {
      return;
    }

    $message = is_array($messages[0] ?? null) ? $messages[0] : [];

    if (empty($message)) {
      return;
    }

    $title = custausu_rm_message_text($message, 'title');
    $subtitle = custausu_rm_message_text($message, 'subtitle');
    $body = custausu_rm_message_text($message, 'body');
    $body_secondary = custausu_rm_message_text($message, 'body_secondary');

    $image_desktop = !empty($message['image_desktop']) && is_scalar($message['image_desktop']) ? esc_url_raw((string) $message['image_desktop']) : '';
    $image_mobile = !empty($message['image_mobile']) && is_scalar($message['image_mobile']) ? esc_url_raw((string) $message['image_mobile']) : '';

    echo '<div class="custausu-rm-placement custausu-rm-placement--doctor_support custausu-rm-layout--hero" data-custausu-rm-placement="doctor_support" data-custausu-rm-layout="hero">';
    echo '<article class="custausu-rm-doctor-support-card">';

    echo '<div class="custausu-rm-doctor-support-card__content">';

    if ($subtitle !== '') {
      echo '<div class="custausu-rm-doctor-support-card__kicker">' . esc_html($subtitle) . '</div>';
    }

    if ($title !== '') {
      echo '<h3 class="custausu-rm-doctor-support-card__title">' . esc_html($title) . '</h3>';
    }

    if ($body !== '') {
      echo '<p class="custausu-rm-doctor-support-card__body">' . esc_html($body) . '</p>';
    }

    if ($body_secondary !== '') {
      echo '<p class="custausu-rm-doctor-support-card__secondary">' . esc_html($body_secondary) . '</p>';
    }

    echo '</div>';

    if ($image_desktop !== '' || $image_mobile !== '') {
      echo '<div class="custausu-rm-doctor-support-card__media">';
      custausu_rm_render_picture($image_desktop, $image_mobile, 'custausu-rm-doctor-support-card');
      echo '</div>';
    }

    echo '</article>';
    echo '</div>';
  }
}

if (!function_exists('custausu_rm_render_placeholder_debug')) {
  function custausu_rm_render_placeholder_debug(string $placement, array $messages, array $config = []): void {
    if (empty($messages)) {
      return;
    }

    $layout = isset($config['layout'])
      ? sanitize_key((string) $config['layout'])
      : 'slider';

    echo '<div class="custausu-rm-placement custausu-rm-placement--' . esc_attr(sanitize_html_class($placement)) . ' custausu-rm-layout--' . esc_attr(sanitize_html_class($layout)) . '"';
    echo ' data-custausu-rm-placement="' . esc_attr($placement) . '"';
    echo ' data-custausu-rm-layout="' . esc_attr($layout) . '">';

    echo '<div class="custausu-rm-placement__debug">';
    echo '<strong>CAS RM placement:</strong> ';
    echo esc_html($placement);
    echo ' <span class="custausu-rm-placement__debug-layout">(' . esc_html($layout) . ')</span>';
    echo ' <span class="custausu-rm-placement__debug-count">— ' . esc_html(count($messages)) . ' message(s)</span>';
    echo '</div>';

    echo '</div>';
  }
}

if (!function_exists('custausu_rm_render')) {
  function custausu_rm_render(string $placement, array $args = []): void {
    $placement = sanitize_key($placement);

    $config = custausu_rm_get_placement_config($placement);
    $config['placement'] = sanitize_key($placement);

    if (empty($config)) {
      return;
    }

    $messages = custausu_rm_client_fetch_messages($placement);

    if (empty($messages)) {
      return;
    }

    if ($placement === 'doctor_summary') {
      custausu_rm_render_doctor_summary($messages, $config);
      return;
    }

    if ($placement === 'doctor_support') {
      custausu_rm_render_doctor_support($messages, $config);
      return;
    }

    custausu_rm_render_placeholder_debug($placement, $messages, $config);
  }
}

if (!function_exists('custausu_rm_client_cache_key')) {
  function custausu_rm_client_cache_key(array $context): string {
    $safe = [
      'placement'         => $context['placement'] ?? '',
      'locale'            => $context['locale'] ?? '',
      'cas_version'       => $context['cas_version'] ?? '',
      'cas_package'       => $context['cas_package'] ?? '',
      'cas_plan'          => $context['cas_plan'] ?? '',
      'license_status'    => $context['license_status'] ?? '',
      'license_type'      => $context['license_type'] ?? '',
      'support_status'    => $context['support_status'] ?? '',
      'support_days_left' => (int) ($context['support_days_left'] ?? 0),
      'license_days_left' => (int) ($context['license_days_left'] ?? 0),
      'upgrade_base_plan' => (string) ($context['upgrade_base_plan'] ?? ''),
      'upgrade_targets'   => array_values((array) ($context['upgrade_targets'] ?? [])),
    ];

    $catalog_version = (int) get_option('custausu_remote_messages_catalog_version', 0);
    $safe['catalog_version'] = $catalog_version;

    return 'custausu_rm_' . md5(wp_json_encode($safe));
  }
}


if (!function_exists('custausu_rm_client_remote_catalog_version')) {
  function custausu_rm_client_remote_catalog_version(array $context): int {
    if (!custausu_rm_client_messages_enabled()) {
      return 0;
    }

    $endpoint = custausu_rm_client_endpoint();

    if ($endpoint === '') {
      return 0;
    }

    $probe_context = $context;
    $probe_context['max_messages'] = 1;
    $probe_context['cas_rm_probe'] = 1;

    $url = add_query_arg(array_filter($probe_context, static function ($value) {
      return $value !== '' && $value !== null;
    }), $endpoint);

    $response = wp_remote_get($url, [
      'timeout' => 5,
      'redirection' => 2,
      'headers' => [
        'Accept' => 'application/json',
        'Cache-Control' => 'no-cache',
      ],
    ]);

    if (is_wp_error($response)) {
      return 0;
    }

    $code = (int) wp_remote_retrieve_response_code($response);

    if ($code < 200 || $code >= 300) {
      return 0;
    }

    $data = json_decode(wp_remote_retrieve_body($response), true);

    if (!is_array($data)) {
      return 0;
    }

    return isset($data['catalog_version']) ? max(0, (int) $data['catalog_version']) : 0;
  }
}


if (!function_exists('custausu_rm_client_fetch_messages')) {
  function custausu_rm_client_fetch_messages(string $placement = 'admin_dashboard', bool $force = false): array {
    $placement = sanitize_key($placement);

    if (!custausu_rm_client_messages_enabled()) {
      return [];
    }

    $endpoint = custausu_rm_client_endpoint();

    if ($endpoint === '') {
      return [];
    }

    $context = custausu_rm_client_context($placement);
    $cache_key = custausu_rm_client_cache_key($context);

    if (!$force) {
      $cached = get_transient($cache_key);

      if (is_array($cached)) {
        $local_catalog_version = (int) get_option('custausu_remote_messages_catalog_version', 0);
        $remote_catalog_version = custausu_rm_client_remote_catalog_version($context);

        if ($remote_catalog_version > 0 && $remote_catalog_version > $local_catalog_version) {
          update_option('custausu_remote_messages_catalog_version', $remote_catalog_version, false);
          delete_transient($cache_key);
        } else {
          return custausu_rm_client_filter_public_free_messages($cached, $placement, $context);
        }
      }
    }

    $url = add_query_arg(array_filter($context, static function ($value) {
      return $value !== '' && $value !== null;
    }), $endpoint);

    $response = wp_remote_get($url, [
      'timeout' => 8,
      'redirection' => 2,
      'headers' => [
        'Accept' => 'application/json',
      ],
    ]);

    if (is_wp_error($response)) {
      return [];
    }

    $code = (int) wp_remote_retrieve_response_code($response);

    if ($code < 200 || $code >= 300) {
      return [];
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (!is_array($data) || empty($data['ok']) || !isset($data['messages']) || !is_array($data['messages'])) {
      return [];
    }

    $remote_catalog_version = isset($data['catalog_version']) ? (int) $data['catalog_version'] : 0;

    if ($remote_catalog_version > 0) {
      update_option('custausu_remote_messages_catalog_version', $remote_catalog_version, false);
    }

    $messages = custausu_rm_client_normalize_messages($data['messages']);
    $messages = custausu_rm_client_filter_public_free_messages($messages, $placement, $context);

    $ttl = isset($data['cache_ttl_seconds']) ? (int) $data['cache_ttl_seconds'] : HOUR_IN_SECONDS;
    $ttl = max(300, min(DAY_IN_SECONDS, $ttl));

    set_transient($cache_key, $messages, $ttl);

    return $messages;
  }
}

if (!function_exists('custausu_rm_client_normalize_messages')) {
  function custausu_rm_client_normalize_messages(array $messages): array {
    $out = [];

    foreach ($messages as $message) {
      if (!is_array($message)) {
        continue;
      }

      $id = isset($message['id']) && is_scalar($message['id'])
        ? sanitize_key((string) $message['id'])
        : '';

      $title = isset($message['title']) && is_scalar($message['title'])
        ? trim(wp_strip_all_tags((string) $message['title']))
        : '';

      if ($id === '' || $title === '') {
        continue;
      }

      $out[] = [
        'id'            => $id,
        'category'      => isset($message['category']) ? sanitize_key((string) $message['category']) : '',
        'message_role'  => isset($message['message_role']) ? sanitize_key((string) $message['message_role']) : '',
        'delivery_group'=> isset($message['delivery_group']) ? sanitize_key((string) $message['delivery_group']) : '',
        'audience_mode' => isset($message['audience_mode']) ? sanitize_key((string) $message['audience_mode']) : '',
        'priority'      => isset($message['priority']) ? (int) $message['priority'] : 0,
        'title'         => $title,
        'subtitle'      => isset($message['subtitle']) && is_scalar($message['subtitle']) ? trim(wp_strip_all_tags((string) $message['subtitle'])) : '',
        'body'          => isset($message['body']) && is_scalar($message['body']) ? trim(wp_strip_all_tags((string) $message['body'])) : '',
        'body_secondary'=> isset($message['body_secondary']) && is_scalar($message['body_secondary']) ? trim(wp_strip_all_tags((string) $message['body_secondary'])) : '',
        'image_desktop' => isset($message['image_desktop']) ? esc_url_raw((string) $message['image_desktop']) : '',
        'image_mobile'  => isset($message['image_mobile']) ? esc_url_raw((string) $message['image_mobile']) : '',
        'cta_label'     => isset($message['cta_label']) && is_scalar($message['cta_label']) ? trim(wp_strip_all_tags((string) $message['cta_label'])) : '',
        'cta_url'       => isset($message['cta_url']) ? esc_url_raw((string) $message['cta_url']) : '',
        'coupon_code'   => isset($message['coupon_code']) && is_scalar($message['coupon_code']) ? trim(wp_strip_all_tags((string) $message['coupon_code'])) : '',
        'support_coupon_tier' => isset($message['support_coupon_tier']) && is_scalar($message['support_coupon_tier'])
          ? substr(sanitize_key((string) $message['support_coupon_tier']), 0, 80)
          : '',
        'support_coupon_enabled' => !empty($message['support_coupon_enabled']) ? 1 : 0,
        'support_duration_bucket' => isset($message['support_duration_bucket']) && is_scalar($message['support_duration_bucket'])
          ? substr(sanitize_key((string) $message['support_duration_bucket']), 0, 50)
          : '',
        'support_renewal_authorized' => !empty($message['support_renewal_authorized']) ? 1 : 0,
        'dismissible'   => !empty($message['dismissible']),
        'dismiss_ttl_seconds' => !empty($message['dismissible'])
          ? max(60, min(2592000, isset($message['dismiss_ttl_seconds']) ? absint($message['dismiss_ttl_seconds']) : 300))
          : 0,
        'dismiss_hash'  => isset($message['dismiss_hash']) && is_scalar($message['dismiss_hash'])
          ? substr(sanitize_key((string) $message['dismiss_hash']), 0, 32)
          : '',
      ];
    }

    return $out;
  }
}


if (!function_exists('custausu_rm_client_current_admin_url')) {
  function custausu_rm_client_current_admin_url(): string {
    $request_uri = isset($_SERVER['REQUEST_URI'])
      ? esc_url_raw((string) wp_unslash($_SERVER['REQUEST_URI']))
      : '';

    if ($request_uri !== '') {
      return esc_url_raw(home_url($request_uri));
    }

    return esc_url_raw(admin_url());
  }
}

if (!function_exists('custausu_rm_client_clear_placement_dismissal')) {
  function custausu_rm_client_clear_placement_dismissal(string $placement): void {
    $placement = sanitize_key($placement);
    $dismissals = custausu_rm_client_dismissals();

    if (isset($dismissals[$placement])) {
      unset($dismissals[$placement]);
      update_option('custausu_remote_messages_dismissals', $dismissals, false);
    }
  }
}

if (!function_exists('custausu_rm_client_dismissals')) {
  function custausu_rm_client_dismissals(): array {
    $raw = get_option('custausu_remote_messages_dismissals', []);

    return is_array($raw) ? $raw : [];
  }
}

if (!function_exists('custausu_rm_client_is_placement_dismissed')) {
  function custausu_rm_client_is_placement_dismissed(string $placement): bool {
    $dismissals = custausu_rm_client_dismissals();
    $placement = sanitize_key($placement);

    $until = isset($dismissals[$placement]) ? (int) $dismissals[$placement] : 0;

    return $until > time();
  }
}

if (!function_exists('custausu_rm_client_dismiss_placement')) {
  function custausu_rm_client_dismiss_placement(string $placement, int $days = 3): void {
    $placement = sanitize_key($placement);
    $days = max(1, min(5, $days));

    $dismissals = custausu_rm_client_dismissals();
    $dismissals[$placement] = time() + ($days * DAY_IN_SECONDS);

    update_option('custausu_remote_messages_dismissals', $dismissals, false);
  }
}

if (!function_exists('custausu_rm_client_message_dismiss_key')) {
  function custausu_rm_client_message_dismiss_key(string $placement, string $message_id, string $dismiss_hash = ''): string {
    $placement = sanitize_key($placement);
    $message_id = sanitize_key($message_id);
    $dismiss_hash = substr(sanitize_key($dismiss_hash), 0, 32);

    if ($placement === '' || $message_id === '') {
      return '';
    }

    if ($dismiss_hash === '') {
      $dismiss_hash = 'default';
    }

    return 'message:' . $placement . ':' . $message_id . ':' . $dismiss_hash;
  }
}

if (!function_exists('custausu_rm_client_is_message_dismissed')) {
  function custausu_rm_client_is_message_dismissed(string $placement, array $message): bool {
    $message_id = isset($message['id']) && is_scalar($message['id']) ? (string) $message['id'] : '';
    $dismiss_hash = isset($message['dismiss_hash']) && is_scalar($message['dismiss_hash']) ? (string) $message['dismiss_hash'] : '';
    $key = custausu_rm_client_message_dismiss_key($placement, $message_id, $dismiss_hash);

    if ($key === '') {
      return false;
    }

    $dismissals = custausu_rm_client_dismissals();
    $until = isset($dismissals[$key]) ? (int) $dismissals[$key] : 0;

    if ($until > time()) {
      return true;
    }

    if ($until > 0) {
      unset($dismissals[$key]);
      update_option('custausu_remote_messages_dismissals', $dismissals, false);
    }

    return false;
  }
}

if (!function_exists('custausu_rm_client_filter_dismissed_messages')) {
  function custausu_rm_client_filter_dismissed_messages(array $messages, string $placement): array {
    $out = [];

    foreach ($messages as $message) {
      if (!is_array($message)) {
        continue;
      }

      if (custausu_rm_client_is_message_dismissed($placement, $message)) {
        continue;
      }

      $out[] = $message;
    }

    return $out;
  }
}

if (!function_exists('custausu_rm_client_dismiss_message')) {
  function custausu_rm_client_dismiss_message(string $placement, string $message_id, string $dismiss_hash = '', int $ttl_seconds = 300): void {
    $key = custausu_rm_client_message_dismiss_key($placement, $message_id, $dismiss_hash);

    if ($key === '') {
      return;
    }

    $ttl_seconds = max(60, min(2592000, $ttl_seconds));
    $dismissals = custausu_rm_client_dismissals();
    $dismissals[$key] = time() + $ttl_seconds;

    update_option('custausu_remote_messages_dismissals', $dismissals, false);
  }
}

if (!function_exists('custausu_rm_client_should_render_admin_top')) {
  function custausu_rm_client_should_render_admin_top(): bool {
    if (!custausu_rm_client_messages_enabled()) {
      return false;
    }

    if (!is_admin() || !current_user_can('manage_options')) {
      return false;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin screen routing query arg; no state change is performed here.
    $page = isset($_GET['page']) ? sanitize_key((string) wp_unslash($_GET['page'])) : '';
    $screen = function_exists('get_current_screen') ? get_current_screen() : null;
    $screen_id = $screen && isset($screen->id) ? (string) $screen->id : '';

    /* Remote Messages admin-top belongs only to exact CAS Settings. */
    $matches = (
      $page === 'custausu-settings'
      || $screen_id === 'toplevel_page_custausu-settings'
    );

    return (bool) apply_filters(
      'custausu_remote_messages_admin_top_should_render',
      $matches,
      $page,
      $screen_id
    );
  }
}

if (!function_exists('custausu_rm_client_render_admin_top')) {
  function custausu_rm_client_render_admin_top(): void {
    $placement = 'admin_dashboard';

    if (!custausu_rm_client_should_render_admin_top()) {
      return;
    }

    if (custausu_rm_client_is_placement_dismissed($placement)) {
      $locale_is_it = function_exists('get_user_locale')
        ? strpos(strtolower(get_user_locale()), 'it') === 0
        : strpos(strtolower(get_locale()), 'it') === 0;

      $show_label = $locale_is_it
        ? 'Mostra i Messaggi Remoti di Custom Auth Suite™'
        : 'Show Custom Auth Suite™ Remote Messages';

      ?>
      <div class="custausu-rm-admin-top-restore">
        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
          <?php wp_nonce_field('custausu_rm_dismiss_admin_top'); ?>
          <input type="hidden" name="action" value="custausu_rm_dismiss_admin_top">
          <input type="hidden" name="custausu_rm_mode" value="show">
          <input type="hidden" name="placement" value="<?php echo esc_attr($placement); ?>">
          <input type="hidden" name="redirect_to" value="<?php echo esc_url(custausu_rm_client_current_admin_url()); ?>">
          <button type="submit" class="button custausu-rm-admin-top-restore__btn"><?php echo esc_html($show_label); ?></button>
        </form>
      </div>
      <?php

      return;
    }

    $messages = custausu_rm_client_fetch_messages($placement);

    if (empty($messages)) {
      return;
    }

    $locale_is_it = function_exists('get_user_locale')
      ? strpos(strtolower(get_user_locale()), 'it') === 0
      : strpos(strtolower(get_locale()), 'it') === 0;

    $heading = $locale_is_it ? 'Aggiornamenti Custom Auth Suite™' : 'Custom Auth Suite™ updates';

    if (custausu_rm_client_is_public_free_build()) {
      $summary = $locale_is_it
        ? 'Sicurezza, compatibilità, manutenzione, documentazione e supporto'
        : 'Security, compatibility, maintenance, documentation and support';
    } else {
      $summary = $locale_is_it
        ? 'Messaggi, supporto, licenze e contenuti utili'
        : 'Messages, support, licenses and useful content';
    }
    $dismiss_label = $locale_is_it ? 'Nascondi per 3 giorni' : 'Hide for 3 days';

    ?>
    <div class="custausu-rm-admin-top-wrap">
      <details class="custausu-rm-admin-top" open>
        <summary>
          <span class="custausu-rm-admin-top__title"><?php echo esc_html($heading); ?></span>
          <span class="custausu-rm-admin-top__subtitle"><?php echo esc_html($summary); ?></span>
        </summary>

        <div class="custausu-rm-admin-top__body">
          <div class="custausu-rm-admin-top__slider" data-custausu-rm-slider data-custausu-rm-autoplay-delay="7000" tabindex="0">
            <div class="custausu-rm-admin-top__slides" aria-label="<?php echo esc_attr($heading); ?>">
              <?php foreach ($messages as $custausu_rm_index => $message): ?>
                <?php
                  $custausu_rm_slide_active_class = $custausu_rm_index === 0 ? 'is-active' : '';
                  $custausu_rm_slide_hidden = $custausu_rm_index === 0 ? 'false' : 'true';
                  $custausu_rm_slide_event_attrs_escaped = custausu_rm_client_event_attrs(
                    $message,
                    $placement,
                    (string) ($message['title'] ?? ''),
                    (string) ($message['cta_label'] ?? '')
                  );
                ?>
                <article class="custausu-rm-admin-top__slide custausu-rm-admin-top__slide--<?php echo esc_attr($message['category'] ?: 'message'); ?> <?php echo esc_attr($custausu_rm_slide_active_class); ?>" aria-hidden="<?php echo esc_attr($custausu_rm_slide_hidden); ?>"<?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Event tracking attributes are generated by controlled escaped helper. ?><?php echo $custausu_rm_slide_event_attrs_escaped; ?>>
                <?php if (!empty($message['image_desktop']) || !empty($message['image_mobile'])): ?>
                  <picture>
                    <?php if (!empty($message['image_mobile'])): ?>
                      <source media="(max-width: 782px)" srcset="<?php echo esc_url($message['image_mobile']); ?>">
                    <?php endif; ?>

                    <?php if (!empty($message['image_desktop'])): ?>
                      <img src="<?php echo esc_url($message['image_desktop']); ?>" alt="" loading="lazy">
                    <?php elseif (!empty($message['image_mobile'])): ?>
                      <img src="<?php echo esc_url($message['image_mobile']); ?>" alt="" loading="lazy">
                    <?php endif; ?>
                  </picture>
                <?php endif; ?>

                <div class="custausu-rm-admin-top__content">
                  <div class="custausu-rm-admin-top__meta">
                    <?php if (!empty($message['category'])): ?>
                      <span><?php echo esc_html($message['category']); ?></span>
                    <?php endif; ?>

                    <?php if (!empty($message['audience_mode'])): ?>
                      <span><?php echo esc_html($message['audience_mode']); ?></span>
                    <?php endif; ?>
                  </div>

                  <h2><?php echo esc_html($message['title']); ?></h2>

                  <?php if (!empty($message['subtitle'])): ?>
                    <p class="custausu-rm-admin-top__subtitle-line"><?php echo esc_html($message['subtitle']); ?></p>
                  <?php endif; ?>

                  <?php if (!empty($message['body'])): ?>
                    <p><?php echo esc_html($message['body']); ?></p>
                  <?php endif; ?>

                  <?php if (!empty($message['body_secondary'])): ?>
                    <p class="custausu-rm-admin-top__body-secondary"><?php echo esc_html($message['body_secondary']); ?></p>
                  <?php endif; ?>

                  <?php if (!empty($message['cta_label']) && !empty($message['cta_url'])): ?>
                    <a class="button button-primary custausu-rm-admin-top__cta" href="<?php echo esc_url($message['cta_url']); ?>" target="_blank" rel="noopener" data-custausu-rm-event-cta="1">
                      <?php echo esc_html($message['cta_label']); ?>
                    </a>
                  <?php endif; ?>
                </div>
                </article>
              <?php endforeach; ?>
            </div>

            <?php if (count($messages) > 1): ?>
              <div class="custausu-rm-admin-top__nav" aria-label="<?php echo esc_attr($locale_is_it ? 'Navigazione messaggi' : 'Message navigation'); ?>">
                <button type="button" class="button custausu-rm-admin-top__nav-btn" data-custausu-rm-prev aria-label="<?php echo esc_attr($locale_is_it ? 'Messaggio precedente' : 'Previous message'); ?>">‹</button>

                <div class="custausu-rm-admin-top__dots">
                  <?php foreach ($messages as $custausu_rm_dot_index => $message): ?>
                    <button
                      type="button"
                      class="custausu-rm-admin-top__dot <?php echo $custausu_rm_dot_index === 0 ? 'is-active' : ''; ?>"
                      data-custausu-rm-dot
                      aria-label="<?php echo esc_attr(($locale_is_it ? 'Vai al messaggio ' : 'Go to message ') . (string) ($custausu_rm_dot_index + 1)); ?>"
                      aria-current="<?php echo $custausu_rm_dot_index === 0 ? 'true' : 'false'; ?>"
                    ></button>
                  <?php endforeach; ?>
                </div>

                <button type="button" class="button custausu-rm-admin-top__nav-btn" data-custausu-rm-next aria-label="<?php echo esc_attr($locale_is_it ? 'Messaggio successivo' : 'Next message'); ?>">›</button>
              </div>
            <?php endif; ?>
          </div>

          <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="custausu-rm-admin-top__dismiss" data-custausu-rm-dismiss-warning="<?php echo esc_attr($locale_is_it
            ? 'I messaggi remoti di Custom Auth Suite™ possono includere aggiornamenti importanti, offerte, contenuti utili e avvisi di compatibilità. Vuoi davvero nasconderli per 3 giorni?'
            : 'Custom Auth Suite™ remote messages may include important updates, offers, useful content and compatibility notices. Do you really want to hide them for 3 days?'
          ); ?>">
            <?php wp_nonce_field('custausu_rm_dismiss_admin_top'); ?>
            <input type="hidden" name="action" value="custausu_rm_dismiss_admin_top">
            <input type="hidden" name="placement" value="<?php echo esc_attr($placement); ?>">
            <input type="hidden" name="days" value="3">
            <input type="hidden" name="redirect_to" value="<?php echo esc_url(custausu_rm_client_current_admin_url()); ?>">
            <button type="submit" class="button"><?php echo esc_html($dismiss_label); ?></button>
          </form>
        </div>
      </details>
    </div>
    <?php
  }
}

add_action('admin_notices', 'custausu_rm_client_render_admin_top', 20);

if (!function_exists('custausu_rm_client_handle_dismiss_admin_top')) {
  function custausu_rm_client_handle_dismiss_admin_top(): void {
    if (!current_user_can('manage_options')) {
      wp_die('Forbidden.');
    }

    check_admin_referer('custausu_rm_dismiss_admin_top');

    $placement = isset($_POST['placement']) ? sanitize_key((string) wp_unslash($_POST['placement'])) : 'admin_dashboard';
    $days = isset($_POST['days']) ? absint(wp_unslash($_POST['days'])) : 5;
    $mode = isset($_POST['custausu_rm_mode']) ? sanitize_key((string) wp_unslash($_POST['custausu_rm_mode'])) : 'hide';

    $message_id = isset($_POST['message_id']) ? sanitize_key((string) wp_unslash($_POST['message_id'])) : '';
    $dismiss_hash = isset($_POST['dismiss_hash']) ? substr(sanitize_key((string) wp_unslash($_POST['dismiss_hash'])), 0, 32) : '';
    $ttl_seconds = isset($_POST['ttl_seconds']) ? absint(wp_unslash($_POST['ttl_seconds'])) : 300;

    if ($mode === 'hide_message') {
      custausu_rm_client_dismiss_message($placement, $message_id, $dismiss_hash, $ttl_seconds);
    } elseif ($mode === 'show') {
      custausu_rm_client_clear_placement_dismissal($placement);
    } else {
      custausu_rm_client_dismiss_placement($placement, $days);
    }

    $custausu_rm_requested_with = isset($_SERVER['HTTP_X_REQUESTED_WITH'])
      ? strtolower(sanitize_text_field((string) wp_unslash($_SERVER['HTTP_X_REQUESTED_WITH'])))
      : '';

    $custausu_rm_ajax = isset($_POST['custausu_rm_ajax'])
      ? sanitize_key((string) wp_unslash($_POST['custausu_rm_ajax']))
      : '';

    if (
      (defined('DOING_AJAX') && DOING_AJAX)
      || $custausu_rm_requested_with === 'xmlhttprequest'
      || $custausu_rm_ajax === '1'
    ) {
      wp_send_json_success([
        'placement' => $placement,
        'mode' => $mode,
        'days' => $days,
        'message_id' => $message_id,
        'ttl_seconds' => $ttl_seconds,
      ]);
    }

    $redirect = isset($_POST['redirect_to']) ? esc_url_raw((string) wp_unslash($_POST['redirect_to'])) : admin_url();

    wp_safe_redirect($redirect);
    exit;
  }
}

add_action('admin_post_custausu_rm_dismiss_admin_top', 'custausu_rm_client_handle_dismiss_admin_top');
