<?php
/**
 * IndexationPage Manager (MVP-001, 2026-08-01).
 *
 * Client-side storage + retrieval for the operator's indexation page URL.
 * The URL is stored in WP options and submitted to the server via
 * POST /v1/indexation-page/register (HMAC-signed).
 *
 * Storage: WP option 'swapads_client_indexation_page' (string URL or '').
 *
 * @package SwapAds\Client\Indexation
 *
 * @since 1.5.7
 */

declare(strict_types=1);

namespace SwapAds\Client\Indexation;

/**
 * Class IndexationPage.
 *
 * @since 1.5.7
 */
final class IndexationPage
{
    public const OPTION_KEY = 'swapads_client_indexation_page';

    public const MAX_LENGTH = 512;

    /**
     * Get the stored indexation page URL, or empty string if not set.
     *
     * @return string URL or ''.
     *
     * @since 1.5.7
     */
    public static function get(): string
    {
        return (string) get_option(self::OPTION_KEY, '');
    }

    /**
     * Validate + store the indexation page URL locally.
     *
     * @param string $url URL to store.
     *
     * @return array<string, mixed> Result {success: bool, error?: string, url: string}.
     *
     * @since 1.5.7
     */
    public static function save(string $url): array
    {
        $url = trim($url);
        if ($url === '') {
            // Allow clearing the value.
            update_option(self::OPTION_KEY, '');
            return ['success' => true, 'url' => ''];
        }

        if (!self::isValid($url)) {
            return [
                'success' => false,
                'error'   => 'Indexation page URL must be a valid http(s) URL.',
                'url'     => $url,
            ];
        }

        update_option(self::OPTION_KEY, $url);
        return ['success' => true, 'url' => $url];
    }

    /**
     * Delete the stored URL (empty string).
     *
     * @return bool True if option was deleted/updated.
     *
     * @since 1.5.7
     */
    public static function clear(): bool
    {
        return (bool) update_option(self::OPTION_KEY, '');
    }

    /**
     * Validate that the URL is well-formed.
     *
     * @param string $url URL.
     *
     * @return bool True if valid.
     *
     * @since 1.5.7
     */
    public static function isValid(string $url): bool
    {
        if (strlen($url) > self::MAX_LENGTH) {
            return false;
        }
        if (!preg_match('#^https?://#i', $url)) {
            return false;
        }
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            return false;
        }
        return true;
    }
}