<?php

declare(strict_types=1);

namespace PpPhp\Core\Update;

/**
 * Where this copy of PPPHP reads its signed update index from.
 *
 * The update authority publishes ONE signed index.json to the file host — a list
 * of every live release + delta, signed with the same Ed25519 key the licence
 * server holds. Because the host (not any one database) is the source of truth,
 * publishing from anywhere (a developer's laptop included) reaches every install:
 * each client fetches the index straight from the host and verifies it OFFLINE
 * against the pinned public key (\PpPhp\Core\Licensing\LicenseTrust).
 *
 * For that to work a client has to KNOW the host URL. This file pins it, exactly
 * as LicenseTrust pins the trust key: the owner stamps it once (it is derived
 * automatically from the Update host's Public download URL when the host config
 * is saved) and it then travels inside every bundle. Left empty during
 * development, a client with a database setting or a configured host still finds
 * its index; only shipped customer bundles rely on this constant.
 *
 * INDEX_URL is a plain https URL to the index file. It is not a secret.
 */
final class UpdateTrust
{
    public const INDEX_URL = 'https://ppphp-updates.ppradhan.com.np/index.json';

    /** The pinned index URL, or '' when this build is unstamped (development). */
    public static function indexUrl(): string
    {
        $u = trim(self::INDEX_URL);
        return preg_match('#^https?://#i', $u) ? rtrim($u, '/') : '';
    }

    public static function isStamped(): bool
    {
        return self::indexUrl() !== '';
    }

    /**
     * Rewrite this file with a new index URL. Owner-only, and deliberately a
     * source edit rather than a setting so it travels inside every packaged
     * bundle. A blank string clears the pin (returns to development behaviour).
     */
    public static function stamp(string $url): bool
    {
        $url = trim($url);
        if ($url !== '' && !preg_match('#^https?://[^\s]+#i', $url)) return false;

        $file = __FILE__;
        $src  = (string) @file_get_contents($file);
        if ($src === '') return false;

        $new = preg_replace(
            "/public const INDEX_URL = '[^']*';/",
            "public const INDEX_URL = '" . rtrim($url, '/') . "';",
            $src,
            1,
            $count
        );
        if (!is_string($new) || $count !== 1) return false;

        return @file_put_contents($file, $new, LOCK_EX) !== false;
    }
}
