<?php
/**
 * Public Free administration services.
 *
 * Provides two Free-safe areas:
 * 1. local, read-only information about separately distributed editions;
 * 2. optional external assisted-support diagnostics using signed, time-limited
 *    tokens and explicitly authorized scopes.
 *
 * The external support service may require a separate paid support entitlement.
 * This file does not manage product licenses, contact a license-validation
 * server, or unlock Advanced/Premium functionality.
 */

if (!defined('ABSPATH')) {
  exit;
}

if (!function_exists('custausu_admin_support_diagnostics_t')) {
  function custausu_admin_support_diagnostics_t(
    string $english,
    string $italian = ''
  ): string {
    $locale = function_exists('get_user_locale')
      ? (string)get_user_locale()
      : (function_exists('get_locale') ? (string)get_locale() : 'en_US');

    return str_starts_with(strtolower($locale), 'it')
      ? ($italian !== '' ? $italian : $english)
      : $english;
  }
}

if (!function_exists('custausu_admin_support_diagnostics_notice_key')) {
  function custausu_admin_support_diagnostics_notice_key(): string {
    return 'custausu_support_diagnostics_admin_notice_' . get_current_user_id();
  }
}

if (!function_exists('custausu_admin_support_diagnostics_set_notice')) {
  function custausu_admin_support_diagnostics_set_notice(
    string $type,
    string $message
  ): void {
    set_transient(
      custausu_admin_support_diagnostics_notice_key(),
      [
        'type' => sanitize_key($type),
        'message' => sanitize_text_field($message),
      ],
      2 * MINUTE_IN_SECONDS
    );
  }
}

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

    $key = custausu_admin_support_diagnostics_notice_key();
    $notice = get_transient($key);
    delete_transient($key);

    if (!is_array($notice) || empty($notice['message'])) {
      return;
    }

    $type = sanitize_key((string)($notice['type'] ?? 'info'));
    if (!in_array($type, ['success', 'warning', 'error', 'info'], true)) {
      $type = 'info';
    }

    echo '<div class="notice notice-' . esc_attr($type) . ' is-dismissible"><p>'
      . esc_html((string)$notice['message'])
      . '</p></div>';
  }
}

if (!function_exists('custausu_admin_support_diagnostics_status_badge')) {
  function custausu_admin_support_diagnostics_status_badge(
    string $status,
    callable $T
  ): string {
    $status = sanitize_key($status);

    if ($status === '') {
      $status = 'none';
    }

    $class = 'custausu-support-diagnostics-badge is-neutral';

    if ($status === 'active') {
      $class = 'custausu-support-diagnostics-badge is-active';
    } elseif (
      in_array(
        $status,
        ['invalid', 'expired', 'revoked', 'locally_revoked'],
        true
      )
    ) {
      $class = 'custausu-support-diagnostics-badge is-invalid';
    }

    $label = match ($status) {
      'active'          => $T('active', 'attivo'),
      'expired'         => $T('expired', 'scaduto'),
      'revoked'         => $T('revoked', 'revocato'),
      'locally_revoked' => $T(
        'locally revoked',
        'revocato localmente'
      ),
      'invalid'         => $T('invalid', 'non valido'),
      'none'            => $T('none', 'nessuno'),
      default           => $status,
    };

    return '<span class="' . esc_attr($class) . '">'
      . esc_html($label)
      . '</span>';
  }
}

if (!function_exists('custausu_admin_support_diagnostics_capability_label')) {
  function custausu_admin_support_diagnostics_capability_label(string $capability, callable $T): string {
    $capability = sanitize_key($capability);

    $labels = [
      'health_check'          => $T('Health Check snapshot', 'Snapshot controllo stato'),
      'package_context_read' => $T('Installed package context', 'Contesto pacchetto installato'),
      'rest_connectivity'    => $T('REST/API connectivity snapshot', 'Snapshot connettività REST/API'),
      'settings_snapshot'    => $T('Sanitized settings snapshot', 'Snapshot impostazioni sanitizzato'),
      'logs_read'            => $T('Runtime diagnostics log viewer', 'Visore log diagnostica runtime'),
      'plugin_inventory'     => $T('Installed plugin inventory', 'Inventario plugin installati'),
      'diagnostic_export'    => $T('Diagnostic export readiness', 'Preparazione export diagnostico'),
    ];

    return $labels[$capability] ?? $capability;
  }
}

if (!function_exists('custausu_admin_support_diagnostics_reason_label')) {
  function custausu_admin_support_diagnostics_reason_label(string $reason, callable $T): string {
    $reason = sanitize_key($reason);

    $labels = [
      'ok'                  => $T('Token valid.', 'Token valido.'),
      'empty_token'         => $T('No token stored.', 'Nessun token salvato.'),
      'malformed_token'     => $T('Malformed token.', 'Token malformato.'),
      'decode_failed'       => $T('Token decode failed.', 'Decodifica token non riuscita.'),
      'invalid_payload_json'=> $T('Invalid token payload.', 'Payload token non valido.'),
      'openssl_unavailable' => $T('OpenSSL is not available.', 'OpenSSL non è disponibile.'),
      'public_key_missing'  => $T('Support public key is missing in this build.', 'La chiave pubblica supporto manca in questa build.'),
      'public_key_invalid'  => $T('Support public key is invalid.', 'La chiave pubblica supporto non è valida.'),
      'signature_invalid'   => $T('Invalid token signature.', 'Firma token non valida.'),
      'claims_invalid'      => $T('Invalid token claims.', 'Claims token non validi.'),
      'claims_incomplete'   => $T('Incomplete token claims.', 'Claims token incompleti.'),
      'scope_mismatch'      => $T('Token does not match this site.', 'Il token non corrisponde a questo sito.'),
      'issued_in_future'    => $T('Token issue date is invalid.', 'La data emissione token non è valida.'),
      'not_before'          => $T('Token is not valid yet.', 'Il token non è ancora valido.'),
      'token_expired'       => $T('Token expired.', 'Token scaduto.'),
      'duration_too_long'   => $T('Token duration is too long.', 'La durata del token è troppo lunga.'),
      'invalid_token'       => $T('Invalid token.', 'Token non valido.'),
      'locally_revoked'   => $T('Revoked locally.', 'Revocato localmente.'),
      'token_too_long' => $T('Token is too long.', 'Il token è troppo lungo.'),
      'jti_missing' => $T('Token identifier is missing.', 'Identificativo token mancante.'),
      'revocation_url_missing' => $T('Revocation endpoint is missing.', 'Endpoint di revoca mancante.'),
      'revocation_check_failed' => $T('Remote revocation check failed.', 'Controllo remoto revoca non riuscito.'),
      'revocation_endpoint_invalid_response' => $T('Revocation endpoint returned an invalid response.', 'L’endpoint di revoca ha restituito una risposta non valida.'),
      'revocation_endpoint_error' => $T('Revocation endpoint error.', 'Errore endpoint revoca.'),
      'token_revoked_remote' => $T('Token has been revoked by CAS Support Desk.', 'Il token è stato revocato da CAS Support Desk.'),
      'token_unknown_remote' => $T('Token is unknown to CAS Support Desk.', 'Il token non è riconosciuto da CAS Support Desk.'),
    ];

    return $labels[$reason] ?? ($reason !== '' ? $reason : $T('Unknown.', 'Sconosciuto.'));
  }
}


if (!function_exists('custausu_admin_support_diagnostics_report_hash_tag')) {
  function custausu_admin_support_diagnostics_report_hash_tag($value): string {
    if (function_exists('custausu_debug_privacy_hash_tag')) {
      return custausu_debug_privacy_hash_tag($value);
    }

    $value = trim((string) $value);

    if ($value === '') {
      return 'empty';
    }

    return substr(
      hash_hmac(
        'sha256',
        strtolower($value),
        wp_salt('auth')
      ),
      0,
      12
    );
  }
}

if (!function_exists('custausu_admin_support_diagnostics_report_identifier')) {
  function custausu_admin_support_diagnostics_report_identifier(
    $value,
    string $kind = 'identifier'
  ): string {
    return '[redacted-' . sanitize_key($kind)
      . ' hash='
      . custausu_admin_support_diagnostics_report_hash_tag($value)
      . ']';
  }
}

if (!function_exists('custausu_admin_support_diagnostics_report_website_datetime')) {
  function custausu_admin_support_diagnostics_report_website_datetime(
    $utc_value
  ): string {
    $utc_value = trim((string) $utc_value);

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

    $timestamp = strtotime($utc_value . ' UTC');

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

    return wp_date(
      'Y-m-d H:i:s T',
      $timestamp,
      wp_timezone()
    );
  }
}

if (!function_exists('custausu_admin_support_diagnostics_report_token_state')) {
  function custausu_admin_support_diagnostics_report_token_state(
    array $state
  ): array {
    $issued_at = sanitize_text_field(
      (string) ($state['issued_at'] ?? '')
    );

    $expires_at = sanitize_text_field(
      (string) ($state['expires_at'] ?? '')
    );

    $revocation_checked_at = sanitize_text_field(
      (string) ($state['revocation_checked_at'] ?? '')
    );

    $checked_at = sanitize_text_field(
      (string) ($state['checked_at'] ?? '')
    );

    $activated_at = sanitize_text_field(
      (string) ($state['activated_at_utc'] ?? '')
    );

    return [
      'schema_version' => absint(
        $state['schema_version'] ?? 1
      ),
      'status' => sanitize_key(
        (string) ($state['status'] ?? 'none')
      ),
      'issued_at_utc' => $issued_at,
      'issued_at_website_timezone' =>
        custausu_admin_support_diagnostics_report_website_datetime(
          $issued_at
        ),
      'expires_at_utc' => $expires_at,
      'expires_at_website_timezone' =>
        custausu_admin_support_diagnostics_report_website_datetime(
          $expires_at
        ),
      'scope' => sanitize_key(
        (string) ($state['scope'] ?? '')
      ),
      'case_id' => sanitize_text_field(
        (string) ($state['case_id'] ?? '')
      ),
      'revocation_checked_at_utc' =>
        $revocation_checked_at,
      'revocation_status' => sanitize_key(
        (string) ($state['revocation_status'] ?? '')
      ),
      'capabilities' => function_exists(
        'custausu_support_diagnostics_normalize_capabilities'
      )
        ? custausu_support_diagnostics_normalize_capabilities(
            $state['capabilities'] ?? []
          )
        : array_values(
            array_filter(
              array_map(
                'sanitize_key',
                (array) ($state['capabilities'] ?? [])
              )
            )
          ),
      'checked_at_utc' => $checked_at,
      'reason' => sanitize_key(
        (string) ($state['reason'] ?? '')
      ),
      'viewer_policy' => sanitize_key(
        (string) ($state['viewer_policy'] ?? '')
      ),
      'activated_at_utc' => $activated_at,
      'activated_at_website_timezone' =>
        custausu_admin_support_diagnostics_report_website_datetime(
          $activated_at
        ),
    ];
  }
}

if (!function_exists('custausu_admin_support_diagnostics_report_logs')) {
  function custausu_admin_support_diagnostics_report_logs(
    array $state
  ): array {
    $logs = function_exists(
      'custausu_debug_support_diagnostics_get_runtime_logs'
    )
      ? custausu_debug_support_diagnostics_get_runtime_logs()
      : get_option(
          'custausu_support_diagnostics_runtime_logs',
          []
        );

    if (!is_array($logs)) {
      return [];
    }

    $activated_at = trim(
      (string) ($state['activated_at_utc'] ?? '')
    );

    $activated_ts = $activated_at !== ''
      ? strtotime($activated_at . ' UTC')
      : false;

    $filtered = [];

    foreach ($logs as $log) {
      $log = is_array($log) ? $log : (array) $log;

      $time_utc = trim(
        (string) (
          $log['time_utc']
          ?? $log['created_at_utc']
          ?? $log['created_at']
          ?? $log['time']
          ?? $log['timestamp']
          ?? ''
        )
      );

      if ($activated_ts !== false && $time_utc !== '') {
        $row_ts = strtotime($time_utc . ' UTC');

        if ($row_ts !== false && $row_ts < $activated_ts) {
          continue;
        }
      }

      $filtered[] =
        custausu_admin_support_diagnostics_report_redact($log);
    }

    $max = (int) apply_filters(
      'custausu_support_diagnostics_report_logs_max_entries',
      80
    );

    $max = max(20, min(100, $max));

    return array_values(
      array_slice($filtered, -$max)
    );
  }
}

if (!function_exists('custausu_admin_support_diagnostics_report_redact')) {
  function custausu_admin_support_diagnostics_report_redact(
    $value,
    string $key = '',
    int $depth = 0
  ) {
    if ($depth > 8) {
      return '[max-depth]';
    }

    $key_l = strtolower(
      trim(
        (string) preg_replace(
          '/[^a-z0-9]+/i',
          '_',
          $key
        )
      )
    );

    if (
      preg_match(
        '/(password|passwd|pwd|secret|token|license_?key|api_?key|private_?key|authorization|cookie|client_secret|signature|nonce)/i',
        $key_l
      )
    ) {
      return '[redacted]';
    }

    if (
      preg_match(
        '/(^|_)(email|e_mail|user_email|customer_email|your_email)($|_)/i',
        $key_l
      )
    ) {
      return '[redacted-email]';
    }

    if ($key_l === 'label') {
      return custausu_admin_support_diagnostics_report_identifier(
        is_scalar($value) ? $value : '',
        'support-label'
      );
    }

    if (
      preg_match('/(^|_)jti(_hash)?($|_)/i', $key_l)
    ) {
      return custausu_admin_support_diagnostics_report_identifier(
        is_scalar($value) ? $value : '',
        'token-id'
      );
    }

    if (
      preg_match(
        '/(session_?hash|activated_by_session_hash)/i',
        $key_l
      )
    ) {
      return '[redacted-session-hash]';
    }

    if (
      preg_match(
        '/(^|_)(site_hash|host_hash|domain_hash|activation_hash|site_fingerprint)($|_)/i',
        $key_l
      )
    ) {
      return custausu_admin_support_diagnostics_report_identifier(
        is_scalar($value) ? $value : '',
        'site-id'
      );
    }

    if (
      preg_match(
        '/(^|_)(device_id|credential_id|credid|clientuhb64|sourceuhb64|truthuhb64|userhandle|user_handle|rawid|aaguid)($|_)/i',
        $key_l
      )
    ) {
      return custausu_admin_support_diagnostics_report_identifier(
        is_scalar($value) ? $value : '',
        'webauthn-id'
      );
    }

    if (
      preg_match(
        '/(^|_)(user_id|uid|activated_by_user_id|instance_id)($|_)/i',
        $key_l
      )
    ) {
      return custausu_admin_support_diagnostics_report_identifier(
        is_scalar($value) ? $value : '',
        'account-id'
      );
    }

    if (
      preg_match(
        '/(^|_)(ip|ip_address|remote_addr)($|_)/i',
        $key_l
      )
    ) {
      return custausu_admin_support_diagnostics_report_identifier(
        is_scalar($value) ? $value : '',
        'ip'
      );
    }

    if (
      preg_match(
        '/(^|_)(username|user_login|display_name|first_name|last_name|customer_name|full_name|your_name)($|_)/i',
        $key_l
      )
    ) {
      return custausu_admin_support_diagnostics_report_identifier(
        is_scalar($value) ? $value : '',
        'identity'
      );
    }

    if (
      preg_match(
        '/(^|_)(your_message|your_subject|message_body|message_content|body|content|subject)($|_)/i',
        $key_l
      )
    ) {
      if (function_exists('custausu_debug_privacy_text_summary')) {
        return custausu_debug_privacy_text_summary(
          $value,
          'form-text'
        );
      }

      return custausu_admin_support_diagnostics_report_identifier(
        is_scalar($value) ? $value : '',
        'form-text'
      );
    }

    if (is_array($value)) {
      $out = [];

      foreach ($value as $item_key => $item) {
        $out[$item_key] =
          custausu_admin_support_diagnostics_report_redact(
            $item,
            (string) $item_key,
            $depth + 1
          );
      }

      return $out;
    }

    if (is_object($value)) {
      return custausu_admin_support_diagnostics_report_redact(
        get_object_vars($value),
        $key,
        $depth + 1
      );
    }

    if (!is_scalar($value)) {
      return $value;
    }

    $string = (string) $value;
    $trimmed = ltrim($string);

    if (
      $trimmed !== ''
      && in_array($trimmed[0], ['{', '['], true)
    ) {
      $decoded = json_decode($string, true);

      if (is_array($decoded)) {
        return custausu_admin_support_diagnostics_report_redact(
          $decoded,
          $key,
          $depth + 1
        );
      }
    }

    $string = preg_replace(
      '/\\[email:[^\\]]+\\]/i',
      '[redacted-email]',
      $string
    ) ?? $string;

    $string = preg_replace(
      '/[A-Z0-9._%+\\-]+@[A-Z0-9.\\-]+\\.[A-Z]{2,}/i',
      '[redacted-email]',
      $string
    ) ?? $string;

    $string = preg_replace_callback(
      '/(["\\\'](?:device_id|credential_id|credId|clientUhB64|sourceUhB64|truthUhB64|userHandle|user_handle|rawId|aaguid|user_id|uid|activated_by_user_id|instance_id|jti|jti_hash|activated_by_session_hash)["\\\']\\s*:\\s*)["\\\'][^"\\\']*["\\\']/i',
      static function (array $match): string {
        return (string) ($match[1] ?? '')
          . '"[redacted-identifier]"';
      },
      $string
    ) ?? $string;

    $string = preg_replace(
      '/CAS-[A-Z0-9][A-Z0-9\\-]{11,}/i',
      'CAS-[redacted]',
      $string
    ) ?? $string;

    $string = preg_replace(
      '/-----BEGIN[^-]+PRIVATE KEY-----.*?-----END[^-]+PRIVATE KEY-----/s',
      '[redacted-private-key]',
      $string
    ) ?? $string;

    $string = preg_replace(
      '/([?&](?:token|key|license_key|password|secret|nonce)=)[^&\\s]+/i',
      '$1[redacted]',
      $string
    ) ?? $string;

    return $string;
  }
}

if (!function_exists('custausu_admin_support_diagnostics_report_cell')) {
  function custausu_admin_support_diagnostics_report_cell($value): string {
    $value = custausu_admin_support_diagnostics_report_redact($value);

    if (is_array($value) || is_object($value)) {
      $json = wp_json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
      return '<pre>' . esc_html(is_string($json) ? $json : '') . '</pre>';
    }

    if (is_bool($value)) {
      return esc_html($value ? 'yes' : 'no');
    }

    if ($value === null || $value === '') {
      return '<span class="muted">—</span>';
    }

    return esc_html((string) $value);
  }
}

if (!function_exists('custausu_admin_support_diagnostics_report_table')) {
  function custausu_admin_support_diagnostics_report_table(string $title, array $rows): string {
    ob_start();

    echo '<section>';
    echo '<h2>' . esc_html($title) . '</h2>';
    echo '<table>';
    echo '<tbody>';

    foreach ($rows as $key => $value) {
      echo '<tr>';
      echo '<th>' . esc_html((string) $key) . '</th>';
      echo '<td>' . wp_kses( custausu_admin_support_diagnostics_report_cell( $value ), custausu_admin_allowed_output_html() ) . '</td>';
      echo '</tr>';
    }

    echo '</tbody>';
    echo '</table>';
    echo '</section>';

    return (string) ob_get_clean();
  }
}

if (!function_exists('custausu_admin_support_diagnostics_report_plugin_inventory')) {
  function custausu_admin_support_diagnostics_report_plugin_inventory(
    array $inventory
  ): string {
    $buckets = [
      'known_cas_relevant' => 'Known CAS-relevant plugins',
      'other' => 'Other installed plugins',
    ];

    $groups = [
      'active' => 'Active',
      'inactive' => 'Inactive',
      'network_active' => 'Network active',
      'must_use' => 'Must-use',
      'drop_ins' => 'Drop-ins',
    ];

    ob_start();

    echo '<section>';
    echo '<h2>Installed plugin inventory</h2>';
    echo '<p class="muted">Limited inventory: name, slug, version and status only.</p>';

    foreach ($buckets as $bucket => $bucket_label) {
      echo '<h3>' . esc_html($bucket_label) . '</h3>';

      foreach ($groups as $group => $group_label) {
        $items = (array)($inventory[$bucket][$group] ?? []);

        echo '<h4>'
          . esc_html($group_label)
          . ' (' . esc_html((string)count($items)) . ')'
          . '</h4>';

        if ($items === []) {
          echo '<p class="muted">No plugins.</p>';
          continue;
        }

        echo '<table>';
        echo '<thead><tr>';
        echo '<th>Name</th><th>Slug</th><th>Version</th><th>Status</th>';
        echo '</tr></thead><tbody>';

        foreach ($items as $item) {
          $item = is_array($item) ? $item : [];

          echo '<tr>';
          echo '<td>' . esc_html((string)($item['name'] ?? '')) . '</td>';
          echo '<td><code>' . esc_html((string)($item['slug'] ?? '')) . '</code></td>';
          echo '<td><code>' . esc_html((string)($item['version'] ?? '')) . '</code></td>';
          echo '<td>' . esc_html((string)($item['status'] ?? '')) . '</td>';
          echo '</tr>';
        }

        echo '</tbody></table>';
      }
    }

    echo '</section>';

    return (string)ob_get_clean();
  }
}

if (!function_exists('custausu_admin_support_diagnostics_export_report_handle')) {
  function custausu_admin_support_diagnostics_export_report_handle(): void {
    if (!is_admin() || !current_user_can('manage_options')) {
      wp_die('Forbidden');
    }

    check_admin_referer('custausu_support_diagnostics_export_report');

    $state = function_exists('custausu_support_diagnostics_get_state')
      ? custausu_support_diagnostics_get_state()
      : [];

    if (
      !function_exists('custausu_support_diagnostics_is_active')
      || !custausu_support_diagnostics_is_active()
      || !function_exists('custausu_support_diagnostics_can')
      || !custausu_support_diagnostics_can('diagnostic_export')
      || !function_exists('custausu_support_diagnostics_current_admin_can_viewer')
      || !custausu_support_diagnostics_current_admin_can_viewer($state)
    ) {
      wp_die('Diagnostic export is not enabled for this admin session.');
    }

    global $wp_version;

    $package_context = function_exists('custausu_free_package_support_context')
      ? custausu_free_package_support_context()
      : [];

    $logs = custausu_admin_support_diagnostics_report_logs(
      is_array($state) ? $state : []
    );

    $case_id = !empty($state['case_id'])
      ? sanitize_file_name((string) $state['case_id'])
      : 'custausu-diagnostics';

    $filename = 'custausu-diagnostic-report-' . $case_id . '-' . gmdate('Ymd-His') . '.html';

    $generated_at_utc = gmdate('Y-m-d H:i:s');
    $token_expires_at = sanitize_text_field(
      (string) ($state['expires_at'] ?? '')
    );

    $summary = [
      'generated_at_utc' => $generated_at_utc,
      'generated_at_website_timezone' =>
        custausu_admin_support_diagnostics_report_website_datetime(
          $generated_at_utc
        ),
      'website_timezone' => wp_timezone_string(),
      'home_url'         => home_url('/'),
      'site_url'         => site_url('/'),
      'wp_version'       => isset($wp_version) ? (string) $wp_version : '',
      'php_version'      => PHP_VERSION,
      'case_id'          => $state['case_id'] ?? '',
      'token_status'     => $state['status'] ?? '',
      'token_scope'      => $state['scope'] ?? '',
      'token_expires_at_utc' => $token_expires_at,
      'token_expires_at_website_timezone' =>
        custausu_admin_support_diagnostics_report_website_datetime(
          $token_expires_at
        ),
      'capabilities'     => $state['capabilities'] ?? [],
      'logs_count'       => count($logs),
      'logs_limit'       => 80,
    ];

    $theme = wp_get_theme();

    $environment = [
      'active_theme'        => $theme ? $theme->get('Name') : '',
      'active_theme_version'=> $theme ? $theme->get('Version') : '',
      'is_multisite'       => is_multisite(),
      'wp_debug'           => defined('WP_DEBUG') && WP_DEBUG,
      'wp_environment_type'=> function_exists('wp_get_environment_type') ? wp_get_environment_type() : '',
      'timezone'           => wp_timezone_string(),
      'locale'             => get_locale(),
    ];

    $plugin_inventory = (
      function_exists('custausu_support_diagnostics_can')
      && custausu_support_diagnostics_can('plugin_inventory')
      && function_exists('custausu_support_report_plugin_inventory')
    )
      ? custausu_support_report_plugin_inventory()
      : [];

    ob_start();

    echo '<!doctype html>';
    echo '<html lang="en">';
    echo '<head>';
    echo '<meta charset="utf-8">';
    echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
    echo '<title>CAS Diagnostic Report</title>';
    if (function_exists('custausu_asset_enqueued_stylesheet_link_html')) {
      // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- WordPress generates the enqueued stylesheet link.
      echo custausu_asset_enqueued_stylesheet_link_html(
        'custausu-support-diagnostics-report',
        'inc/css/custausu-support-diagnostics-report.css'
      );
    }
    echo '</head>';
    echo '<body>';
    echo '<div class="wrap">';

    echo '<header>';
    echo '<h1>CAS Diagnostic Report</h1>';
    echo '<p class="muted">Human-readable support diagnostics export. Personal identifiers and security-sensitive values are omitted, redacted or pseudonymized before download.</p>';
    echo '</header>';

    echo wp_kses( custausu_admin_support_diagnostics_report_table('Export summary', $summary), custausu_admin_allowed_output_html() );
    echo wp_kses( custausu_admin_support_diagnostics_report_table('WordPress environment', $environment), custausu_admin_allowed_output_html() );

    if (
      $plugin_inventory !== []
      && function_exists('custausu_admin_support_diagnostics_report_plugin_inventory')
    ) {
      echo wp_kses( custausu_admin_support_diagnostics_report_plugin_inventory(
        $plugin_inventory
      ), custausu_admin_allowed_output_html() );
    }

    echo wp_kses( custausu_admin_support_diagnostics_report_table('Support diagnostics token state', custausu_admin_support_diagnostics_report_token_state((array) $state)), custausu_admin_allowed_output_html() );
    echo wp_kses( custausu_admin_support_diagnostics_report_table('Installed package context', custausu_admin_support_diagnostics_report_redact((array) $package_context)), custausu_admin_allowed_output_html() );

    echo '<section>';
    echo '<h2>Runtime diagnostics logs</h2>';

    if (empty($logs)) {
      echo '<p class="muted">No runtime diagnostics logs collected.</p>';
    } else {
      echo '<table class="log-table">';
      echo '<thead><tr>';
      echo '<th>Date / time</th>';
      echo '<th>Level</th>';
      echo '<th>Channel</th>';
      echo '<th>Message</th>';
      echo '<th>Data</th>';
      echo '</tr></thead>';
      echo '<tbody>';

      foreach ($logs as $log) {
        $log = is_array($log) ? $log : (array) $log;

        $time = $log['time_utc'] ?? $log['created_at_utc'] ?? $log['created_at'] ?? $log['time'] ?? $log['timestamp'] ?? '';
        $level = $log['level'] ?? '';
        $channel = $log['channel'] ?? '';
        $message = $log['message'] ?? '';

        $data = $log;
        foreach (['time_utc', 'created_at', 'created_at_utc', 'time', 'timestamp', 'level', 'channel', 'message'] as $known_key) {
          unset($data[$known_key]);
        }

        echo '<tr>';
        echo '<td>' . wp_kses( custausu_admin_support_diagnostics_report_cell( $time ), custausu_admin_allowed_output_html() ) . '</td>';
        echo '<td>' . wp_kses( custausu_admin_support_diagnostics_report_cell( $level ), custausu_admin_allowed_output_html() ) . '</td>';
        echo '<td>' . wp_kses( custausu_admin_support_diagnostics_report_cell( $channel ), custausu_admin_allowed_output_html() ) . '</td>';
        echo '<td>' . wp_kses( custausu_admin_support_diagnostics_report_cell( $message ), custausu_admin_allowed_output_html() ) . '</td>';
        echo '<td>' . wp_kses( custausu_admin_support_diagnostics_report_cell( $data ), custausu_admin_allowed_output_html() ) . '</td>';
        echo '</tr>';
      }

      echo '</tbody>';
      echo '</table>';
    }

    echo '</section>';

    echo '</div>';
    echo '</body>';
    echo '</html>';

    // Safe complete HTML download assembled above from escaped/KSES-bounded report components.
    $html_safe = (string) ob_get_clean();

    nocache_headers();

    header('Content-Type: text/html; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . strlen($html_safe));

    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $html_safe is a complete controlled HTML document download; HTML escaping here would corrupt the document.
    echo $html_safe;
    exit;
  }
}



if (!function_exists('custausu_admin_support_diagnostics_clean_url')) {
  function custausu_admin_support_diagnostics_clean_url(): string {
    return admin_url('admin.php?page=custausu-settings');
  }
}

if (!function_exists('custausu_admin_support_diagnostics_clear_confirmation_key')) {
  function custausu_admin_support_diagnostics_clear_confirmation_key(): string {
    return 'custausu_sd_clear_confirm_' . get_current_user_id();
  }
}

if (!function_exists('custausu_admin_support_diagnostics_delete_clear_confirmation')) {
  function custausu_admin_support_diagnostics_delete_clear_confirmation(): void {
    delete_transient(
      custausu_admin_support_diagnostics_clear_confirmation_key()
    );
  }
}

if (!function_exists('custausu_admin_support_diagnostics_create_clear_confirmation')) {
  function custausu_admin_support_diagnostics_create_clear_confirmation(
    string $context
  ): array {
    if (!current_user_can('manage_options')) {
      return [];
    }

    $context = sanitize_key($context);

    if (!in_array($context, ['panel', 'notice'], true)) {
      $context = 'panel';
    }

    $token = wp_generate_password(32, false, false);

    if (
      !is_string($token)
      || !preg_match('/\A[A-Za-z0-9]{32}\z/D', $token)
    ) {
      return [];
    }

    $confirmation = [
      'token'      => $token,
      'context'    => $context,
      'user_id'    => get_current_user_id(),
      'created_at' => time(),
      'expires_at' => time() + (5 * MINUTE_IN_SECONDS),
    ];

    set_transient(
      custausu_admin_support_diagnostics_clear_confirmation_key(),
      $confirmation,
      5 * MINUTE_IN_SECONDS
    );

    return $confirmation;
  }
}

if (!function_exists('custausu_admin_support_diagnostics_get_clear_confirmation')) {
  function custausu_admin_support_diagnostics_get_clear_confirmation(
    string $expected_context = ''
  ): array {
    if (!current_user_can('manage_options')) {
      return [];
    }

    $raw_token = '';

    /*
     * WPORG-07G2B2A: nonce-verification scope.
     *
     * This block performs only a read-only lookup of a user-scoped,
     * short-lived transient. The POST token is needed to derive the
     * token-bound nonce action; the caller verifies that dedicated nonce
     * before cancellation or revocation. The GET token only reveals the
     * confirmation UI and cannot change state.
     */
    // phpcs:disable WordPress.Security.NonceVerification.Missing,WordPress.Security.NonceVerification.Recommended
    if (isset($_POST['custausu_support_diagnostics_confirmation'])) {
      $raw_token = sanitize_text_field(
        wp_unslash(
          $_POST['custausu_support_diagnostics_confirmation']
        )
      );
    } elseif (
      isset($_GET['custausu_support_diagnostics_confirm_clear'])
    ) {
      $raw_token = sanitize_text_field(
        wp_unslash(
          $_GET['custausu_support_diagnostics_confirm_clear']
        )
      );
    }
    // phpcs:enable WordPress.Security.NonceVerification.Missing,WordPress.Security.NonceVerification.Recommended

    if (
      $raw_token === ''
      || !preg_match('/\A[A-Za-z0-9]{32}\z/D', $raw_token)
    ) {
      return [];
    }

    $stored = get_transient(
      custausu_admin_support_diagnostics_clear_confirmation_key()
    );

    if (!is_array($stored)) {
      return [];
    }

    $stored_token = (string)($stored['token'] ?? '');
    $stored_user  = absint($stored['user_id'] ?? 0);
    $stored_context = sanitize_key(
      (string)($stored['context'] ?? '')
    );
    $expires_at = absint($stored['expires_at'] ?? 0);

    if (
      $stored_token === ''
      || !hash_equals($stored_token, $raw_token)
      || $stored_user !== get_current_user_id()
      || $expires_at < time()
    ) {
      custausu_admin_support_diagnostics_delete_clear_confirmation();
      return [];
    }

    $expected_context = sanitize_key($expected_context);

    if (
      $expected_context !== ''
      && $stored_context !== $expected_context
    ) {
      return [];
    }

    return $stored;
  }
}

if (!function_exists('custausu_admin_support_diagnostics_clear_confirmation_url')) {
  function custausu_admin_support_diagnostics_clear_confirmation_url(
    string $context,
    string $token
  ): string {
    $context = sanitize_key($context);

    if (!in_array($context, ['panel', 'notice'], true)) {
      $context = 'panel';
    }

    $token = sanitize_text_field($token);

    if ($context === 'notice') {
      return add_query_arg(
        [
          'custausu_support_diagnostics_confirm_clear' => $token,
        ],
        custausu_admin_support_diagnostics_clean_url()
      );
    }

    $url = add_query_arg(
      [
        'custausu_support_diagnostics'               => '1',
        'custausu_support_diagnostics_confirm_clear' => $token,
      ],
      custausu_admin_support_diagnostics_clean_url()
    );

    return $url . '#custausu-section-license';
  }
}

if (!function_exists('custausu_admin_support_diagnostics_clear_cancel_url')) {
  function custausu_admin_support_diagnostics_clear_cancel_url(
    string $context
  ): string {
    return sanitize_key($context) === 'notice'
      ? custausu_admin_support_diagnostics_clean_url()
      : custausu_admin_support_diagnostics_panel_url();
  }
}

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

    $state = function_exists(
      'custausu_support_diagnostics_get_stored_state'
    )
      ? custausu_support_diagnostics_get_stored_state()
      : [];

    $state = is_array($state) ? $state : [];

    if (
      sanitize_key(
        (string)($state['status'] ?? 'none')
      ) !== 'active'
    ) {
      return;
    }

    if (
      function_exists(
        'custausu_support_diagnostics_current_admin_can_viewer'
      )
      && custausu_support_diagnostics_current_admin_can_viewer($state)
    ) {
      return;
    }

    $expires_at = sanitize_text_field(
      (string)($state['expires_at'] ?? '')
    );

    $expires_label = $expires_at !== ''
      ? get_date_from_gmt(
          $expires_at,
          trim(
            (string)get_option('date_format')
            . ' '
            . (string)get_option('time_format')
          )
        )
      : '';

    $title = function_exists('custausu_admin_support_diagnostics_t')
      ? custausu_admin_support_diagnostics_t(
          'Custom Auth Suite™: The Remote Support Diagnostics session is active.',
          'Custom Auth Suite™: La sessione di Diagnostica di Supporto Remoto è attiva.'
        )
      : 'Custom Auth Suite™: The Remote Support Diagnostics session is active.';

    $description = function_exists('custausu_admin_support_diagnostics_t')
      ? custausu_admin_support_diagnostics_t(
          'Diagnostic details, logs and reports remain restricted to the authorized support session. Any site administrator may end and locally revoke this temporary session.',
          'Dettagli diagnostici, log e report restano riservati alla sessione di supporto autorizzata. Qualsiasi amministratore del sito può terminare e revocare localmente questa sessione temporanea.'
        )
      : 'Diagnostic details, logs and reports remain restricted to the authorized support session.';

    $expiry_text = function_exists('custausu_admin_support_diagnostics_t')
      ? custausu_admin_support_diagnostics_t(
          'Scheduled expiry:',
          'Scadenza prevista:'
        )
      : 'Scheduled expiry:';

    $button = function_exists('custausu_admin_support_diagnostics_t')
      ? custausu_admin_support_diagnostics_t(
          'End and revoke on this site',
          'Termina e revoca su questo sito'
        )
      : 'End and revoke on this site';

    $confirmation = function_exists(
      'custausu_admin_support_diagnostics_get_clear_confirmation'
    )
      ? custausu_admin_support_diagnostics_get_clear_confirmation(
          'notice'
        )
      : [];

    echo '<div class="notice notice-warning custausu-support-diagnostics-admin-notice">';
    echo '<p><strong>' . esc_html($title) . '</strong></p>';
    echo '<p>' . esc_html($description) . '</p>';

    if ($expires_label !== '') {
      echo '<p><strong>'
        . esc_html($expiry_text)
        . '</strong> '
        . esc_html($expires_label)
        . '</p>';
    }

    if (!empty($confirmation['token'])) {
      $confirm_token = (string)$confirmation['token'];

      echo '<div class="custausu-support-diagnostics-confirmation" role="alert">';
      echo '<p><strong>'
        . esc_html(
          custausu_admin_support_diagnostics_t(
            'Confirm termination and local revocation',
            'Conferma termine e revoca locale'
          )
        )
        . '</strong></p>';

      echo '<p>'
        . esc_html(
          custausu_admin_support_diagnostics_t(
            'This immediately ends the local diagnostic session, removes its runtime logs and prevents this token from being used again on this site.',
            'Questa operazione termina immediatamente la sessione diagnostica locale, rimuove i relativi log runtime e impedisce che questo token venga riutilizzato su questo sito.'
          )
        )
        . '</p>';

      echo '<form method="post" action="'
        . esc_url(admin_url('admin-post.php'))
        . '">';

      echo '<input type="hidden" name="action" value="custausu_support_diagnostics_action">';
      echo '<input type="hidden" name="custausu_support_diagnostics_context" value="notice">';
      echo '<input type="hidden" name="custausu_support_diagnostics_confirmation" value="'
        . esc_attr($confirm_token)
        . '">';

      wp_nonce_field(
        'custausu_support_diagnostics_clear_confirm_' . $confirm_token,
        'custausu_support_diagnostics_clear_nonce'
      );

      echo '<div class="custausu-support-diagnostics-confirmation-actions">';

      echo '<button type="submit" name="do" value="clear_cancel" class="button">'
        . esc_html(
          custausu_admin_support_diagnostics_t('Cancel', 'Annulla')
        )
        . '</button>';

      echo '<button type="submit" name="do" value="clear_confirm" class="button custausu-support-diagnostics-final-revoke">'
        . esc_html(
          custausu_admin_support_diagnostics_t(
            'Confirm end and revoke',
            'Conferma termine e revoca'
          )
        )
        . '</button>';

      echo '</div>';
      echo '</form>';
      echo '</div>';
    } else {
      echo '<form method="post" action="'
        . esc_url(admin_url('admin-post.php'))
        . '">';

      echo '<input type="hidden" name="action" value="custausu_support_diagnostics_action">';
      echo '<input type="hidden" name="do" value="clear_prepare">';
      echo '<input type="hidden" name="custausu_support_diagnostics_context" value="notice">';

      wp_nonce_field('custausu_support_diagnostics_action');

      echo '<p><button type="submit" class="button button-secondary">'
        . esc_html($button)
        . '</button></p>';

      echo '</form>';
    }

    echo '</div>';
  }
}

if (!function_exists('custausu_admin_support_diagnostics_requested')) {
  function custausu_admin_support_diagnostics_requested(): bool {
    if (!is_admin() || !current_user_can('manage_options')) {
      return false;
    }

    $flag = '';

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin query arg used only to open the support diagnostics panel; no state change is performed here.
    if (isset($_GET['custausu_support_diagnostics'])) {
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin query arg is unslashed and sanitized immediately.
      $flag = sanitize_key((string) wp_unslash($_GET['custausu_support_diagnostics']));
    }

    return in_array($flag, ['1', 'yes', 'show', 'open'], true);
  }
}

if (!function_exists('custausu_admin_support_diagnostics_has_state')) {
  function custausu_admin_support_diagnostics_has_state(): bool {
    if (!is_admin() || !current_user_can('manage_options')) {
      return false;
    }

    $states = [];

    if (function_exists('custausu_support_diagnostics_get_state')) {
      $state = custausu_support_diagnostics_get_state();
      if (is_array($state)) {
        $states[] = $state;
      }
    }

    if (function_exists('custausu_support_diagnostics_get_stored_state')) {
      $state = custausu_support_diagnostics_get_stored_state();
      if (is_array($state)) {
        $states[] = $state;
      }
    }

    foreach ([
      'custausu_support_diagnostics_state',
      'cas_support_diagnostics_state', // Legacy cleanup after prefix migration.
      'custausu_support_diagnostics',
      'custausu_support_diagnostics_token_state',
    ] as $option_name) {
      $state = get_option($option_name, []);
      if (is_array($state) && !empty($state)) {
        $states[] = $state;
      }
    }

    foreach ($states as $state) {
      $status = sanitize_key((string)($state['status'] ?? 'none'));
      $token  = trim((string)($state['token'] ?? ''));

      if ($token !== '') {
        return true;
      }

      if (in_array($status, ['active', 'expired', 'invalid'], true)) {
        return true;
      }
    }

    return false;
  }
}

if (!function_exists('custausu_admin_support_diagnostics_should_render')) {
  function custausu_admin_support_diagnostics_should_render(): bool {
    if (custausu_admin_support_diagnostics_requested()) {
      return true;
    }

    if (!custausu_admin_support_diagnostics_has_state()) {
      return false;
    }

    if (!function_exists('custausu_support_diagnostics_current_admin_can_viewer')) {
      return false;
    }

    return custausu_support_diagnostics_current_admin_can_viewer();
  }
}

if (!function_exists('custausu_admin_render_support_diagnostics_rows')) {
  function custausu_admin_render_support_diagnostics_rows(callable $T): string {
    if (!custausu_admin_support_diagnostics_should_render()) {
      return '';
    }

    $state = function_exists('custausu_support_diagnostics_get_state')
      ? custausu_support_diagnostics_get_state()
      : [];

    $state = is_array($state) ? $state : [];

    $status = sanitize_key((string)($state['status'] ?? 'none'));
    $can_view_diagnostics = function_exists('custausu_support_diagnostics_current_admin_can_viewer')
      ? custausu_support_diagnostics_current_admin_can_viewer($state)
      : false;
    $can_clear_diagnostics = function_exists('custausu_support_diagnostics_current_admin_can_clear_token')
      ? custausu_support_diagnostics_current_admin_can_clear_token($state)
      : false;
    $reason = sanitize_key((string)($state['reason'] ?? ''));

    $clear_confirmation = function_exists(
      'custausu_admin_support_diagnostics_get_clear_confirmation'
    )
      ? custausu_admin_support_diagnostics_get_clear_confirmation(
          'panel'
        )
      : [];

    $clear_confirmation_requested =
      !empty($clear_confirmation['token']);


    $is_requested_by_url = custausu_admin_support_diagnostics_requested();
    $is_active_support   = ($status === 'active');
    $is_token_state      = custausu_admin_support_diagnostics_has_state();

    $has_public_key = function_exists('custausu_support_diagnostics_get_public_key')
      && custausu_support_diagnostics_get_public_key() !== '';

    $site_hash = function_exists('custausu_support_diagnostics_site_hash') ? custausu_support_diagnostics_site_hash() : '';
    $host_hash = function_exists('custausu_support_diagnostics_host_hash') ? custausu_support_diagnostics_host_hash() : '';

    $capabilities = function_exists('custausu_support_diagnostics_normalize_capabilities')
      ? custausu_support_diagnostics_normalize_capabilities($state['capabilities'] ?? [])
      : [];

    ob_start();

    /*
     * Full-width diagnostics section.
     *
     * Keep the section title above the complete diagnostics interface rather
     * than reserving a separate WordPress table label column.
     */
    echo '<tr class="custausu-support-diagnostics-row">';
    echo '<td colspan="2" class="custausu-support-diagnostics-cell">';
    echo '<h3 class="custausu-support-diagnostics-section-title">'
      . esc_html($T('Remote support diagnostics', 'Diagnostica supporto remoto'))
      . '</h3>';

    echo '<div class="custausu-support-diagnostics-box">';

    echo '<div class="custausu-support-diagnostics-head">';
    echo '<div>';
    echo '<strong>' . esc_html($T('Temporary support access', 'Accesso temporaneo supporto')) . '</strong>';
    echo '<p class="description custausu-support-diagnostics-note">'
      . esc_html($T(
        'This ticket-based Remote Support Diagnostics session is separate from the Doctor Assisted Support opt-in. It can only be enabled by manually applying a valid signed token generated after customer consent in a CAS Support Desk ticket.',
        'Questa sessione di Diagnostica Remota collegata al ticket è separata dall’opt-in Supporto Assistito Doctor. Può essere attivata solo applicando manualmente un token firmato valido, generato dopo il consenso cliente in un ticket CAS Support Desk.'
      ))
      . '</p>';
    echo '</div>';
    echo wp_kses( '<div>' . custausu_admin_support_diagnostics_status_badge($status, $T) . '</div>', custausu_admin_allowed_output_html() );
    echo '</div>';

    if (!$has_public_key) {
      echo '<div class="custausu-support-diagnostics-warning">';
      echo esc_html($T(
        'Support diagnostics public key is not configured in this build.',
        'La chiave pubblica per la diagnostica supporto non è configurata in questa build.'
      ));
      echo '</div>';
    }

    if ($is_requested_by_url && !$is_active_support) {
      echo '<div class="custausu-support-diagnostics-warning">';
      echo '<strong>' . esc_html($T(
        'Diagnostics are preview until a valid ticket-based support token is applied.',
        'La diagnostica resta bloccata finché non viene applicato un token supporto valido collegato a un ticket.'
      )) . '</strong>';
      echo '<p class="description">'
        . esc_html($T(
          'The support link only opens this token form. It does not authorize access, does not enable logs, and does not expose diagnostics without a signed token.',
          'Il link supporto apre solo questo form token. Non autorizza l’accesso, non abilita i log e non espone diagnostiche senza un token firmato.'
        ))
        . '</p>';
      echo '</div>';
    }

    if ($status === 'active' && $can_view_diagnostics) {
      echo '<div class="custausu-support-diagnostics-active-panel">';
      echo '<p><strong>' . esc_html($T('Remote support is active.', 'Supporto remoto attivo.')) . '</strong></p>';

      if (!empty($state['label'])) {
        echo '<p class="description"><strong>Label:</strong> ' . esc_html((string)$state['label']) . '</p>';
      }

      if (!empty($state['case_id'])) {
        echo '<p class="description"><strong>Case ID:</strong> <code>' . esc_html((string)$state['case_id']) . '</code></p>';
      }

      if (!empty($state['expires_at'])) {
        echo '<p class="description"><strong>' . esc_html($T('Expires at', 'Scade il')) . ':</strong> '
          . esc_html((string)$state['expires_at'])
          . ' UTC</p>';
      }

      if (!empty($state['scope'])) {
        echo '<p class="description"><strong>Scope:</strong> <code>' . esc_html((string)$state['scope']) . '</code></p>';
      }

      if (!empty($capabilities)) {
        echo '<p class="description"><strong>' . esc_html($T('Allowed diagnostics', 'Diagnostiche consentite')) . ':</strong></p>';
        echo '<div class="custausu-support-diagnostics-capabilities">';

        foreach ($capabilities as $capability) {
          echo '<span class="custausu-support-diagnostics-capability">'
            . esc_html(custausu_admin_support_diagnostics_capability_label($capability, $T))
            . '</span>';
        }

        echo '</div>';
      }

      if (function_exists('custausu_support_diagnostics_can') && custausu_support_diagnostics_can('diagnostic_export')) {
        $report_url = wp_nonce_url(
          admin_url('admin-post.php?action=custausu_support_diagnostics_export_report'),
          'custausu_support_diagnostics_export_report'
        );

        echo '<p class="custausu-support-diagnostics-export-actions">';
        echo '<a class="button button-primary" href="' . esc_url($report_url) . '">'
          . esc_html($T('Download readable diagnostic report', 'Scarica report diagnostico leggibile'))
          . '</a>';
        echo '</p>';

        echo '<p class="description">'
          . esc_html($T(
            'Exports sanitized diagnostics, runtime logs and selected support snapshots as a readable HTML report.',
            'Esporta diagnostica sanitizzata, log runtime e snapshot supporto selezionati in un report HTML leggibile.'
          ))
          . '</p>';
      }

      echo '</div>';

      if (function_exists('custausu_debug_support_diagnostics_render_log_viewer')) {
        echo wp_kses( custausu_debug_support_diagnostics_render_log_viewer($T), custausu_admin_allowed_output_html() );
      }
    } elseif ($status === 'active' && !$can_view_diagnostics) {
      echo '<div class="custausu-support-diagnostics-warning">';
      echo '<strong>' . esc_html($T(
        'Remote support diagnostics are active for a support session.',
        'La diagnostica supporto remoto è attiva per una sessione di supporto.'
      )) . '</strong>';
      echo '<p class="description">'
        . esc_html($T(
          'Details, runtime logs and token removal are hidden from this admin session.',
          'Dettagli, log runtime e rimozione token sono nascosti da questa sessione admin.'
        ))
        . '</p>';
      echo '</div>';
    } elseif ($reason !== '') {
      echo '<p class="description custausu-support-diagnostics-reason">'
        . esc_html(custausu_admin_support_diagnostics_reason_label($reason, $T))
        . '</p>';
    }

    if (!$is_requested_by_url || $is_active_support || in_array($status, ['active', 'expired'], true)) {
    echo '<div class="custausu-support-diagnostics-identifiers">';
    echo '<p class="description"><strong>'
      . esc_html($T('Ticket-based diagnostics only', 'Diagnostica solo tramite ticket'))
      . '</strong></p>';

    echo '<p class="description">'
      . esc_html($T(
        'Support identifiers are not displayed in this panel. CAS Support Desk generates scoped signed tokens from the ticket data after customer consent.',
        'Gli identificatori di supporto non vengono mostrati in questo pannello. CAS Support Desk genera token firmati e limitati usando i dati del ticket dopo il consenso del cliente.'
      ))
      . '</p>';
    echo '</div>';
    }

  if ($status !== 'active' || $can_view_diagnostics) {
    echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" class="custausu-support-diagnostics-form">';
    echo '<input type="hidden" name="action" value="custausu_support_diagnostics_action">';
    echo '<input type="hidden" name="custausu_support_diagnostics_context" value="panel">';

    wp_nonce_field('custausu_support_diagnostics_action');

    if ($status !== 'active') {
      echo '<div class="custausu-support-diagnostics-token-entry">';

      echo '<label for="custausu_support_diagnostics_token"><strong>'
        . esc_html($T('Ticket-based support token', 'Token supporto collegato a ticket'))
        . '</strong></label>';

      echo '<textarea id="custausu_support_diagnostics_token" name="custausu_support_diagnostics_token" rows="4" class="large-text code" required placeholder="'
        . esc_attr($T(
          'Paste the full signed token copied from CAS Support Desk. The Diagnostics URL only opens this panel; it does not contain the token for security reasons.',
          'Incolla il token firmato completo copiato da CAS Support Desk. La Diagnostics URL apre solo questo pannello; per sicurezza non contiene il token.'
        ))
        . '"></textarea>';

      echo '<div class="custausu-support-diagnostics-actions">';

      echo '<button type="submit" name="do" value="apply" class="button button-primary">'
        . esc_html($T('Activate ticket diagnostics', 'Attiva diagnostica ticket'))
        . '</button>';

      echo '</div>';
      echo '</div>';
    } elseif ($can_clear_diagnostics) {
      echo '<div class="custausu-support-diagnostics-active-actions">';

      if ($clear_confirmation_requested) {
        $confirm_token = (string)$clear_confirmation['token'];

        echo '<div class="custausu-support-diagnostics-confirmation" role="alert">';
        echo '<p><strong>'
          . esc_html($T(
            'Confirm termination and local revocation',
            'Conferma termine e revoca locale'
          ))
          . '</strong></p>';

        echo '<p class="description">'
          . esc_html($T(
            'This immediately ends the local diagnostic session, removes its runtime logs and prevents this token from being used again on this site.',
            'Questa operazione termina immediatamente la sessione diagnostica locale, rimuove i relativi log runtime e impedisce che questo token venga riutilizzato su questo sito.'
          ))
          . '</p>';

        echo '<input type="hidden" name="custausu_support_diagnostics_confirmation" value="'
          . esc_attr($confirm_token)
          . '">';

        wp_nonce_field(
          'custausu_support_diagnostics_clear_confirm_' . $confirm_token,
          'custausu_support_diagnostics_clear_nonce'
        );

        echo '<div class="custausu-support-diagnostics-confirmation-actions">';

        echo '<button type="submit" name="do" value="clear_cancel" class="button" formnovalidate>'
          . esc_html($T('Cancel', 'Annulla'))
          . '</button>';

        echo '<button type="submit" name="do" value="clear_confirm" class="button custausu-support-diagnostics-final-revoke" formnovalidate>'
          . esc_html($T(
            'Confirm end and revoke',
            'Conferma termine e revoca'
          ))
          . '</button>';

        echo '</div>';
        echo '</div>';
      } else {
        echo '<button type="submit" name="do" value="clear_prepare" class="button" formnovalidate>'
          . esc_html($T(
            'End and revoke on this site',
            'Termina e revoca su questo sito'
          ))
          . '</button>';
      }

      echo '</div>';
    } elseif ($status === 'active') {
      echo '<p class="description custausu-support-diagnostics-token-management-note">'
        . esc_html($T(
          'Token management is reserved to the support session that applied the token.',
          'La gestione del token è riservata alla sessione supporto che lo ha applicato.'
        ))
        . '</p>';
    }

    echo '</form>';
  }

    echo '</div>'; // .custausu-support-diagnostics-box

    echo '</td></tr>';

    return (string) ob_get_clean();
  }
}


/**
 * CAS Free local Upgrade cards.
 *
 * These cards are bundled informational content. They do not use CAS RM
 * delivery, dismissals or interaction analytics.
 */

if (!function_exists('custausu_admin_support_diagnostics_panel_url')) {
  function custausu_admin_support_diagnostics_panel_url(): string {
    return admin_url('admin.php?page=custausu-settings&custausu_support_diagnostics=1#custausu-section-license');
  }
}

if (!function_exists('custausu_admin_support_diagnostics_handle_action')) {
  function custausu_admin_support_diagnostics_handle_action(): void {
    if (!is_admin()) {
      return;
    }

    if (!current_user_can('manage_options')) {
      wp_die('Forbidden');
    }

    $do = sanitize_key(
      (string)($_POST['do'] ?? '')
    );

    $allowed = [
      'apply',
      'clear_prepare',
      'clear_confirm',
      'clear_cancel',
    ];

    if (!in_array($do, $allowed, true)) {
      check_admin_referer(
        'custausu_support_diagnostics_action'
      );

      custausu_admin_support_diagnostics_set_notice(
        'error',
        custausu_admin_support_diagnostics_t(
          'Invalid support diagnostics action.',
          'Azione diagnostica supporto non valida.'
        )
      );

      wp_safe_redirect(
        custausu_admin_support_diagnostics_panel_url()
      );
      exit;
    }

    $context = sanitize_key(
      (string)(
        $_POST['custausu_support_diagnostics_context']
        ?? 'panel'
      )
    );

    if (!in_array($context, ['panel', 'notice'], true)) {
      $context = 'panel';
    }

    if ($do === 'clear_prepare') {
      check_admin_referer(
        'custausu_support_diagnostics_action'
      );

      $state = function_exists(
        'custausu_support_diagnostics_get_stored_state'
      )
        ? custausu_support_diagnostics_get_stored_state()
        : [];

      $state = is_array($state) ? $state : [];

      if (
        !function_exists(
          'custausu_support_diagnostics_current_admin_can_clear_token'
        )
        || !custausu_support_diagnostics_current_admin_can_clear_token(
          $state
        )
      ) {
        custausu_admin_support_diagnostics_set_notice(
          'error',
          custausu_admin_support_diagnostics_t(
            'This administrator cannot end the active support diagnostics session.',
            'Questo amministratore non può terminare la sessione diagnostica di supporto attiva.'
          )
        );

        wp_safe_redirect(
          custausu_admin_support_diagnostics_clear_cancel_url(
            $context
          )
        );
        exit;
      }

      $confirmation =
        custausu_admin_support_diagnostics_create_clear_confirmation(
          $context
        );

      if (empty($confirmation['token'])) {
        custausu_admin_support_diagnostics_set_notice(
          'error',
          custausu_admin_support_diagnostics_t(
            'The revocation confirmation could not be created. Please try again.',
            'Impossibile creare la conferma di revoca. Riprova.'
          )
        );

        wp_safe_redirect(
          custausu_admin_support_diagnostics_clear_cancel_url(
            $context
          )
        );
        exit;
      }

      wp_safe_redirect(
        custausu_admin_support_diagnostics_clear_confirmation_url(
          $context,
          (string)$confirmation['token']
        )
      );
      exit;
    }

    if (
      $do === 'clear_confirm'
      || $do === 'clear_cancel'
    ) {
      $confirmation =
        custausu_admin_support_diagnostics_get_clear_confirmation(
          $context
        );

      if (empty($confirmation['token'])) {
        custausu_admin_support_diagnostics_set_notice(
          'error',
          custausu_admin_support_diagnostics_t(
            'The revocation confirmation is missing or has expired.',
            'La conferma di revoca è mancante o scaduta.'
          )
        );

        wp_safe_redirect(
          custausu_admin_support_diagnostics_clear_cancel_url(
            $context
          )
        );
        exit;
      }

      $confirm_token = (string)$confirmation['token'];

      check_admin_referer(
        'custausu_support_diagnostics_clear_confirm_'
          . $confirm_token,
        'custausu_support_diagnostics_clear_nonce'
      );

      if ($do === 'clear_cancel') {
        custausu_admin_support_diagnostics_delete_clear_confirmation();

        wp_safe_redirect(
          custausu_admin_support_diagnostics_clear_cancel_url(
            $context
          )
        );
        exit;
      }

      $state = function_exists(
        'custausu_support_diagnostics_get_stored_state'
      )
        ? custausu_support_diagnostics_get_stored_state()
        : [];

      $state = is_array($state) ? $state : [];

      if (
        !function_exists(
          'custausu_support_diagnostics_current_admin_can_clear_token'
        )
        || !custausu_support_diagnostics_current_admin_can_clear_token(
          $state
        )
      ) {
        custausu_admin_support_diagnostics_delete_clear_confirmation();

        custausu_admin_support_diagnostics_set_notice(
          'error',
          custausu_admin_support_diagnostics_t(
            'This administrator cannot end the active support diagnostics session.',
            'Questo amministratore non può terminare la sessione diagnostica di supporto attiva.'
          )
        );

        wp_safe_redirect(
          custausu_admin_support_diagnostics_clean_url()
        );
        exit;
      }

      custausu_admin_support_diagnostics_delete_clear_confirmation();

      if (
        function_exists(
          'custausu_support_diagnostics_clear_token'
        )
      ) {
        $cleared =
          custausu_support_diagnostics_clear_token();

        $delivery = function_exists(
          'custausu_support_diagnostics_client_revoke_last_result'
        )
          ? custausu_support_diagnostics_client_revoke_last_result()
          : [];

        if (!$cleared) {
          custausu_admin_support_diagnostics_set_notice(
            'error',
            custausu_admin_support_diagnostics_t(
              'Remote support diagnostics could not be ended safely. The local revocation tombstone was not persisted.',
              'Impossibile terminare in sicurezza la diagnostica supporto remoto. Il blocco di revoca locale non è stato salvato.'
            )
          );
        } else {
          if (
            function_exists(
              'custausu_debug_support_diagnostics_clear_runtime_logs'
            )
          ) {
            custausu_debug_support_diagnostics_clear_runtime_logs();
          } else {
            delete_option(
              'custausu_support_diagnostics_runtime_logs'
            );

            delete_option(
              'cas_support_diagnostics_runtime_log'
            );
          }

          $remote_status = sanitize_key(
            (string) (
              $delivery['remote_status']
              ?? 'not_prepared'
            )
          );

          if ($remote_status === 'delivered') {
            custausu_admin_support_diagnostics_set_notice(
              'success',
              custausu_admin_support_diagnostics_t(
                'Remote support diagnostics ended, locally revoked and confirmed by CAS Support Desk.',
                'Diagnostica supporto remoto terminata, revocata localmente e confermata da CAS Support Desk.'
              )
            );
          } elseif ($remote_status === 'queued') {
            custausu_admin_support_diagnostics_set_notice(
              'warning',
              custausu_admin_support_diagnostics_t(
                'Remote support diagnostics ended and locally revoked. The remote revocation notice is queued for automatic retry.',
                'Diagnostica supporto remoto terminata e revocata localmente. La notifica di revoca remota è in coda per il nuovo tentativo automatico.'
              )
            );
          } elseif (
            in_array(
              $remote_status,
              [
                'terminal',
                'exhausted',
                'transient_unqueued',
              ],
              true
            )
          ) {
            custausu_admin_support_diagnostics_set_notice(
              'warning',
              custausu_admin_support_diagnostics_t(
                'Remote support diagnostics ended and remains locally revoked. The remote revocation notice could not be completed.',
                'Diagnostica supporto remoto terminata e revocata localmente. Non è stato possibile completare la notifica di revoca remota.'
              )
            );
          } else {
            custausu_admin_support_diagnostics_set_notice(
              'success',
              custausu_admin_support_diagnostics_t(
                'Remote support diagnostics ended and locally revoked.',
                'Diagnostica supporto remoto terminata e revocata localmente.'
              )
            );
          }
        }
      } else {
        custausu_admin_support_diagnostics_set_notice(
          'error',
          custausu_admin_support_diagnostics_t(
            'Remote support diagnostics is not available in this build.',
            'La diagnostica supporto remoto non è disponibile in questa build.'
          )
        );
      }


      /*
       * Deliberately remove the diagnostics query argument and fragment
       * after actual local revocation.
       */
      wp_safe_redirect(
        custausu_admin_support_diagnostics_clean_url()
      );
      exit;
    }

    check_admin_referer(
      'custausu_support_diagnostics_action'
    );

    $token = isset(
      $_POST['custausu_support_diagnostics_token']
    )
      ? trim(
          sanitize_textarea_field(
            wp_unslash(
              $_POST['custausu_support_diagnostics_token']
            )
          )
        )
      : '';

    if ($token === '') {
      custausu_admin_support_diagnostics_set_notice(
        'error',
        custausu_admin_support_diagnostics_t(
          'Support token is empty.',
          'Il token supporto è vuoto.'
        )
      );

      wp_safe_redirect(
        custausu_admin_support_diagnostics_panel_url()
      );
      exit;
    }

    if (
      !function_exists(
        'custausu_support_diagnostics_apply_token'
      )
    ) {
      custausu_admin_support_diagnostics_set_notice(
        'error',
        custausu_admin_support_diagnostics_t(
          'Remote support diagnostics is not available in this build.',
          'La diagnostica supporto remoto non è disponibile in questa build.'
        )
      );

      wp_safe_redirect(
        custausu_admin_support_diagnostics_panel_url()
      );
      exit;
    }

    $result = custausu_support_diagnostics_apply_token(
      $token
    );

    if (!empty($result['ok'])) {
      if (
        function_exists(
          'custausu_debug_support_diagnostics_clear_runtime_logs'
        )
      ) {
        custausu_debug_support_diagnostics_clear_runtime_logs();
      } else {
        delete_option(
          'custausu_support_diagnostics_runtime_logs'
        );

        delete_option(
          'cas_support_diagnostics_runtime_log'
        );
      }

      if (
        function_exists(
          'custausu_debug_support_diagnostics_seed_runtime_logs'
        )
      ) {
        custausu_debug_support_diagnostics_seed_runtime_logs();
      }

      custausu_admin_support_diagnostics_set_notice(
        'success',
        custausu_admin_support_diagnostics_t(
          'Remote support diagnostics enabled temporarily.',
          'Diagnostica supporto remoto abilitata temporaneamente.'
        )
      );
    } else {
      $validation = is_array(
        $result['validation'] ?? null
      )
        ? $result['validation']
        : [];

      $reason = sanitize_key(
        (string)(
          $validation['reason']
          ?? 'invalid_token'
        )
      );

      custausu_admin_support_diagnostics_set_notice(
        'error',
        sprintf(
          '%s %s',
          custausu_admin_support_diagnostics_t(
            'Support token is invalid.',
            'Il token supporto non è valido.'
          ),
          $reason !== ''
            ? '(' . $reason . ')'
            : ''
        )
      );
    }

    wp_safe_redirect(
      custausu_admin_support_diagnostics_panel_url()
    );
    exit;
  }
}

if (!function_exists('custausu_admin_support_diagnostics_redact_export_value')) {
  function custausu_admin_support_diagnostics_redact_export_value($value, string $key = '') {
    $key_l = strtolower($key);

    $sensitive_key = (
      strpos($key_l, 'password') !== false
      || strpos($key_l, 'secret') !== false
      || strpos($key_l, 'token') !== false
      || strpos($key_l, 'license_key') !== false
      || strpos($key_l, 'private_key') !== false
      || strpos($key_l, 'api_key') !== false
      || strpos($key_l, 'authorization') !== false
    );

    if ($sensitive_key) {
      return '[redacted]';
    }

    if (is_array($value)) {
      $out = [];

      foreach ($value as $k => $v) {
        $out[$k] = custausu_admin_support_diagnostics_redact_export_value($v, is_scalar($k) ? (string) $k : '');
      }

      return $out;
    }

    if (is_object($value)) {
      return custausu_admin_support_diagnostics_redact_export_value((array) $value, $key);
    }

    if (is_string($value)) {
      if (strpos($value, '-----BEGIN PRIVATE KEY-----') !== false) {
        return '[redacted-private-key]';
      }

      if (preg_match('/CAS-[A-Z0-9-]{12,}/i', $value)) {
        return preg_replace('/CAS-[A-Z0-9-]{12,}/i', 'CAS-[redacted]', $value);
      }

      if (strlen($value) > 12000) {
        return substr($value, 0, 12000) . "\n...[truncated]";
      }
    }

    return $value;
  }
}

if (!function_exists('custausu_admin_support_diagnostics_collect_export')) {
  function custausu_admin_support_diagnostics_collect_export(): array {
    $state = function_exists('custausu_support_diagnostics_get_state')
      ? custausu_support_diagnostics_get_state()
      : [];

    $state = is_array($state) ? $state : [];

    $safe_state = $state;
    if (isset($safe_state['token'])) {
      $safe_state['token'] = '[redacted]';
    }

    $runtime_logs = get_option('custausu_support_diagnostics_runtime_logs', []);

    if (!is_array($runtime_logs)) {
      $legacy = get_option('cas_support_diagnostics_runtime_log', []);
      $runtime_logs = is_array($legacy) ? $legacy : [];
    }

    $package_context = function_exists('custausu_free_package_support_context')
      ? custausu_free_package_support_context()
      : [];

    $package_context = is_array($package_context)
      ? $package_context
      : [];

    $export = [
      'schema' => [
        'name'    => 'custausu_support_diagnostics_export',
        'version' => 1,
      ],
      'generated_at_utc' => gmdate('Y-m-d H:i:s'),
      'site' => [
        'home_url'   => home_url('/'),
        'site_url'   => site_url('/'),
        'wp_version' => get_bloginfo('version'),
        'php_version'=> PHP_VERSION,
        'environment_type' => function_exists('wp_get_environment_type') ? wp_get_environment_type() : '',
        'timezone' => function_exists('wp_timezone_string') ? wp_timezone_string() : '',
        'cas_version' => defined('CUSTAUSU_VERSION') ? CUSTAUSU_VERSION : '',
        'custausu_plugin_file' => defined('CUSTAUSU_PLUGIN_FILE') ? basename((string) CUSTAUSU_PLUGIN_FILE) : '',
      ],
      'support_diagnostics_state' => $safe_state,
      'package_context' => $package_context,
      'runtime_logs' => $runtime_logs,
    ];

    if (function_exists('custausu_support_diagnostics_can') && custausu_support_diagnostics_can('settings_snapshot')) {
      if (function_exists('custausu_get_settings')) {
        $export['settings_snapshot'] = custausu_get_settings();
      } elseif (function_exists('custausu_settings_get_all')) {
        $export['settings_snapshot'] = custausu_settings_get_all();
      } else {
        $export['settings_snapshot'] = [];
      }
    }

    if (
      function_exists('custausu_support_diagnostics_can')
      && custausu_support_diagnostics_can('plugin_inventory')
      && function_exists('custausu_support_report_plugin_inventory')
    ) {
      $export['plugin_inventory'] =
        custausu_support_report_plugin_inventory();
    }

    return custausu_admin_support_diagnostics_redact_export_value($export);
  }
}

if (!function_exists('custausu_admin_support_diagnostics_handle_export')) {
  function custausu_admin_support_diagnostics_handle_export(): void {
    if (!is_admin() || !current_user_can('manage_options')) {
      wp_die('Forbidden');
    }

    check_admin_referer('custausu_support_diagnostics_export');

    $state = function_exists('custausu_support_diagnostics_get_state')
      ? custausu_support_diagnostics_get_state()
      : [];

    if (
      !function_exists('custausu_support_diagnostics_is_active')
      || !custausu_support_diagnostics_is_active()
      || !function_exists('custausu_support_diagnostics_can')
      || !custausu_support_diagnostics_can('diagnostic_export')
      || !function_exists('custausu_support_diagnostics_current_admin_can_viewer')
      || !custausu_support_diagnostics_current_admin_can_viewer($state)
    ) {
      wp_die('Diagnostic export is not enabled for this admin session.');
    }

    $export = custausu_admin_support_diagnostics_collect_export();

    $filename = 'custausu-diagnostic-export-' . gmdate('Ymd-His') . '.json';

    nocache_headers();

    header('Content-Type: application/json; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');

    echo wp_json_encode(
      $export,
      JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
    );

    exit;
  }
}

if (!function_exists('custausu_free_upgrade_cards_option_name')) {
  function custausu_free_upgrade_cards_option_name(): string {
    return 'custausu_free_upgrade_card_dismissals';
  }
}

if (!function_exists('custausu_free_upgrade_cards_dismiss_days')) {
  function custausu_free_upgrade_cards_dismiss_days(): int {
    return 20;
  }
}

if (!function_exists('custausu_free_upgrade_cards_get_dismissals')) {
  function custausu_free_upgrade_cards_get_dismissals(): array {
    $raw = get_option(custausu_free_upgrade_cards_option_name(), []);
    $raw = is_array($raw) ? $raw : [];

    $now = time();
    $clean = [];

    foreach (['advanced', 'premium'] as $card_id) {
      $until = isset($raw[$card_id]) ? absint($raw[$card_id]) : 0;

      if ($until > $now) {
        $clean[$card_id] = $until;
      }
    }

    if ($clean !== $raw) {
      update_option(custausu_free_upgrade_cards_option_name(), $clean, false);
    }

    return $clean;
  }
}

if (!function_exists('custausu_free_upgrade_card_is_dismissed')) {
  function custausu_free_upgrade_card_is_dismissed(string $card_id): bool {
    $dismissals = custausu_free_upgrade_cards_get_dismissals();
    return !empty($dismissals[sanitize_key($card_id)]);
  }
}

if (!function_exists('custausu_free_upgrade_cards_is_italian')) {
  function custausu_free_upgrade_cards_is_italian(): bool {
    $locale = function_exists('get_user_locale')
      ? (string) get_user_locale()
      : (string) get_locale();

    return strpos(strtolower($locale), 'it') === 0;
  }
}

if (!function_exists('custausu_free_upgrade_cards_data')) {
  function custausu_free_upgrade_cards_data(): array {
    $is_it = custausu_free_upgrade_cards_is_italian();

    return [
      'advanced' => [
        'kicker' => $is_it
          ? 'PIÙ PROTEZIONE, PIÙ INTEGRAZIONI, PIÙ CONTROLLO.'
          : 'MORE PROTECTION, MORE INTEGRATIONS, MORE CONTROL.',
        'title' => $is_it
          ? 'Disponibile con Custom Auth Suite™ Advanced.'
          : 'Available with Custom Auth Suite™ Advanced.',
        'body' => $is_it
          ? 'Advanced aggiunge reCAPTCHA Enterprise, CF7 Math Check, Polylang/i18n, strumenti di import/export e personalizzazioni più evolute.'
          : 'Advanced adds reCAPTCHA Enterprise, CF7 Math Check, Polylang/i18n, import/export tools and more advanced customization.',
        'secondary' => $is_it
          ? 'Ideale quando il login personalizzato diventa parte stabile del sito.'
          : 'Designed for sites where the custom login becomes a stable part of the project.',
        'cta_label' => $is_it ? 'Scopri Advanced' : 'Learn about Advanced',
        'cta_url' => $is_it
          ? 'https://customauthsuite.com/it/licenza-advanced-custom-auth-suite/'
          : 'https://customauthsuite.com/custom-auth-suite-advanced/',
      ],
      'premium' => [
        'kicker' => $is_it
          ? 'PASSKEYS, WEBAUTHN E DIAGNOSTICA AVANZATA.'
          : 'PASSKEYS, WEBAUTHN AND ADVANCED DIAGNOSTICS.',
        'title' => $is_it
          ? 'Disponibile con Custom Auth Suite™ Premium.'
          : 'Available with Custom Auth Suite™ Premium.',
        'body' => $is_it
          ? 'Premium include tutto Advanced e aggiunge Passkeys/WebAuthn, device intelligence e strumenti avanzati per sicurezza e supporto.'
          : 'Premium includes everything in Advanced and adds Passkeys/WebAuthn, device intelligence and advanced security and support tools.',
        'secondary' => $is_it
          ? 'Pensato per siti dove autenticazione, sicurezza e continuità operativa sono centrali.'
          : 'Designed for sites where authentication, security and operational continuity are central.',
        'cta_label' => $is_it ? 'Scopri Premium' : 'Learn about Premium',
        'cta_url' => $is_it
          ? 'https://customauthsuite.com/it/licenza-premium-custom-auth-suite/'
          : 'https://customauthsuite.com/custom-auth-suite-premium/',
      ],
    ];
  }
}

if (!function_exists('custausu_free_upgrade_card_render_picture')) {
  function custausu_free_upgrade_card_render_picture(string $card_id): void {
    if (!defined('CUSTAUSU_PLUGIN_URL')) {
      return;
    }

    $card_id = sanitize_key($card_id);

    if (!in_array($card_id, ['advanced', 'premium'], true)) {
      return;
    }

    $base = CUSTAUSU_PLUGIN_URL . 'inc/assets/images/custausu-free-upgrade-cards/custausu-upgrade-card-' . $card_id . '-';

    echo '<picture class="custausu-free-upgrade-card__picture">';
    echo '<source media="(max-width: 782px)" type="image/webp" srcset="' . esc_url($base . 'mobile.webp') . '">';
    echo '<source media="(max-width: 782px)" srcset="' . esc_url($base . 'mobile.png') . '">';
    echo '<source type="image/webp" srcset="' . esc_url($base . 'desktop.webp') . '">';
    echo '<img class="custausu-free-upgrade-card__img" src="' . esc_url($base . 'desktop.png') . '" alt="" loading="lazy">';
    echo '</picture>';
  }
}

if (!function_exists('custausu_free_upgrade_cards_render')) {
  function custausu_free_upgrade_cards_render(): string {
    if (!function_exists('custausu_is_public_build') || !custausu_is_public_build()) {
      return '';
    }

    $cards = custausu_free_upgrade_cards_data();
    $dismiss_label = custausu_free_upgrade_cards_is_italian()
      ? 'Nascondi per 20 giorni'
      : 'Hide for 20 days';

    $rendered_cards = 0;

    ob_start();

    echo '<div class="custausu-free-upgrade-cards custausu-free-upgrade-cards--local">';

    foreach ($cards as $card_id => $card) {
      if (custausu_free_upgrade_card_is_dismissed($card_id)) {
        continue;
      }

      $rendered_cards++;

      echo '<article class="custausu-free-upgrade-card custausu-free-upgrade-card--' . esc_attr($card_id) . '">';

      echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" class="custausu-free-upgrade-card__dismiss">';
      echo wp_nonce_field('custausu_free_upgrade_card_dismiss', '_wpnonce', true, false); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
      echo '<input type="hidden" name="action" value="custausu_free_upgrade_card_dismiss">';
      echo '<input type="hidden" name="card_id" value="' . esc_attr($card_id) . '">';
      echo '<input type="hidden" name="redirect_to" value="' . esc_url(custausu_rm_client_current_admin_url()) . '">';
      echo '<button type="submit" class="button-link custausu-free-upgrade-card__dismiss-btn" aria-label="' . esc_attr($dismiss_label) . '" title="' . esc_attr($dismiss_label) . '">×</button>';
      echo '</form>';

      echo '<div class="custausu-free-upgrade-card__kicker">' . esc_html((string) $card['kicker']) . '</div>';
      echo '<h3 class="custausu-free-upgrade-card__title">' . esc_html((string) $card['title']) . '</h3>';
      echo '<p class="custausu-free-upgrade-card__body">' . esc_html((string) $card['body']) . '</p>';
      echo '<p class="custausu-free-upgrade-card__secondary">' . esc_html((string) $card['secondary']) . '</p>';
      echo '<a class="button button-primary custausu-free-upgrade-card__cta" href="' . esc_url((string) $card['cta_url']) . '" target="_blank" rel="noopener noreferrer">' . esc_html((string) $card['cta_label']) . '</a>';
      echo '<div class="custausu-free-upgrade-card__media" aria-hidden="true">';
      custausu_free_upgrade_card_render_picture($card_id);
      echo '</div>';

      echo '</article>';
    }

    echo '</div>';

    $html = trim((string) ob_get_clean());

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

    return $html;
  }
}

if (!function_exists('custausu_free_upgrade_card_handle_dismiss')) {
  function custausu_free_upgrade_card_handle_dismiss(): void {
    if (!current_user_can('manage_options')) {
      wp_die(esc_html__('You are not allowed to perform this action.', 'custom-auth-suite'));
    }

    check_admin_referer('custausu_free_upgrade_card_dismiss');

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

    if (!in_array($card_id, ['advanced', 'premium'], true)) {
      wp_die(esc_html__('Invalid Upgrade CAS card.', 'custom-auth-suite'));
    }

    $dismissals = custausu_free_upgrade_cards_get_dismissals();
    $dismissals[$card_id] = time() + (custausu_free_upgrade_cards_dismiss_days() * DAY_IN_SECONDS);
    update_option(custausu_free_upgrade_cards_option_name(), $dismissals, false);

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

    if ($redirect === '') {
      $redirect = wp_get_referer();
    }

    if (!$redirect) {
      $redirect = admin_url();
    }

    wp_safe_redirect($redirect);
    exit;
  }
}

add_action('admin_post_custausu_free_upgrade_card_dismiss', 'custausu_free_upgrade_card_handle_dismiss');

if (!function_exists('custausu_admin_render_free_services_section')) {
  function custausu_admin_render_free_services_section(callable $T): string {
    $settings_locale = function_exists('get_user_locale')
      ? strtolower((string)get_user_locale())
      : strtolower((string)get_locale());

    $upgrade_url = strpos($settings_locale, 'it') === 0
      ? 'https://customauthsuite.com/it/il-plugin/'
      : 'https://customauthsuite.com/plugin/';

    $upgrade_cards_html = custausu_free_upgrade_cards_render();

    ob_start();

    echo '<div class="custausu-license-layout">';
    echo '<div class="custausu-license-layout__main">';
    echo '<table id="custausu-section-license" class="widefat striped custausu-section-license--upgrade">';
    echo '<colgroup>';
    echo '<col class="custausu-license-table__label-column">';
    echo '<col class="custausu-license-table__value-column">';
    echo '</colgroup>';
    echo '<thead class="custausu-head"><tr><th colspan="2" class="custausu-license-section-heading-cell">';
    echo '<h2 class="custausu-license-section-title"><span class="dashicons dashicons-info-outline"></span> | '
      . esc_html($T('Upgrade CAS', 'Aggiorna CAS'))
      . '</h2>';
    echo '</th></tr></thead>';
    echo '<tbody>';
    echo '<tr><td colspan="2" class="custausu-upgrade-box-cell">';
    echo '<div class="custausu-upgrade-box">';
    echo '<div class="custausu-upgrade-box__content">';
    echo '<div class="custausu-upgrade-box__badges">';
    echo '<span class="custausu-badge custausu-badge--free">Free</span>';
    echo '<span class="custausu-badge custausu-badge--advanced">Advanced</span>';
    echo '<span class="custausu-badge custausu-badge--premium">Premium</span>';
    echo '</div>';
    echo '<h3 class="custausu-upgrade-box__title">'
      . esc_html($T(
        'Explore the Advanced and Premium editions',
        'Scopri le edizioni Advanced e Premium'
      ))
      . '</h3>';
    echo '<p class="custausu-upgrade-box__text">'
      . esc_html($T(
        'This WordPress.org build includes the complete Free feature set. Advanced and Premium are separate packages distributed outside WordPress.org.',
        'Questa build WordPress.org include il set completo di funzioni Free. Advanced e Premium sono pacchetti separati distribuiti fuori da WordPress.org.'
      ))
      . '</p>';
    echo '<p class="description custausu-upgrade-box__description">'
      . esc_html($T(
        'Commercial package installation and license management do not exist in this public Free package.',
        'L’installazione dei pacchetti commerciali e la gestione delle licenze non sono presenti in questo pacchetto pubblico Free.'
      ))
      . '</p>';
    echo '</div>';
    echo '<div class="custausu-upgrade-box__actions">';
    echo '<a class="button button-primary custausu-upgrade-box__button" href="'
      . esc_url($upgrade_url)
      . '" target="_blank" rel="noopener noreferrer">'
      . esc_html($T(
        'Compare Advanced / Premium',
        'Confronta Advanced / Premium'
      ))
      . '</a>';
    echo '<span class="description custausu-upgrade-box__note">'
      . esc_html($T(
        'No license action is available or required in CAS Free.',
        'In CAS Free non è disponibile né richiesta alcuna azione di licenza.'
      ))
      . '</span>';
    echo '</div>';
    echo '</div>';
    echo '</td></tr>';

    if (function_exists('custausu_admin_render_support_diagnostics_rows')) {
      echo wp_kses( custausu_admin_render_support_diagnostics_rows( $T ), custausu_admin_allowed_output_html() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    }

    echo '</tbody></table>';
    echo '</div>';

    if ($upgrade_cards_html !== '') {
      echo '<aside class="custausu-license-layout__side">';
      echo '<div class="custausu-license-upgrade-cards-box">';
      echo wp_kses( $upgrade_cards_html, custausu_admin_allowed_output_html() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
      echo '</div>';
      echo '</aside>';
    }

    echo '</div>';

    return (string)ob_get_clean();
  }
}

add_action(
  'admin_post_custausu_support_diagnostics_action',
  'custausu_admin_support_diagnostics_handle_action'
);
add_action(
  'admin_post_custausu_support_diagnostics_export_report',
  'custausu_admin_support_diagnostics_export_report_handle'
);
add_action(
  'admin_notices',
  'custausu_admin_support_diagnostics_render_global_notice',
  19
);
add_action(
  'admin_notices',
  'custausu_admin_support_diagnostics_render_action_notice',
  20
);
