<?php
/**
 * Shared storage for the offer link and the admin password.
 *
 * The link and the password hash live in separate files so that a misconfigured
 * server which serves data/config.json cannot also leak the credential.
 */
declare(strict_types=1);

const DATA_DIR    = __DIR__ . '/../data';
const CONFIG_FILE = DATA_DIR . '/config.json';
const AUTH_FILE   = DATA_DIR . '/auth.json';

const DEFAULT_LINK = 'https://example.com/replace-me';

function read_json(string $file, array $defaults): array
{
    if (!is_file($file)) {
        return $defaults;
    }
    $raw = file_get_contents($file);
    if ($raw === false) {
        return $defaults;
    }
    $data = json_decode($raw, true);

    return is_array($data) ? array_merge($defaults, $data) : $defaults;
}

/** Write via a temp file and rename, so a concurrent reader never sees half a file. */
function write_json(string $file, array $data): bool
{
    if (!is_dir(DATA_DIR) && !mkdir(DATA_DIR, 0775, true) && !is_dir(DATA_DIR)) {
        return false;
    }
    $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    if ($json === false) {
        return false;
    }
    $tmp = $file . '.tmp';
    if (file_put_contents($tmp, $json . "\n", LOCK_EX) === false) {
        return false;
    }

    return rename($tmp, $file);
}

function config_load(): array
{
    return read_json(CONFIG_FILE, ['link' => DEFAULT_LINK, 'updated_at' => null]);
}

function config_save(string $link): bool
{
    return write_json(CONFIG_FILE, [
        'link'       => $link,
        'updated_at' => gmdate('c'),
    ]);
}

function auth_hash(): ?string
{
    $auth = read_json(AUTH_FILE, ['password_hash' => null]);
    $hash = $auth['password_hash'];

    return is_string($hash) && $hash !== '' ? $hash : null;
}

function auth_set_password(string $password): bool
{
    return write_json(AUTH_FILE, [
        'password_hash' => password_hash($password, PASSWORD_DEFAULT),
        'updated_at'    => gmdate('c'),
    ]);
}

/** Only absolute http(s) URLs — the value is written straight into an href. */
function link_is_valid(string $url): bool
{
    if ($url === '' || filter_var($url, FILTER_VALIDATE_URL) === false) {
        return false;
    }
    $scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));

    return in_array($scheme, ['http', 'https'], true);
}
