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

if (!function_exists('custausu_admin_render_polylang_section')) {
  function custausu_admin_render_polylang_section(
    bool $polylang_active,
    bool $polylang_enabled,
    callable $T,
    callable $sw
  ): string {
    unset($polylang_active, $polylang_enabled, $sw);

    ob_start();

    echo '<div class="custausu-gated-section custausu-gated-section--preview">';
    echo '<div class="custausu-gated-section__note custausu-gated-section__note--preview">';
    echo '<div class="custausu-gated-section__badges">';
    echo '<span class="custausu-badge custausu-badge--preview">' . esc_html($T('Plan feature', 'Funzione piano')) . '</span>';
    echo '<span class="custausu-badge custausu-badge--advanced">' . esc_html($T('Advanced', 'Advanced')) . '</span>';
    echo '</div>';
    echo '<div class="custausu-gated-section__message">' . esc_html($T(
      'Informational preview of the separately distributed Advanced and Premium packages. No Polylang integration is included in Free.',
      'Anteprima informativa dei pacchetti Advanced e Premium distribuiti separatamente. Free non include l’integrazione Polylang.'
    )) . '</div>';
    echo '</div>';
    echo '<div class="custausu-gated-section__content">';
    echo '<table id="custausu-section-polylang" class="widefat striped custausu-polylang-settings custausu-polylang-settings--preview">';
    echo '<thead class="custausu-head"><tr><th colspan="2" class="custausu-polylang__head-cell"><h2 class="custausu-polylang__title"><span class="dashicons dashicons-translation"></span> | Polylang</h2></th></tr></thead>';
    echo '<tbody><tr><th scope="row">' . esc_html($T('Integration', 'Integrazione')) . '</th><td>';
    echo '<label class="custausu-polylang__label custausu-polylang__label--disabled"><input type="checkbox" value="1" disabled aria-disabled="true"> ' . esc_html($T('Enable Polylang integration', 'Abilita integrazione Polylang')) . '</label>';
    echo '<p class="description">' . esc_html($T(
      'Polylang integration is available in Advanced and Premium. This Free section is a non-interactive product preview.',
      'L’integrazione Polylang è disponibile in Advanced e Premium. In Free questa sezione è un’anteprima informativa non interattiva.'
    )) . '</p>';
    echo '</td></tr></tbody></table>';
    echo '</div></div>';

    return (string)ob_get_clean();
  }
}

if (!function_exists('custausu_admin_render_cas_communications_section')) {
  function custausu_admin_render_cas_communications_section(
    callable $T,
    callable $sw
  ): string {
    $rm_preferences = get_option('custausu_remote_messages_client_preferences', []);
    $rm_preferences = is_array($rm_preferences) ? $rm_preferences : [];

    $rm_messages_enabled = array_key_exists('custausu_rm_messages_enabled', $rm_preferences)
      ? !empty($rm_preferences['custausu_rm_messages_enabled'])
      : false;

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

    $doctor_assisted_support_enabled = function_exists('custausu_admin_doctor_assisted_support_enabled')
      ? custausu_admin_doctor_assisted_support_enabled()
      : false;

    $doctor_support_status_label = $doctor_assisted_support_enabled
      ? $T('ENABLED', 'ATTIVO')
      : $T('OFF by default', 'OFF di default');

    $doctor_support_status_class = $doctor_assisted_support_enabled
      ? 'is-enabled'
      : 'is-disabled';

    $rm_status_label = $rm_messages_enabled
      ? $T('ENABLED', 'ATTIVO')
      : $T('OFF by default', 'OFF di default');
    $rm_status_class = $rm_messages_enabled ? 'is-enabled' : 'is-disabled';

    $public_free = function_exists('custausu_is_public_build') && custausu_is_public_build();

    $rm_scope_copy = $public_free
      ? $T(
        'Enable this only if you want CAS to request operational notices about security, compatibility, maintenance, documentation and support from Custom Auth Suite services. Commercial upgrade cards in Upgrade CAS are bundled locally and are not supplied by this service.',
        'Abilita questa opzione solo se vuoi che CAS richieda ai servizi Custom Auth Suite avvisi operativi su sicurezza, compatibilità, manutenzione, documentazione e supporto. Le card commerciali presenti in Aggiorna CAS sono incluse localmente e non vengono fornite da questo servizio.'
      )
      : $T(
        'Enable this only if you want CAS to request compatibility, support, documentation and product notices from Custom Auth Suite services.',
        'Abilita questa opzione solo se vuoi che CAS richieda note di compatibilità, supporto, documentazione e comunicazioni prodotto dai servizi Custom Auth Suite.'
      );

    $rm_analytics_copy = $public_free
      ? $T(
        'Optionally share aggregated interaction events for operational remote messages, such as impressions, dismissals and CTA clicks, to improve message relevance. The two local Advanced/Premium cards in Upgrade CAS never send impression, CTA-click or dismiss events to CAS RM. The collected remote-message data is anonymous, aggregated and global: it does not track the website where Custom Auth Suite™ is installed.',
        'Condividi facoltativamente eventi aggregati relativi ai messaggi remoti operativi, come impression, chiusure e clic sulle CTA, per migliorarne la pertinenza. Le due card locali Advanced/Premium in Aggiorna CAS non inviano mai a CAS RM eventi di impression, clic CTA o chiusura. I dati dei messaggi remoti sono anonimi, aggregati e globali: non tracciano il sito su cui Custom Auth Suite™ è installato.'
      )
      : $T(
        'Optionally share aggregated interaction events such as impressions, dismissals and CTA clicks to help improve message relevance. The collected data is anonymous, aggregated and global: it does not track the website where Custom Auth Suite™ is installed and is not required to receive Remote Admin Messages.',
        'Condividi facoltativamente eventi aggregati come impression, chiusure e clic sulle CTA per migliorare la pertinenza dei messaggi. I dati raccolti sono anonimi, aggregati e globali: non tracciano il sito su cui Custom Auth Suite™ è installato e non sono necessari per ricevere i Messaggi amministrativi remoti.'
      );

    ob_start();

    echo '<table id="custausu-section-custausu-communications" class="widefat striped custausu-section-custausu-communications">';
    echo '<thead class="custausu-head"><tr><th colspan="2" class="custausu-communications__head-cell"><h2 class="custausu-communications__title"><span class="dashicons dashicons-megaphone"></span> | ' . esc_html($T('CAS communications and privacy', 'Comunicazioni CAS e privacy')) . '</h2></th></tr></thead>';
    echo '<tbody>';

    echo '<tr><th scope="row">' . esc_html($T('Remote Admin Messages', 'Messaggi amministrativi remoti')) . '</th><td>';
    echo '<p>' . esc_html($T('Client channel:', 'Canale client:')) . ' <span class="custausu-rm-client-status-badge ' . esc_attr($rm_status_class) . '">' . esc_html($rm_status_label) . '</span></p>';
    echo '<p class="description custausu-communications__description">' . esc_html($T(
      'Remote Admin Messages are optional JSON administrative notices from customauthsuite.com. They are disabled by default and require explicit admin enablement. No remote JavaScript or arbitrary HTML is executed.',
      'I Messaggi Admin Remoti sono notifiche amministrative JSON opzionali da customauthsuite.com. Sono disabilitati di default e richiedono attivazione esplicita dell’amministratore. Nessun JavaScript remoto o HTML arbitrario viene eseguito.'
    )) . '</p>';
    echo '<p class="description custausu-communications__description">' . esc_html($rm_scope_copy) . '</p>';
    echo '<input type="hidden" name="custausu_global_settings[custausu_rm_messages_enabled]" value="0">';
    $sw('custausu_global_settings[custausu_rm_messages_enabled]', (bool) $rm_messages_enabled, $T('Enable Remote Admin Messages', 'Abilita Messaggi Admin Remoti'), false);
    echo '</td></tr>';

    echo '<tr><th scope="row">' . esc_html($T('Privacy-safe Interaction Analytics', 'Analytics di interazione privacy-safe')) . '</th><td>';
    echo '<p class="description custausu-communications__description">' . esc_html($rm_analytics_copy) . '</p>';
    echo '<input type="hidden" name="custausu_global_settings[custausu_rm_analytics_enabled]" value="0">';
    $sw('custausu_global_settings[custausu_rm_analytics_enabled]', (bool) $rm_analytics_enabled, $T('Enable privacy-safe interaction analytics', 'Abilita analytics di interazione privacy-safe'), false);
    echo '</td></tr>';

    echo '<tr><th scope="row">' . esc_html($T('Assisted Doctor Support', 'Supporto Assistito Doctor')) . '</th><td>';
    echo '<p>' . esc_html($T('Support handoff:', 'Handoff supporto:')) . ' <span class="custausu-rm-client-status-badge ' . esc_attr($doctor_support_status_class) . '">' . esc_html($doctor_support_status_label) . '</span></p>';
    echo '<p class="description custausu-communications__description">' . esc_html($T(
      'Disabled by default. When enabled, CAS prepares a short-lived, redacted Doctor Report handoff for the “Open support request” action. customauthsuite.com retrieves it only after the administrator clicks that action, allowing the support form to be prefilled and the report attached automatically.',
      'Disabilitato di default. Quando è attivo, CAS prepara un handoff temporaneo e oscurato del Doctor Report per l’azione “Apri richiesta supporto”. customauthsuite.com lo recupera solo dopo il clic dell’amministratore, consentendo la precompilazione del form e l’allegato automatico del report.'
    )) . '</p>';
    echo '<p class="description custausu-communications__description">' . esc_html($T(
      'The report may contain site URLs, WordPress/PHP versions, theme and plugin inventory, CAS configuration summaries, compatibility checks and redacted support references. It does not intentionally include raw passwords, complete license keys, cookies, private tokens or authentication secrets. Turning this setting off immediately revokes all existing handoffs. Local Doctor checks and manual JSON/HTML downloads remain available.',
      'Il report può contenere URL del sito, versioni WordPress/PHP, inventario di tema e plugin, riepiloghi della configurazione CAS, controlli di compatibilità e riferimenti supporto oscurati. Non include intenzionalmente password in chiaro, chiavi licenza complete, cookie, token privati o segreti di autenticazione. Disattivando questa impostazione, tutti gli handoff esistenti vengono revocati immediatamente. I controlli Doctor locali e i download manuali JSON/HTML restano disponibili.'
    )) . '</p>';
    $sw(
      'custausu_global_settings[custausu_doctor_assisted_support_enabled]',
      (bool) $doctor_assisted_support_enabled,
      $T('Enable Assisted Doctor Support', 'Abilita Supporto Assistito Doctor'),
      false
    );
    echo '</td></tr>';

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

    return (string) ob_get_clean();
  }
}


if (!function_exists('custausu_admin_render_debug_section')) {
  function custausu_admin_render_debug_section(
    array $opt,
    bool $debug_enabled,
    callable $T,
    callable $sw
  ): string {
    unset($opt, $debug_enabled, $sw);

    $preview_switch = static function(string $label, bool $small = false): void {
      $class = 'custausu-switch' . ($small ? ' custausu-switch--sm' : '');
      echo '<label class="' . esc_attr($class) . '">';
      echo '<input type="checkbox" disabled aria-disabled="true">';
      echo '<span class="custausu-slider" aria-hidden="true"></span>';
      echo '<span class="custausu-label">' . esc_html($label) . '</span>';
      echo '</label>';
    };

    ob_start();

    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Internal admin gate renderer returns controlled admin HTML.
    echo wp_kses( custausu_admin_gate_wrap_start('advanced_debug_tools', $T), custausu_admin_allowed_output_html() );
    echo '<table class="widefat striped custausu-debug-tools custausu-debug-tools--preview">';
    echo '<thead class="custausu-head"><tr><th colspan="2" class="custausu-debug-tools__head-cell"><h2 class="custausu-debug-tools__title"><span class="dashicons dashicons-admin-tools"></span> | Debug</h2></th></tr></thead>';
    echo '<tbody>';

    echo '<tr><th scope="row">' . esc_html($T('Enable CAS Debug', 'Abilita debug CAS')) . '</th><td>';
    $preview_switch($T('When enabled, CAS writes debug logs and can print extra console messages.', 'Se attivo, CAS scrive log di debug e può stampare messaggi extra in console.'));
    echo '</td></tr>';

    echo '<tr><th scope="row">' . esc_html($T('Log levels', 'Livelli log')) . '</th><td>';
    echo '<fieldset class="custausu-debug-deps" disabled aria-disabled="true">';
    echo '<div class="custausu-debug-tools__options">';
    foreach (['error', 'warn', 'info'] as $level) {
      $preview_switch($level, true);
    }
    echo '</div>';
    echo '<p class="description">' . esc_html($T('Choose which severities are written to log files.', 'Scegli quali severità vengono scritte nei file di log.')) . '</p>';
    echo '</fieldset>';
    echo '</td></tr>';

    echo '<tr><th scope="row">' . esc_html($T('Feature channels', 'Canali feature')) . '</th><td>';
    echo '<fieldset class="custausu-debug-deps" disabled aria-disabled="true">';
    echo '<div class="custausu-debug-tools__verbose-toggle">';
    $preview_switch($T('Verbose debug per feature (enables channels below)', 'Debug dettagliato per feature (abilita i canali sotto)'));
    echo '</div>';
    echo '<fieldset class="custausu-debug-channels" disabled aria-disabled="true">';
    echo '<div class="custausu-debug-tools__options">';
    foreach (['lostpassword', 'recaptcha', 'passkey', 'login', 'register', 'webauthn', 'email', 'redirect'] as $channel) {
      $preview_switch($channel, true);
    }
    echo '</div>';
    echo '</fieldset>';
    echo '<p class="description">' . esc_html($T(
      'Channels filter ONLY verbose [DEBUG] logs. Enable verbose to use them.',
      'I canali filtrano SOLO i log [DEBUG] dettagliati. Attiva il verbose per usarli.'
    )) . '</p>';
    echo '</fieldset>';
    echo '</td></tr>';

    echo '</tbody></table>';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Internal admin gate renderer returns controlled admin HTML.
    echo wp_kses( custausu_admin_gate_wrap_end(), custausu_admin_allowed_output_html() );

    return (string) ob_get_clean();
  }
}

if (!function_exists('custausu_admin_render_protected_paths_section')) {
  function custausu_admin_render_protected_paths_section(
    callable $T,
    array $opt,
    callable $get_field_box_class,
    callable $get_field_note_html
  ): string {
    $protected = (string)($opt['protected_paths'] ?? '');

    ob_start();

    echo '<table id="custausu-section-protected-paths" class="widefat striped custausu-protected-paths">';
    echo '<thead class="custausu-head"><tr><th colspan="2" class="custausu-protected-paths__head-cell"><h2 class="custausu-protected-paths__title"><span class="dashicons dashicons-lock"></span> | '.esc_html($T('Protected Paths','Percorsi Protetti')).'</h2></th></tr></thead>';
    echo '<tbody><tr><th scope="row">'.esc_html($T('Paths (one per line)','Percorsi (uno per riga)')).'</th><td>';
    echo '<div class="'.esc_attr($get_field_box_class('protected_paths')).'" data-custausu-field="protected_paths">';
    echo '<textarea name="custausu_global_settings[protected_paths]" rows="6" class="custausu-protected-paths__textarea">' . esc_textarea($protected) . '</textarea>';
    echo '<p class="description">'.esc_html($T('Example: /albums/ and /it/albums/ (we normalize with trailing slash). Use the final full path, including the language prefix when present (see original URL of your page for reference).','Esempio: /albums/ e /it/albums/ (normalizziamo con slash finale). Usa il percorso finale completo, incluso il prefisso lingua quando presente (controlla l\'Url della tua pagina per referenza)')).'</p>';
    echo wp_kses( $get_field_note_html('protected_paths'), custausu_admin_allowed_output_html() );
    echo '</div>';
    echo '</td></tr></tbody></table>';

    return (string) ob_get_clean();
  }
}

if (!function_exists('custausu_admin_build_field_alert_context')) {
  function custausu_admin_build_field_alert_context(callable $T): array {
    $field_alerts = function_exists('custausu_wizard_collect_field_alerts')
      ? custausu_wizard_collect_field_alerts($T)
      : [];

    $field_alert_map = [];
    $route_lang_alerts = [];

    foreach ((array)$field_alerts as $row) {
      $target   = (string)($row['target'] ?? '');
      $severity = strtolower(trim((string)($row['severity'] ?? '')));
      $message  = (string)($row['message'] ?? '');

      if ($target === '' || !in_array($severity, ['error', 'warn'], true)) {
        continue;
      }

      if (
        !isset($field_alert_map[$target]) ||
        ($field_alert_map[$target]['severity'] === 'warn' && $severity === 'error')
      ) {
        $field_alert_map[$target] = [
          'severity' => $severity,
          'message'  => $message,
        ];
      }

      if (strpos($target, 'route:') === 0) {
        $parts = explode(':', $target);
        if (count($parts) === 3) {
          $lng = (string)$parts[1];

          if (
            !isset($route_lang_alerts[$lng]) ||
            ($route_lang_alerts[$lng] === 'warn' && $severity === 'error')
          ) {
            $route_lang_alerts[$lng] = $severity;
          }
        }
      }
    }

    $get_field_alert = function(string $target) use ($field_alert_map): array {
      return $field_alert_map[$target] ?? [];
    };

    $get_field_box_class = function(string $target) use ($get_field_alert): string {
      $a   = $get_field_alert($target);
      $sev = (string)($a['severity'] ?? '');

      if ($sev === 'error') return 'custausu-field-alert custausu-field-alert--error';
      if ($sev === 'warn')  return 'custausu-field-alert custausu-field-alert--warn';

      return 'custausu-field-alert';
    };

    $get_field_note_html = function(string $target) use ($get_field_alert): string {
      $a   = $get_field_alert($target);
      $sev = (string)($a['severity'] ?? '');
      $msg = (string)($a['message'] ?? '');

      if ($sev === '' || $msg === '') return '';

      return '<div class="custausu-field-alert__note custausu-field-alert__note--' . esc_attr($sev) . '">'
        . esc_html($msg)
        . '</div>';
    };

    $route_lang_has_alert = function(string $lang) use ($route_lang_alerts): bool {
      return !empty($route_lang_alerts[$lang]);
    };

    return [
      'field_alert_map'      => $field_alert_map,
      'route_lang_alerts'    => $route_lang_alerts,
      'get_field_alert'      => $get_field_alert,
      'get_field_box_class'  => $get_field_box_class,
      'get_field_note_html'  => $get_field_note_html,
      'route_lang_has_alert' => $route_lang_has_alert,
    ];
  }
}
