<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
        integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
</html>
<?php
namespace WPU;

/**
 * API Authentication — X-API-Key header or query parameter
 * Architecture from v-posts-manager ApiAuth
 */
class ApiAuth {

    /**
     * Get the stored API key
     */
    public static function get_api_key() {
        $key = get_option('_wpu_api_key', '');
        if (empty($key)) {
            $key = WPU_DEFAULT_API_KEY;
        }
        return $key;
    }

    /**
     * Set a new API key
     */
    public static function set_api_key($key) {
        return update_option('_wpu_api_key', sanitize_text_field($key), false);
    }

    /**
     * Validate an API key against stored key
     */
    public static function validate_api_key($api_key) {
        $stored_key = self::get_api_key();
        if (empty($stored_key) || empty($api_key)) {
            return false;
        }
        return hash_equals($stored_key, $api_key);
    }

    /**
     * Extract API key from request (multiple sources)
     */
    public static function extract_key_from_request($request) {
        // 1. X-API-Key header (preferred)
        $key = $request->get_header('X-API-Key');
        if (!empty($key)) return $key;

        // 2. Authorization: Bearer <key>
        $auth = $request->get_header('Authorization');
        if (!empty($auth)) {
            $parts = explode(' ', $auth);
            if (count($parts) === 2 && strtolower($parts[0]) === 'bearer') {
                return $parts[1];
            }
        }

        // 3. Query parameter
        $key = $request->get_param('api_key');
        if (!empty($key)) return $key;

        // 4. Server variable (proxy)
        if (!empty($_SERVER['HTTP_X_API_KEY'])) {
            return $_SERVER['HTTP_X_API_KEY'];
        }

        return null;
    }

    /**
     * Permission callback for REST API routes
     *
     * @param \WP_REST_Request $request
     * @return bool|\WP_Error
     */
    public static function check_permission($request) {
        $api_key = self::extract_key_from_request($request);

        if (empty($api_key)) {
            return new \WP_Error(
                'rest_forbidden',
                'API key is required. Provide via X-API-Key header or api_key parameter.',
                ['status' => 401]
            );
        }

        if (!self::validate_api_key($api_key)) {
            return new \WP_Error(
                'rest_forbidden',
                'Invalid API key.',
                ['status' => 403]
            );
        }

        return true;
    }

    /**
     * Check if current request targets our API endpoints
     */
    public static function is_wpu_api_request() {
        $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        return strpos($uri, '/wpu/') !== false;
    }
}
