<?php

declare(strict_types=1);

namespace PrettyLinks\Pro\Tools;

use PrettyLinks\Options\Store as OptionsStore;

class Bookmarklet
{
    /**
     * V3 drop-in: token lives inside `prli_options.bookmarklet_auth`.
     */
    public const TOKEN_KEY = 'bookmarklet_auth';

    public const ENDPOINT_QUERY_VAR = 'prli_bookmarklet';

    /**
     * Get the stored bookmarklet token, generating and persisting one if absent.
     *
     * @return string The bookmarklet auth token.
     */
    public static function getOrCreateToken(): string
    {
        $store = new OptionsStore();
        $token = (string) $store->get(self::TOKEN_KEY, '');
        if ($token === '') {
            $token = wp_generate_password(40, false, false);
            $store->set(self::TOKEN_KEY, $token);
        }
        return $token;
    }

    /**
     * Generate a fresh bookmarklet token and persist it, replacing any existing one.
     *
     * @return string The newly generated bookmarklet auth token.
     */
    public static function regenerateToken(): string
    {
        $token = wp_generate_password(40, false, false);
        (new OptionsStore())->set(self::TOKEN_KEY, $token);
        return $token;
    }

    /**
     * Build the `javascript:` bookmarklet payload that posts the current page to the endpoint.
     *
     * @param  string               $endpointUrl The bookmarklet endpoint URL.
     * @param  string               $token       The bookmarklet auth token.
     * @param  array<string, mixed> $extraParams Optional query params baked into the bookmarklet URL (e.g. `['category_ids' => [5, 7]]`). The handler reads them from `$_REQUEST` when the bookmarklet fires.
     * @return string The bookmarklet JavaScript payload.
     */
    public static function payload(string $endpointUrl, string $token, array $extraParams = []): string
    {
        $hasQuery    = strpos($endpointUrl, '?') !== false;
        $endsWithVar = substr($endpointUrl, -strlen(self::ENDPOINT_QUERY_VAR) - 1)
            === self::ENDPOINT_QUERY_VAR . '=';

        if ($endsWithVar) {
            $base = $endpointUrl . rawurlencode($token);
        } else {
            $base = $endpointUrl
                . ($hasQuery ? '&' : '?')
                . self::ENDPOINT_QUERY_VAR . '=' . rawurlencode($token);
        }

        if ($extraParams !== []) {
            $base .= '&' . http_build_query($extraParams);
        }

        $jsBase = wp_json_encode($base);
        if (!is_string($jsBase)) {
            $jsBase = '""';
        }

        return 'javascript:(function(){'
            . 'var u=' . $jsBase . ';'
            . 'var t=encodeURIComponent(document.title||"");'
            . 'var l=encodeURIComponent(document.location.href);'
            . 'void(window.open(u+"&target_url="+l+"&name="+t));'
            . '})();';
    }
}
