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


if (!function_exists('custausu_admin_logs_dir')) {
  function custausu_admin_logs_dir(): string {
    $uploads = function_exists('wp_upload_dir') ? wp_upload_dir(null, false) : [];

    if (!empty($uploads['basedir']) && is_string($uploads['basedir'])) {
      return rtrim($uploads['basedir'], '/') . '/custom-auth-suite/logs';
    }

    return rtrim(get_temp_dir(), '/') . '/custom-auth-suite/logs';
  }
}

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

    check_admin_referer('custausu_reset_settings');

    delete_option('custausu_global_settings');
    delete_option('cas_global_settings'); // Legacy option cleanup after prefix migration.

    wp_safe_redirect(add_query_arg([
      'page'       => 'custausu-settings',
      'custausu_notice' => 'settings_reset',
    ], admin_url('admin.php')));
    exit;
  }
}

if (!function_exists('custausu_admin_safe_mode_redirect_url')) {
  function custausu_admin_safe_mode_redirect_url(array $args = []): string {
    $url = wp_get_referer();

    if (!$url) {
      $url = admin_url('admin.php?page=custausu-settings');
    }

    $url = remove_query_arg(
      ['_wpnonce', 'action', 'custausu_safe_mode'],
      $url
    );

    return !empty($args) ? add_query_arg($args, $url) : $url;
  }
}

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

    check_admin_referer('custausu_safe_mode_action');

    if (!function_exists('custausu_safe_mode_enable')) {
      wp_die('CAS Safe Mode is unavailable.');
    }

    custausu_safe_mode_enable('admin');

    wp_safe_redirect(custausu_admin_safe_mode_redirect_url([
      'custausu_safe_mode' => 'enabled',
    ]));
    exit;
  }
}

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

    check_admin_referer('custausu_safe_mode_action');

    if (!function_exists('custausu_safe_mode_disable')) {
      wp_die('CAS Safe Mode is unavailable.');
    }

    custausu_safe_mode_disable();

    $status = (function_exists('custausu_safe_mode_is_forced') && custausu_safe_mode_is_forced())
      ? 'forced'
      : 'disabled';

    wp_safe_redirect(custausu_admin_safe_mode_redirect_url([
      'custausu_safe_mode' => $status,
    ]));
    exit;
  }
}

// -----------------------------------------------------------------------------
// License actions
// -----------------------------------------------------------------------------

