<?php

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

/**
 * Permission callback for settings REST API routes
 * 
 * @return boolean Whether the user can access the endpoint
 */
function content_craft_ai_settings_permission_callback()
{
  // Only allow authenticated users with a valid token
  $token = get_option('content_craft_ai_token');
  if (empty($token)) {
    return false;
  }

  // Verify nonce for CSRF protection
  $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: Settings nonce verification failed');
    return false;
  }

  return true;
}

/**
 * Register settings routes
 */
function content_craft_ai_register_settings_routes()
{
  // Update settings route - we don't need a GET route as per requirements
  register_rest_route('content-craft-ai/v1', '/settings', array(
    'methods' => 'POST',
    'callback' => 'content_craft_ai_handle_update_settings',
    'permission_callback' => 'content_craft_ai_settings_permission_callback',
  ));

  // Internal links routes
  register_rest_route('content-craft-ai/v1', '/internal-links/refresh', array(
    'methods' => 'POST',
    'callback' => 'content_craft_ai_refresh_internal_links',
    'permission_callback' => 'content_craft_ai_settings_permission_callback',
  ));

  register_rest_route('content-craft-ai/v1', '/internal-links/stats', array(
    'methods' => 'GET',
    'callback' => 'content_craft_ai_get_internal_links_stats',
    'permission_callback' => 'content_craft_ai_settings_permission_callback',
  ));
}

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