<?php
// Utility Functions for SAC Plugin
if ( ! defined('ABSPATH') ) exit;

/**
 * Get incoming API key from:
 * - Header: x-api-key
 * - Query/body param: key (legacy)
 * - Query/body param: api_key (alternate)
 */
if ( ! function_exists('myaio_sac_get_incoming_api_key') ) {
    function myaio_sac_get_incoming_api_key( WP_REST_Request $request ): string {
        $incoming = $request->get_header('x-api-key');

        if ( empty($incoming) ) {
            $incoming = $request->get_param('key');
        }

        if ( empty($incoming) ) {
            $incoming = $request->get_param('api_key');
        }

        if ( ! is_string($incoming) ) {
            return '';
        }

        return sanitize_text_field( wp_unslash($incoming) );
    }
}

/**
 * Validate API key against stored option and verified flag.
 */
if ( ! function_exists('myaio_sac_validate_api_key') ) {
    function myaio_sac_validate_api_key( WP_REST_Request $request ): bool {
        $incoming = myaio_sac_get_incoming_api_key($request);

        $expected = (string) get_option('myaio_sac_api_key', '');
        $verified = (bool) get_option('myaio_sac_api_verified', false);

        if ( ! $verified || $expected === '' || $incoming === '' ) {
            return false;
        }

        return hash_equals($expected, $incoming);
    }
}

/**
 * Standard permission callback for REST routes (recommended).
 * Use in register_rest_route(): 'permission_callback' => 'myaio_sac_rest_permission_check'
 */
if ( ! function_exists('myaio_sac_rest_permission_check') ) {
    function myaio_sac_rest_permission_check( WP_REST_Request $request ) {
        if ( myaio_sac_validate_api_key($request) ) {
            return true;
        }
        return new WP_Error('unauthorized', 'Invalid or unverified API key', ['status' => 401]);
    }
}

/**
 * Optional helper if you want EXACT same unauthorized output everywhere.
 * Use at the top of callbacks when you keep permission_callback = __return_true.
 */
if ( ! function_exists('myaio_sac_require_api_key_or_401') ) {
    function myaio_sac_require_api_key_or_401( WP_REST_Request $request ) {
        if ( myaio_sac_validate_api_key($request) ) {
            return true;
        }
        return new WP_REST_Response(['error' => 'Unauthorized'], 401);
    }
}

/**
 * Helper: get all site URLs (posts + pages)
 */
if ( ! function_exists('myaio_sac_get_all_site_urls') ) {
    function myaio_sac_get_all_site_urls(): array {
        $urls = [];

        $posts = get_posts([
            'post_type'   => ['post', 'page'],
            'post_status' => 'publish',
            'numberposts' => -1,
            'fields'      => 'ids',
        ]);

        foreach ( (array) $posts as $post_id ) {
            $urls[] = [
                'url'  => get_permalink($post_id),
                'type' => get_post_type($post_id),
            ];
        }

        return $urls;
    }
}
