<?php

/**
 * Authentication Check
 * 
 * Handles all authentication checks and redirects for the plugin
 */

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

/**
 * Check if a user is authenticated by verifying stored token and user data
 *
 * @return bool True if authenticated, false otherwise
 */
function content_craft_ai_is_authenticated()
{
  $token = get_option('content_craft_ai_token');

  // If no token exists, user is not authenticated
  if (empty($token)) {
    return false;
  }

  // Call the check_auth function that verifies the token with the API
  // This will return false if token is expired and clear the token
  $user = content_craft_ai_check_auth();

  return !empty($user);
}

/**
 * Get plugin page URL
 * 
 * @param string $page Page slug without the plugin prefix
 * @return string Full admin URL for the page
 */
function content_craft_ai_get_page_url($page = '')
{
  if (empty($page)) {
    // Default to auth page
    return add_query_arg(
      'page',
      'content-craft-ai',
      admin_url('admin.php')
    );
  }

  return add_query_arg(
    'page',
    'content-craft-ai-' . $page,
    admin_url('admin.php')
  );
}

/**
 * Check if current page is a Content Craft AI plugin page
 * 
 * @return bool|string False if not a plugin page, or the page slug if it is
 */
function content_craft_ai_is_plugin_page()
{
  // Only check admin pages with a page parameter
  // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page slug from URL for navigation, not processing form data
  if (!is_admin() || !isset($_GET['page'])) {
    return false;
  }

  // Sanitize and unslash the page parameter
  // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page slug from URL for navigation, not processing form data
  $current_page = sanitize_text_field(wp_unslash($_GET['page']));

  // Check if this is one of our plugin pages
  if (strpos($current_page, 'content-craft-ai') === false) {
    return false;
  }

  return $current_page;
}

/**
 * Redirect to auth page with appropriate parameters
 * 
 * @param bool $manual_logout Whether this is a manual logout
 */
function content_craft_ai_redirect_to_auth($manual_logout = false)
{
  $param = $manual_logout ? 'manual_logout' : 'auth_expired';
  wp_safe_redirect(add_query_arg($param, '1', content_craft_ai_get_page_url()));
  exit;
}

/**
 * Early authentication check that runs at plugins_loaded
 */
function content_craft_ai_early_auth_check()
{
  $current_page = content_craft_ai_is_plugin_page();

  // Only proceed if this is a protected plugin page (not the auth page itself)
  if ($current_page && $current_page !== 'content-craft-ai' && strpos($current_page, 'content-craft-ai-') === 0) {
    // If not authenticated, redirect to auth page
    if (!content_craft_ai_is_authenticated()) {
      content_craft_ai_redirect_to_auth();
    }
  }
}

/**
 * Standard authentication redirect handler
 */
function content_craft_ai_handle_auth_redirects()
{
  $current_page = content_craft_ai_is_plugin_page();

  // Only proceed for plugin pages
  if (!$current_page) {
    return;
  }

  $is_authenticated = content_craft_ai_is_authenticated();

  // Case 1: User is authenticated but on the auth page - redirect to dashboard
  if ($is_authenticated && $current_page === 'content-craft-ai') {
    wp_safe_redirect(content_craft_ai_get_page_url('dashboard'));
    exit;
  }

  // Case 2: User is not authenticated but trying to access protected pages
  if (!$is_authenticated && $current_page !== 'content-craft-ai') {
    // Check if this is a manual logout - sanitize and unslash the parameter
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading logout parameter from URL for navigation flow, not processing form data
    $was_logout = isset($_GET['logout']) ? sanitize_text_field(wp_unslash($_GET['logout'])) === '1' : false;
    content_craft_ai_redirect_to_auth($was_logout);
  }
}

/**
 * Initialize authentication checks
 */
function content_craft_ai_init_auth_checks()
{
  // Add the earliest possible auth check
  add_action('plugins_loaded', 'content_craft_ai_early_auth_check');

  // Add admin_init check with higher priority to handle redirects properly
  add_action('admin_init', 'content_craft_ai_handle_auth_redirects', 20);
}

// Initialize auth checks
content_craft_ai_init_auth_checks();
