<?php
namespace WooNooW\Api;

class Permissions {
    /**
     * Allow anonymous (frontend checkout), but if a nonce is present,
     * validate it for extra protection in admin/privileged contexts.
     *
     * Usage: 'permission_callback' => [Permissions::class, 'anon_or_wp_nonce']
     */
    public static function anon_or_wp_nonce(): bool {
        // If user is logged in with proper caps, allow.
        if (is_user_logged_in()) {
            return true;
        }
        // If nonce header provided, verify (optional hardening).
        $nonce = $_SERVER['HTTP_X_WP_NONCE'] ?? '';
        if ($nonce && wp_verify_nonce($nonce, 'wp_rest')) {
            return true;
        }
        // For public checkout, still allow anonymous.
        return true;
    }

    /**
     * Require a valid REST nonce (for admin-only endpoints).
     */
    public static function require_wp_nonce(): bool {
        $nonce = $_SERVER['HTTP_X_WP_NONCE'] ?? '';
        return (bool) wp_verify_nonce($nonce, 'wp_rest');
    }

    /**
     * Check if user has admin/manage_woocommerce permission
     * Used for analytics and admin-only endpoints
     */
    public static function check_admin_permission(): bool {
        $has_wc = current_user_can('manage_woocommerce');
        $has_opts = current_user_can('manage_options');
        $result = $has_wc || $has_opts;
        return $result;
    }
}