<?php
/**
 * REST endpoints for payment provider webhooks (preparation).
 *
 * @package Maca_Menu_List
 */

if (!defined('ABSPATH')) {
    exit;
}

add_action('rest_api_init', 'maca_menulist_payments_register_rest_routes');

/**
 * Register payment webhook routes.
 */
function maca_menulist_payments_register_rest_routes() {
    foreach (array_keys(maca_menulist_payments_get_providers()) as $provider_id) {
        register_rest_route(
            'maca-menulist/v1',
            '/payments/' . $provider_id . '/webhook',
            array(
                'methods'             => 'POST',
                'callback'            => 'maca_menulist_payments_rest_webhook_handler',
                'permission_callback' => '__return_true',
            )
        );
    }
}

/**
 * Webhook handler placeholder — verifies configuration only.
 *
 * @param WP_REST_Request $request Request.
 * @return WP_REST_Response|WP_Error
 */
function maca_menulist_payments_rest_webhook_handler($request) {
    $provider_id = sanitize_key((string) $request->get_param('provider_id'));
    $route = $request->get_route();

    if (preg_match('#/payments/([a-z]+)/webhook#', $route, $m)) {
        $provider_id = $m[1];
    }

    $provider = maca_menulist_payments_get_provider($provider_id);
    if (!$provider) {
        return new WP_Error('unknown_provider', __('Unknown payment provider.', 'maca-restu-pro'), array('status' => 404));
    }

    /**
     * Process provider webhook (Stripe signature, Swish callback, etc.).
     *
     * @param string          $provider_id Provider id.
     * @param WP_REST_Request $request     Request.
     */
    $result = apply_filters('maca_menulist_payments_webhook_' . $provider_id, null, $request);

    if ($result === null) {
        return new WP_REST_Response(
            array(
                'received' => true,
                'message'  => __('Webhook endpoint is ready. Payment processing will be enabled in a future update.', 'maca-restu-pro'),
            ),
            200
        );
    }

    if (is_wp_error($result)) {
        return $result;
    }

    return new WP_REST_Response(array('received' => true), 200);
}
