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

if (!function_exists('custausu_safe_mode_option_name')) {
  function custausu_safe_mode_option_name(): string {
    return 'custausu_safe_mode_state';
  }
}

if (!function_exists('custausu_safe_mode_truthy')) {
  function custausu_safe_mode_truthy($value): bool {
    if (is_bool($value)) {
      return $value;
    }

    $value = strtolower(trim((string) $value));
    return in_array($value, ['1', 'true', 'yes', 'on'], true);
  }
}

if (!function_exists('custausu_safe_mode_is_forced')) {
  function custausu_safe_mode_is_forced(): bool {
    return defined('CUSTAUSU_SAFE_MODE_FORCE')
      && custausu_safe_mode_truthy(CUSTAUSU_SAFE_MODE_FORCE);
  }
}

if (!function_exists('custausu_safe_mode_force_constant_name')) {
  function custausu_safe_mode_force_constant_name(): string {
    return 'CUSTAUSU_SAFE_MODE_FORCE';
  }
}

if (!function_exists('custausu_safe_mode_option_state')) {
  function custausu_safe_mode_option_state(): array {
    $state = get_option(custausu_safe_mode_option_name(), []);
    return is_array($state) ? $state : [];
  }
}

if (!function_exists('custausu_safe_mode_is_enabled')) {
  function custausu_safe_mode_is_enabled(): bool {
    if (custausu_safe_mode_is_forced()) {
      return true;
    }

    $state = custausu_safe_mode_option_state();
    return !empty($state['enabled']);
  }
}

if (!function_exists('custausu_safe_mode_source')) {
  function custausu_safe_mode_source(): string {
    if (custausu_safe_mode_is_forced()) {
      return 'wp-config';
    }

    return custausu_safe_mode_is_enabled() ? 'option' : 'off';
  }
}

if (!function_exists('custausu_safe_mode_reason')) {
  function custausu_safe_mode_reason(): string {
    if (custausu_safe_mode_is_forced()) {
      return 'forced_by_wp_config';
    }

    $state = custausu_safe_mode_option_state();
    return sanitize_key((string)($state['reason'] ?? 'manual'));
  }
}

if (!function_exists('custausu_safe_mode_enable')) {
  function custausu_safe_mode_enable(string $reason = 'manual'): bool {
    $reason = sanitize_key($reason);
    if ($reason === '') {
      $reason = 'manual';
    }

    $state = [
      'enabled'        => true,
      'reason'         => $reason,
      'enabled_at_utc' => gmdate('Y-m-d H:i:s'),
      'enabled_by'     => function_exists('get_current_user_id') ? (int) get_current_user_id() : 0,
    ];

    return update_option(custausu_safe_mode_option_name(), $state, false);
  }
}

if (!function_exists('custausu_safe_mode_disable')) {
  function custausu_safe_mode_disable(): bool {
    return delete_option(custausu_safe_mode_option_name());
  }
}

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

    if (!custausu_safe_mode_is_enabled()) {
      return;
    }

    $is_forced = custausu_safe_mode_is_forced();

    $message = function_exists('custausu_admin_t')
      ? custausu_admin_t(
        'CAS Safe Mode is active. CAS custom redirects are temporarily bypassed; protected paths fall back to the native WordPress login.',
        'CAS Safe Mode è attivo. I redirect custom CAS sono temporaneamente bypassati; i percorsi protetti usano il login WordPress nativo.'
        )
      : 'CAS Safe Mode is active.';

    echo '<div class="notice notice-warning">';
    echo '<p><strong>Custom Auth Suite:</strong> ' . esc_html($message) . '</p>';

    if ($is_forced) {
      $force_constant = function_exists('custausu_safe_mode_force_constant_name')
        ? custausu_safe_mode_force_constant_name()
        : 'CUSTAUSU_SAFE_MODE_FORCE';

      $forced = function_exists('custausu_admin_t')
        ? sprintf(
            custausu_admin_t(
              'Safe Mode is forced by wp-config.php via %s. Remove it or set it to false to disable Safe Mode.',
              'Safe Mode è forzato da wp-config.php tramite %s. Rimuovilo oppure impostalo a false per disattivare Safe Mode.'
            ),
            $force_constant
          )
        : sprintf('Safe Mode is forced by wp-config.php via %s.', $force_constant);

      echo '<p>' . esc_html($forced) . '</p>';
    } else {
      $url = wp_nonce_url(
        admin_url('admin-post.php?action=custausu_disable_safe_mode'),
        'custausu_safe_mode_action'
      );

      $label = function_exists('custausu_admin_t')
        ? custausu_admin_t('Disable Safe Mode', 'Disattiva Safe Mode')
        : 'Disable Safe Mode';

      echo '<p><a class="button button-secondary" href="' . esc_url($url) . '">'
        . esc_html($label)
        . '</a></p>';
    }

    echo '</div>';
  }
}

if (is_admin()) {
  add_action('admin_notices', 'custausu_safe_mode_admin_notice');
}

