<?php

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

/**
 * Permission callback for title-article REST API routes
 * 
 * @return boolean Whether the user can access the endpoint
 */
function content_craft_ai_title_article_permission_callback()
{
    // Check if user is logged in and has proper capabilities
    if (!current_user_can('publish_posts')) {
        return false;
    }

    // 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: Title article nonce verification failed');
        return false;
    }

    return true;
}

/**
 * Register title-article routes
 */
function content_craft_ai_register_title_article_routes()
{
    // Load the handlers controller
    require_once CONTENT_CRAFT_AI_PLUGIN_PATH . 'app/controllers/title-article/TitleArticleHandlersController.php';
    $handlers_controller = TitleArticleHandlersController::get_instance();

    // Generate titles from keywords
    register_rest_route('content-craft-ai/v1', '/title-article/generate-titles', array(
        'methods' => 'POST',
        'callback' => array($handlers_controller, 'handle_generate_titles'),
        'permission_callback' => 'content_craft_ai_title_article_permission_callback',
    ));

    // Generate articles from titles
    register_rest_route('content-craft-ai/v1', '/title-article/generate-articles', array(
        'methods' => 'POST',
        'callback' => array($handlers_controller, 'handle_generate_articles'),
        'permission_callback' => 'content_craft_ai_title_article_permission_callback',
    ));
}

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