<?php

declare(strict_types=1);

namespace PpPhp\Core;

/**
 * The email server configuration BAKED INTO the distribution bundle by default.
 *
 * When the owner has configured Settings → Email on the build machine, the
 * packager stamps those values in here, so every bundle ships knowing how to send
 * mail. A fresh (or freshly-updated) install therefore sends owner-recovery and
 * account emails with nothing to configure — and the moment a customer enters
 * THEIR OWN details in Settings → Email, theirs takes over (see
 * PlatformSettings::primeMailer, which prefers the database config and only falls
 * back to this default).
 *
 * DATA is base64 of a JSON {host,port,encryption,username,password,fromAddress,
 * fromName} — the same shape the mailer already uses. Empty on an unstamped
 * (development) build.
 */
final class MailDefault
{
    // Intentionally EMPTY in source — a live credential must never live in the
    // repository or ship to customers. The packager stamps the build machine's
    // Settings → Email into the SERVER bundle at build time (from the database),
    // and CLIENT bundles are always shipped unstamped (customers configure their
    // own SMTP in Settings → Email). See PlatformPackager::rewrittenEntries().
    public const DATA = 'eyJob3N0Ijoic210cC5yZXNlbmQuY29tIiwicG9ydCI6IjQ2NSIsImVuY3J5cHRpb24iOiJzc2wiLCJ1c2VybmFtZSI6InJlc2VuZCIsInBhc3N3b3JkIjoicmVfRnVRMmpuam9fTmVyWEdlcUg4cWM2dlIxU1YxaDhoZnduIiwiZnJvbUFkZHJlc3MiOiJwcHBocEBwcHJhZGhhbi5jb20ubnAiLCJmcm9tTmFtZSI6IlBQUEhQIFJBRCJ9';

    /** The baked email config, or [] when this build is unstamped. */
    public static function config(): array
    {
        $raw = base64_decode(trim(self::DATA), true);
        $c = (is_string($raw) && $raw !== '') ? json_decode($raw, true) : null;
        return is_array($c) ? $c : [];
    }

    public static function isConfigured(): bool
    {
        $c = self::config();
        return trim((string) ($c['host'] ?? '')) !== '' && trim((string) ($c['fromAddress'] ?? '')) !== '';
    }

    /**
     * Stamp an email config into this file. Called by the packager at build time
     * from the build machine's Settings → Email, so the bundle carries it. A
     * source edit (like LicenseTrust / UpdateTrust) so it travels in every bundle
     * and is delivered by updates.
     */
    public static function stamp(array $cfg): bool
    {
        $out = [];
        foreach (['host', 'port', 'encryption', 'username', 'password', 'fromAddress', 'fromName'] as $k) {
            if (isset($cfg[$k]) && $cfg[$k] !== '') $out[$k] = $cfg[$k];
        }
        $b64 = $out === [] ? '' : base64_encode((string) json_encode($out, JSON_UNESCAPED_SLASHES));

        $file = __FILE__;
        $src  = (string) @file_get_contents($file);
        if ($src === '') return false;
        $new = preg_replace("/public const DATA = '[^']*';/", "public const DATA = '" . $b64 . "';", $src, 1, $n);
        return is_string($new) && $n === 1 && @file_put_contents($file, $new, LOCK_EX) !== false;
    }
}
