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

/**
 * Classic WordPress admin notices for CAS Remote Messages.
 *
 * Important architecture:
 * - Remote Admin Messages are product/admin notices delivered as safe JSON.
 * - Privacy-safe Interaction Analytics are optional telemetry events.
 * - Analytics must remain OFF until an administrator explicitly opts in.
 */

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

if (!function_exists('custausu_admin_rm_notice_settings')) {
  function custausu_admin_rm_notice_settings(): array {
    $settings = get_option('custausu_global_settings', []);
    $settings = is_array($settings) ? $settings : [];

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

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

    if (!array_key_exists('custausu_rm_messages_enabled', $settings)) {
      $settings['custausu_rm_messages_enabled'] = 0;
    }

    return $settings;
  }
}

if (!function_exists('custausu_admin_rm_notice_update_settings')) {
  function custausu_admin_rm_notice_update_settings(array $updates): bool {
    $preferences = get_option(custausu_admin_rm_preferences_option_name(), []);
    $preferences = is_array($preferences) ? $preferences : [];

    foreach ($updates as $key => $value) {
      $key = sanitize_key((string) $key);

      if (!in_array($key, ['custausu_rm_messages_enabled', 'custausu_rm_analytics_enabled'], true)) {
        continue;
      }

      $preferences[$key] = !empty($value) ? 1 : 0;
    }

    return (bool) update_option(custausu_admin_rm_preferences_option_name(), $preferences, false);
  }
}



if (!function_exists('custausu_admin_rm_handle_settings_form_preferences')) {
  /**
   * Persist Remote Messages preferences from the main CAS Settings form.
   */
  function custausu_admin_rm_handle_settings_form_preferences(): void {
    if (!is_admin() || !current_user_can('manage_options')) {
      return;
    }

    global $pagenow;

    if ((string) $pagenow !== 'options.php') {
      return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is verified below before reading settings values.
    $option_page = isset($_POST['option_page']) ? sanitize_key((string) wp_unslash($_POST['option_page'])) : '';

    if ($option_page !== 'custausu_settings_group') {
      return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is checked immediately below.
    $nonce = isset($_POST['_wpnonce'])
      ? sanitize_text_field(wp_unslash((string) $_POST['_wpnonce']))
      : '';

    if (!wp_verify_nonce($nonce, 'custausu_settings_group-options')) {
      return;
    }

    /*
     * Read CAS RM preferences from the posted settings form.
     */
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above; value is sanitized immediately.
    $messages_raw = isset($_POST['custausu_global_settings']['custausu_rm_messages_enabled'])
      ? sanitize_text_field(wp_unslash((string) $_POST['custausu_global_settings']['custausu_rm_messages_enabled']))
      : '0';

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above; value is sanitized immediately.
    $analytics_raw = isset($_POST['custausu_global_settings']['custausu_rm_analytics_enabled'])
      ? sanitize_text_field(wp_unslash((string) $_POST['custausu_global_settings']['custausu_rm_analytics_enabled']))
      : '0';

    custausu_admin_rm_notice_update_settings([
      'custausu_rm_messages_enabled'  => ($messages_raw === '1') ? 1 : 0,
      'custausu_rm_analytics_enabled' => ($analytics_raw === '1') ? 1 : 0,
    ]);
  }
}

add_action('admin_init', 'custausu_admin_rm_handle_settings_form_preferences', 1);


if (!function_exists('custausu_admin_rm_notice_dismissals')) {
  function custausu_admin_rm_notice_dismissals(): array {
    $raw = get_option('custausu_admin_classic_notice_dismissals', []);
    return is_array($raw) ? $raw : [];
  }
}

if (!function_exists('custausu_admin_rm_notice_is_dismissed')) {
  function custausu_admin_rm_notice_is_dismissed(string $notice_id): bool {
    $dismissals = custausu_admin_rm_notice_dismissals();
    $key = sanitize_key($notice_id);

    if (empty($dismissals[$key])) {
      return false;
    }

    $until = (int) $dismissals[$key];

    if ($until > 0 && $until < time()) {
      unset($dismissals[$key]);
      update_option('custausu_admin_classic_notice_dismissals', $dismissals, false);
      return false;
    }

    return true;
  }
}

if (!function_exists('custausu_admin_rm_notice_dismiss')) {
  function custausu_admin_rm_notice_dismiss(string $notice_id, int $days = 30): void {
    $key = sanitize_key($notice_id);
    $days = max(1, min(3650, $days));

    $dismissals = custausu_admin_rm_notice_dismissals();
    $dismissals[$key] = time() + ($days * DAY_IN_SECONDS);

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

if (!function_exists('custausu_admin_rm_notice_current_screen_id')) {
  function custausu_admin_rm_notice_current_screen_id(): string {
    $screen = function_exists('get_current_screen') ? get_current_screen() : null;
    return $screen && isset($screen->id) ? sanitize_key((string) $screen->id) : '';
  }
}

if (!function_exists('custausu_admin_rm_notice_is_cas_screen')) {
  function custausu_admin_rm_notice_is_cas_screen(): bool {
    $screen_id = custausu_admin_rm_notice_current_screen_id();

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

    return (
      strpos($screen_id, 'cas') !== false ||
      strpos($screen_id, 'custom-auth-suite') !== false
    );
  }
}

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

    $screen_id = custausu_admin_rm_notice_current_screen_id();

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

    $blocked_fragments = [
      'update',
      'plugin-install',
      'theme-install',
      'customize',
      'site-health',
      'tools_page_health-check',
    ];

    foreach ($blocked_fragments as $blocked) {
      if (strpos($screen_id, $blocked) !== false) {
        return false;
      }
    }

    return true;
  }
}


if (!function_exists('custausu_admin_rm_render_classic_notices')) {
  function custausu_admin_rm_render_classic_notices(): void {
    if (!custausu_admin_rm_notice_global_screen_allowed()) {
      return;
    }

    $is_cas_screen = custausu_admin_rm_notice_is_cas_screen();

    $settings = custausu_admin_rm_notice_settings();

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

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

    $locale = function_exists('determine_locale') ? determine_locale() : get_locale();
    $it = is_string($locale) && strpos(strtolower($locale), 'it') === 0;

    if ($is_cas_screen && $messages_enabled && !$analytics_enabled && !custausu_admin_rm_notice_is_dismissed('rm_analytics_optin')) {
      $enable_url = wp_nonce_url(
        admin_url('admin-post.php?action=custausu_rm_enable_analytics'),
        'custausu_rm_enable_analytics'
      );

      $dismiss_url = wp_nonce_url(
        admin_url('admin-post.php?action=custausu_rm_dismiss_classic_notice&notice=rm_analytics_optin&days=30'),
        'custausu_rm_dismiss_classic_notice'
      );

      echo '<div class="notice notice-info is-dismissible custausu-admin-classic-notice custausu-admin-classic-notice--rm-analytics">';
      echo '<p><strong>' . esc_html($it ? 'Custom Auth Suite™ — Analytics privacy-safe' : 'Custom Auth Suite™ — Privacy-safe analytics') . '</strong></p>';
      echo '<p>' . esc_html($it
        ? 'I messaggi remoti amministrativi sono attivi. Gli analytics di interazione restano spenti finché non dai consenso esplicito. Se attivati, sono anonimi, aggregati e globali, e non tracciano il sito su cui Custom Auth Suite™ è installato.'
        : 'Remote Admin Messages are enabled. Interaction analytics are off until you explicitly opt in. If enabled, they are anonymous, aggregated and global, and do not track the website where Custom Auth Suite™ is installed.'
      ) . '</p>';
      echo '<p>';
      echo '<a class="button button-primary" href="' . esc_url($enable_url) . '">' . esc_html($it ? 'Attiva analytics privacy-safe' : 'Enable privacy-safe analytics') . '</a> ';
      echo '<a class="button" href="' . esc_url($dismiss_url) . '">' . esc_html($it ? 'Non ora' : 'Not now') . '</a>';
      echo '</p>';
      echo '</div>';
    }

  }
}

add_action('admin_notices', 'custausu_admin_rm_render_classic_notices', 30);

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

    check_admin_referer('custausu_rm_enable_analytics');

    $enabled = 1;

    custausu_admin_rm_notice_update_settings([
      'custausu_rm_messages_enabled'  => $enabled,
      'custausu_rm_analytics_enabled' => $enabled,
    ]);

    custausu_admin_rm_notice_dismiss('rm_analytics_optin', 3650);

    wp_safe_redirect(wp_get_referer() ?: admin_url('admin.php?page=custausu-settings'));
    exit;
  }
}

add_action('admin_post_custausu_rm_enable_analytics', 'custausu_admin_rm_handle_enable_analytics');

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

    check_admin_referer('custausu_rm_dismiss_classic_notice');

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce checked above; value is sanitized immediately.
    $notice = isset($_GET['notice']) ? sanitize_key((string) wp_unslash($_GET['notice'])) : '';

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce checked above; value is sanitized immediately.
    $days = isset($_GET['days']) ? absint(wp_unslash($_GET['days'])) : 30;

    if ($notice !== '') {
      custausu_admin_rm_notice_dismiss($notice, $days);
    }

    wp_safe_redirect(wp_get_referer() ?: admin_url('admin.php?page=custausu-settings'));
    exit;
  }
}

add_action('admin_post_custausu_rm_dismiss_classic_notice', 'custausu_admin_rm_handle_dismiss_classic_notice');
