<?php

// If this file is called directly, abort.
if (!defined('WPINC')) {
	die;
}

// API Reindex Endpoints
add_action('rest_api_init', function() {
	// Posts Categories Reindex
	register_rest_route('rest/v1', '/getPostsCategories', [
		'methods' => 'GET',
		'callback' => 'athena_api_reindex_posts_categories',
		'permission_callback' => 'athena_verify_integration_key'
	]);

	// Posts Reindex (with pagination)
	register_rest_route('rest/v1', '/getPosts', [
		'methods' => 'GET',
		'callback' => 'athena_api_reindex_posts',
		'permission_callback' => 'athena_verify_integration_key'
	]);
});
// END API Reindex Endpoints

// Reindex Posts Categories
function athena_api_reindex_posts_categories(WP_REST_Request $request) {
	try {
		if (!class_exists('ApiReindexController')) {
			require_once ASWP_ATHENA_CORE_INC . 'Controller/ApiReindexController.php';
		}

		$apiReindexController = new ApiReindexController();
		$postsCategories = $apiReindexController->getPostsCategories();

		return new WP_REST_Response($postsCategories, 200);
	} catch (Exception $e) {
		return new WP_REST_Response([
			'success' => false,
			'error' => $e->getMessage()
		], 500);
	}
}
// END Reindex Posts Categories

// Reindex Posts with Pagination
function athena_api_reindex_posts(WP_REST_Request $request) {
	try {
		if (!class_exists('ApiReindexController')) {
			require_once ASWP_ATHENA_CORE_INC . 'Controller/ApiReindexController.php';
		}

		// Get page parameter from query string (default to 1)
		$page = $request->get_param('page');
		$page = $page ? (int) $page : 1;

		// Validate page number
		if ($page < 1) {
			return new WP_REST_Response([
				'success' => false,
				'error' => 'Invalid page number. Must be >= 1'
			], 400);
		}

		$apiReindexController = new ApiReindexController();
		$posts = $apiReindexController->getPosts($page);

		return new WP_REST_Response($posts, 200);
	} catch (Exception $e) {
		return new WP_REST_Response([
			'success' => false,
			'error' => $e->getMessage()
		], 500);
	}
}
// END Reindex Posts with Pagination

// Verify Integration Key for REST API requests
function athena_verify_integration_key(WP_REST_Request $request) {
	$auth_header = $request->get_header('Authorization');

	// Check if header exists and has "Bearer" format
	if (!$auth_header || !preg_match('/Bearer\s+(.*)$/i', $auth_header, $matches)) {
		return new WP_Error('no_auth', 'Missing authorization header', ['status' => 401]);
	}

	$provided_key = $matches[1];

	// Load integration key from options
	$options = get_option('athena_options', []);
	$integration_key = $options['integration_key'] ?? '';

	// Verify key
	if (empty($integration_key) || $provided_key !== $integration_key) {
		return new WP_Error('invalid_auth', 'Invalid integration key', ['status' => 401]);
	}

	return true;
}