<?php
/**
 * Pretty-URL router  /create-dashboard?task_gid=<id>&key=<hmac>
 *
 * • Adds a rewrite rule for /create-dashboard
 * • Reads both task_gid and key from the query string
 * • 302-redirects to the REST endpoint, preserving the key
 */

/* 1. Register extra query vars */
add_filter( 'query_vars', function ( $vars ) {
    $vars[] = 'afc_create_dash';   // marker
    $vars[] = 'task_gid';
    $vars[] = 'key';
    return $vars;
} );

/* 2. Add rewrite rule  /create-dashboard */
add_action( 'init', function () {
    add_rewrite_rule(
        '^create-dashboard/?$',                // /create-dashboard
        'index.php?afc_create_dash=1',         // sets our marker
        'top'
    );
}, 10 );

/* 3. Redirect to the REST route, preserving key */
add_action( 'template_redirect', function () {

    if ( get_query_var( 'afc_create_dash' ) !== '1' ) {
        return;   // not our route
    }

    $task_gid = sanitize_text_field( $_GET['task_gid'] ?? '' );
    $key      = sanitize_text_field( $_GET['key']      ?? '' );

    if ( !$task_gid || !$key ) {
        wp_die( 'Missing task_gid or key.', 400 );
    }

    // Build REST endpoint URL and append the key
    $rest_url = add_query_arg(
        'key',
        rawurlencode( $key ),
        rest_url( "/afb/v1/create-dashboard/{$task_gid}" )
    );

    wp_redirect( $rest_url, 302 );
    exit;
} );
