<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Support;

defined('ABSPATH') || exit;

class UserDesignLinks
{
    public static function buildResumeUrl(int $productId, int $userDesignId, string $accessToken = '', bool $forceModalOpen = true, array $options = []) : string
    {
        if ($productId <= 0 || $userDesignId <= 0) {
            return '';
        }

        $url = get_permalink($productId);
        if (! $url) {
            return '';
        }

        $args = [
            'apd_resume_design' => $userDesignId,
        ];

        if ($accessToken !== '') {
            $args['apd_access_token'] = $accessToken;
        }

        $variationId = absint($options['variation_id'] ?? 0);
        if ($variationId > 0) {
            $args['apd_variation_id'] = $variationId;
        }

        $attributes = $options['attributes'] ?? [];
        if (is_array($attributes)) {
            foreach ($attributes as $key => $value) {
                $name = sanitize_key((string) $key);
                if ($name === '' || strpos($name, 'attribute_') !== 0) {
                    continue;
                }
                $args[$name] = wc_clean(wp_unslash((string) $value));
            }
        }

        if ($forceModalOpen) {
            $args['apd_resume_open'] = '1';
        }

        return add_query_arg($args, $url);
    }
}
