<?php

namespace WPSN\Admin;

defined('ABSPATH') || exit;

/**
 * Small helper for preserving Tasks Hub queue context inside internal module
 * screens.
 *
 * This is intentionally lightweight so admin pages can keep their existing
 * pageUrl()/redirect helpers while automatically carrying:
 * - return_to (Tasks Hub workspace URL)
 * - wpsn_task_queue_title
 * - wpsn_task_queue_key
 * - wpsn_task_ref
 */
final class TasksWorkbenchContext
{
    /**
     * @return array<string,string>
     */
    public static function requestArgs(bool $includeTaskRef = true): array
    {
        $out = [];

        $returnToRaw = self::requestValue('return_to');
        $returnTo = $returnToRaw !== null ? esc_url_raw((string) wp_unslash($returnToRaw)) : '';
        if ($returnTo !== '') {
            $out['return_to'] = $returnTo;
        }

        $queueTitleRaw = self::requestValue('wpsn_task_queue_title');
        $queueTitle = $queueTitleRaw !== null ? sanitize_text_field((string) wp_unslash($queueTitleRaw)) : '';
        if ($queueTitle !== '') {
            $out['wpsn_task_queue_title'] = $queueTitle;
        }

        $snapshotKeyRaw = self::requestValue('wpsn_task_queue_key');
        $snapshotKey = $snapshotKeyRaw !== null ? sanitize_key((string) wp_unslash($snapshotKeyRaw)) : '';
        if ($snapshotKey !== '') {
            $out['wpsn_task_queue_key'] = $snapshotKey;
        }

        if ($includeTaskRef) {
            $taskRefRaw = self::requestValue('wpsn_task_ref');
            $taskRef = $taskRefRaw !== null ? self::sanitizeTaskRef((string) wp_unslash($taskRefRaw)) : '';
            if ($taskRef !== '') {
                $out['wpsn_task_ref'] = $taskRef;
            }
        }

        return $out;
    }

    public static function isActive(): bool
    {
        return self::requestArgs(false) !== [];
    }

    /**
     * @param array<string,mixed> $args
     * @return array<string,mixed>
     */
    public static function mergeArgs(array $args = [], bool $includeTaskRef = true): array
    {
        $context = self::requestArgs($includeTaskRef);
        if ($context === []) {
            return $args;
        }

        foreach ($context as $key => $value) {
            if (!array_key_exists($key, $args) || $args[$key] === '' || $args[$key] === null) {
                $args[$key] = $value;
            }
        }

        return $args;
    }

    public static function decorateUrl(string $url, bool $includeTaskRef = true): string
    {
        $url = trim($url);
        if ($url === '') {
            return '';
        }

        $context = self::requestArgs($includeTaskRef);
        if ($context === []) {
            return $url;
        }

        return (string) add_query_arg($context, $url);
    }

    /**
     * @param array<string,mixed> $args
     */
    public static function pageUrl(string $pageSlug, array $args = [], string $script = 'tools.php', bool $includeTaskRef = true): string
    {
        $base = admin_url($script);
        $args = array_merge(['page' => sanitize_key($pageSlug)], $args);
        $args = self::mergeArgs($args, $includeTaskRef);

        return (string) add_query_arg($args, $base);
    }


    /**
     * @return mixed|null
     */
    private static function requestValue(string $key)
    {
        if (array_key_exists($key, $_REQUEST)) {
            return $_REQUEST[$key];
        }

        if (array_key_exists($key, $_GET)) {
            return $_GET[$key];
        }

        if (array_key_exists($key, $_POST)) {
            return $_POST[$key];
        }

        return null;
    }
    private static function sanitizeTaskRef(string $ref): string
    {
        $ref = trim($ref);
        if ($ref === '') {
            return '';
        }

        $ref = preg_replace('/[^a-zA-Z0-9:_\-]/', '', $ref);
        return is_string($ref) ? $ref : '';
    }
}
