<?php

namespace auctionforge\inc\abs;

use auctionforge\inc\Debug;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\interfaces\Webhooks;
use WP_Error;
use WP_REST_Request;

abstract class BidspiritWebhooks implements Webhooks
{
    const APP_FIREBASE_COOKIE = 'FCM_TOKEN';
    const API_NAMESPACE = 'bidspirit/v1';

    protected function checkPermission()
    {
        $authToken = SettingsHelper::getOption('auth_token', '');
        return ($authToken != "" || defined('AUCTIONFORGE_API_TOKEN'));
    }

    /**
     * Base method to verify nonce from REST API requests
     * @param WP_REST_Request $request The REST request object
     * @return bool|WP_Error Returns true if nonce is valid, WP_Error otherwise
     */
    protected function verifyNonce(WP_REST_Request $request)
    {
        // Get nonce from request headers
        $nonce = isset($_SERVER['HTTP_X_WP_NONCE']) ? $_SERVER['HTTP_X_WP_NONCE'] : '';
        
        // Verify nonce
        if (empty($nonce) || !wp_verify_nonce($nonce, 'wp_rest')) {
            return new WP_Error('invalid_nonce', __('Invalid security token', 'auctionforge'), array('status' => 403));
        }

        return true;
    }

    /**
     * Check if user is authenticated and verify nonce for REST API requests
     * @param WP_REST_Request $request The REST request object
     * @return bool|WP_Error Returns true if user is authenticated and nonce is valid, WP_Error otherwise
     */
    public static function checkNoncePermission(WP_REST_Request $request)
    {
        // Check if user is logged in
        if (!is_user_logged_in()) {
            return new WP_Error('not_logged_in', __('User is not authenticated', 'auctionforge'), array('status' => 401));
        }

        // Use the base nonce verification
        return (new static)->verifyNonce($request);
    }

    /**
     * Default nonce permission check without authentication requirement
     * @param WP_REST_Request $request The REST request object
     * @return bool|WP_Error Returns true if nonce is valid, WP_Error otherwise
     */
    protected function checkNoncePermissionDefault(WP_REST_Request $request)
    {
        return $this->verifyNonce($request);
    }
}