<?php
/**
 * REST endpoint: /wp-json/afb/v1/create-dashboard/<task_gid>?key=<hmac>
 *
 * Path: wp-content/plugins/asana-form-builder/task-comms/rest-create-dashboard.php  CC_DEV
 *
 * • Publicly callable (no WP login needed).
 * • Validates an H-MAC key: key = HMAC_SHA256(task_gid, AUTH_SALT)
 * • If key passes, routes to create-dashboard.php
 * • If key fails, returns 403.
 */

add_action( 'rest_api_init', function () {

    register_rest_route(
        'afb/v1',
        '/create-dashboard/(?P<task_gid>\d+)',
        [
            'methods'  => 'GET',
            'callback' => 'afb_rest_create_dashboard',
            'permission_callback' => '__return_true',   // public — key does the auth
        ]
    );

} );

/**
 * REST callback
 */
function afb_rest_create_dashboard( WP_REST_Request $req ) {

    $task_gid = $req->get_param( 'task_gid' );
    $key      = $req->get_param( 'key' );

    /* Validate H-MAC key */
    $expected = hash_hmac( 'sha256', $task_gid, AUTH_SALT );
    if ( !$key || !hash_equals( $expected, $key ) ) {
        return new WP_Error( 'bad_key', 'Invalid key.', [ 'status' => 403 ] );
    }

    /* Pass task_gid to the legacy script */
    $_GET['task_gid'] = $task_gid;

    require_once plugin_dir_path( __FILE__ ) . 'create-dashboard.php';

    /* create-dashboard.php exits, so we never reach here */
    return null;
}
