<?php

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

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

    // Verify JWT token validity if available
    $token = get_option('content_craft_ai_token');
    if (empty($token)) {
        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: Notifications nonce verification failed');
        return false;
    }

    return true;
}

/**
 * Register notifications routes
 */
function content_craft_ai_register_notifications_routes()
{
    // Get notifications
    register_rest_route('content-craft-ai/v1', '/notifications', array(
        'methods' => 'GET',
        'callback' => 'content_craft_ai_get_notifications',
        'permission_callback' => 'content_craft_ai_notifications_permission_callback',
        'args' => array(
            'page' => array(
                'default' => 1,
                'sanitize_callback' => 'absint',
            ),
            'limit' => array(
                'default' => 10,
                'sanitize_callback' => 'absint',
            ),
        ),
    ));

    // Dismiss notification
    register_rest_route('content-craft-ai/v1', '/notifications/(?P<id>[a-zA-Z0-9-]+)/dismiss', array(
        'methods' => 'POST',
        'callback' => 'content_craft_ai_dismiss_notification',
        'permission_callback' => 'content_craft_ai_notifications_permission_callback',
        'args' => array(
            'id' => array(
                'validate_callback' => function ($param) {
                    return !empty($param);
                }
            ),
        ),
    ));
}

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