<?php

namespace App\Helpers;

use App\Models\SystemSetting;

/**
 * BrandingHelper — single source of truth for the platform's display
 * identity (name, host, support emails) anywhere a Blade view or
 * controller needs it.
 *
 * Why this exists: parts of the UI used to ship hardcoded "MailTrixy"
 * or "app.mailtrixy.com" strings (workspace slug prefix, email
 * placeholders, dashboard copy, landing page testimonials). Resellers
 * who installed under their own brand would see those leak through —
 * even though Admin → Settings → General → Site Name was set correctly.
 * Routing every brand reference through this helper means changing the
 * site name once in admin actually renames the whole platform.
 *
 * Use from Blade as: `{{ \App\Helpers\BrandingHelper::name() }}`
 */
class BrandingHelper
{
    /**
     * The configured platform name.
     *
     * Resolution order:
     *   1. system_settings.site_name (admin → Settings → General) — wins
     *      whenever it has content, including the literal "MailTrixy"
     *      (the platform's actual product name for the team running
     *      this codebase).
     *   2. config('app.name')  (env APP_NAME)
     *   3. The literal "MailTrixy" as the final fallback so a fresh
     *      install — before admin types anything in Site Name — still
     *      shows the real product brand instead of a placeholder.
     *
     * Previous versions of this helper explicitly *rejected* the string
     * "MailTrixy" at every step as an anti-leak guard for resellers who
     * never retyped the default. That guard was overcorrecting: the team
     * building this product, and customers who chose "MailTrixy" as
     * their own brand, both saw the helper fall through to the generic
     * "App" string and leak that into the admin sidebar header, PWA
     * prompt, page <title>, and notification emails. Resellers who want
     * to rebrand still do so the obvious way — by typing their brand in
     * Site Name. No magic filtering needed.
     */
    public static function name(): string
    {
        try {
            $n = trim((string) SystemSetting::get('site_name', ''));
            if ($n !== '') {
                return $n;
            }
        } catch (\Throwable $e) {
            // DB not ready — fall through
        }
        $envName = trim((string) config('app.name', ''));
        if ($envName !== '') {
            return $envName;
        }
        return 'MailTrixy';
    }

    /**
     * Parsed host portion of APP_URL — used as the prefix for the
     * workspace slug input and as the domain in email placeholders.
     *
     * APP_URL=https://app.acme.com  →  "app.acme.com"
     * APP_URL=http://localhost:8000 →  "localhost"
     */
    public static function host(): string
    {
        $url = (string) config('app.url', '');
        $host = parse_url($url, PHP_URL_HOST);
        return $host ?: 'localhost';
    }

    /**
     * Strip a leading subdomain (`app.`, `www.`) to get the bare root
     * domain — better for email defaults so "support@acme.com" is the
     * placeholder, not "support@app.acme.com".
     */
    public static function rootDomain(): string
    {
        $host = self::host();
        if (str_starts_with($host, 'app.'))  return substr($host, 4);
        if (str_starts_with($host, 'www.'))  return substr($host, 4);
        return $host;
    }

    /**
     * Pre-baked email-shape placeholder for input fields. Pass any local
     * part — e.g. emailPlaceholder('support') → 'support@yourbrand.com'.
     */
    public static function emailPlaceholder(string $local): string
    {
        return $local . '@' . self::rootDomain();
    }

    /**
     * Support email — admin-configured `support_email` setting falls back
     * to "support@{rootDomain}" derived from APP_URL.
     */
    public static function supportEmail(): string
    {
        try {
            $val = SystemSetting::get('support_email', '');
            if ($val !== '') return $val;
        } catch (\Throwable $e) {
            // ignore
        }
        return self::emailPlaceholder('support');
    }
}
