<?php

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

/**
 * Permission callback for features REST API routes
 * 
 * @return boolean Whether the user can access the endpoint
 */
function content_craft_ai_features_permission_callback()
{
  // Only allow authenticated users
  $api_key = get_option('content_craft_ai_api_key');
  if (empty($api_key)) {
    return false;
  }

  // Verify nonce
  $nonce_verified = wp_verify_nonce(
    isset($_SERVER['HTTP_X_WP_NONCE']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_X_WP_NONCE'])) : '',
    'wp_rest'
  );

  if (!$nonce_verified) {
    // error_log('Content Craft AI: Features nonce verification failed');
    return false;
  }

  return true;
}

/**
 * Register features routes
 */
function content_craft_ai_register_features_routes()
{
  // Get AI models
  register_rest_route('content-craft-ai/v1', '/features/ai-models', array(
    'methods' => 'GET',
    'callback' => 'content_craft_ai_get_models',
    'permission_callback' => 'content_craft_ai_features_permission_callback',
  ));

  // Get image services
  register_rest_route('content-craft-ai/v1', '/features/image-services', array(
    'methods' => 'GET',
    'callback' => 'content_craft_ai_get_image_services',
    'permission_callback' => 'content_craft_ai_features_permission_callback',
  ));

  // Get WordPress categories
  register_rest_route('content-craft-ai/v1', '/features/categories', array(
    'methods' => 'GET',
    'callback' => 'content_craft_ai_handle_get_categories',
    'permission_callback' => 'content_craft_ai_article_generator_permission_callback',
  ));
}

// Register routes
add_action('rest_api_init', 'content_craft_ai_register_features_routes');
