<?php

namespace App\Helpers;

use App\Models\Workspace;
use App\Services\PlanLimitService;

/**
 * Centralized white-label decision helper.
 *
 * Layout files call WhiteLabel::shouldShowPoweredBy() to decide whether
 * to render a "Powered by [BrandName]" footer line. The result depends
 * on the current workspace's plan — workspaces with the `white_label`
 * plan feature enabled get a clean unbranded view; others see the
 * platform credit (which the admin operator can still rebrand site-wide
 * via Settings → Branding → site_name).
 *
 * Falls back to "show" (true) when there's no workspace context (public
 * marketing pages, login screens) — those are always unbranded by the
 * platform-level site_name and don't need the per-tenant flag.
 */
class WhiteLabel
{
    /**
     * Return true if the current workspace should DISPLAY the platform's
     * "Powered by" credit. Returns false ONLY when the workspace has an
     * active subscription on a plan that explicitly enables `white_label`.
     *
     * Why this deliberately bypasses PlanLimitService::hasFeature:
     *  - hasFeature() returns true for any workspace that contains an
     *    admin member (isExempt path) — so on a typical install where the
     *    super-admin set up the first workspace, white-label would
     *    silently be ON for everyone. That makes sense for "permissive"
     *    features (admin shouldn't hit plan caps in their own workspace)
     *    but is the WRONG default for a paid-tier feature like white-label.
     *  - hasFeature() also returns true when there's no plan at all
     *    (free / unsubscribed workspaces). Again, permissive default is
     *    wrong for white-label — free customers should see the credit.
     *
     * The strict rule: white-label is opt-in. A workspace must (a) have
     * an active subscription, (b) on a plan that has the white_label
     * feature flag enabled, AND (c) have it set to enabled=true on the
     * specific PlanFeature row. Anything else falls through to "show".
     */
    public static function shouldShowPoweredBy(?Workspace $workspace = null): bool
    {
        // Resolve workspace from auth() if not passed explicitly
        if (!$workspace && auth()->check()) {
            $workspace = auth()->user()->activeWorkspace ?? null;
        }

        if (!$workspace) {
            return true;
        }

        try {
            // Pull the workspace's active subscription. Anything else
            // (no subscription, cancelled, past-due) keeps the credit on.
            //
            // Workspace exposes a singular `subscription()` HasOne with
            // latestOfMany() — useful for "current" lookups but it doesn't
            // filter by status, so a workspace with both an old canceled
            // sub AND a new active one might resolve to either depending
            // on insertion order. Query the Subscription model directly
            // so we get a hard "active + not canceled" guarantee.
            $subscription = \App\Models\Subscription::query()
                ->where('workspace_id', $workspace->id)
                ->where('status', 'active')
                ->whereNull('canceled_at')
                ->latest('id')
                ->first();

            if (!$subscription || !$subscription->plan_id) {
                return true;
            }

            // Look for the explicit per-plan feature row. We don't rely on
            // PlanLimitService here because we need a hard yes/no — no
            // admin-exempt, no "no-plan = allow" fallback.
            $feature = \App\Models\PlanFeature::query()
                ->where('plan_id', $subscription->plan_id)
                ->where('feature_key', 'white_label')
                ->where('enabled', true)
                ->first();

            // Show the credit unless the plan has white_label explicitly enabled.
            return !$feature;
        } catch (\Throwable $e) {
            // DB unavailable / model missing: default to safe (show credit).
            return true;
        }
    }

    /**
     * Inverse helper for templates that want a positive condition
     * (more readable in blade @if checks).
     */
    public static function isWhiteLabeled(?Workspace $workspace = null): bool
    {
        return !self::shouldShowPoweredBy($workspace);
    }

    /**
     * The brand name to display anywhere — falls back to config('app.name')
     * (which itself reads from APP_NAME in .env). The original 3rd-level
     * fallback was the literal "MailTrixy" — that leaked through whenever
     * a customer ran on a fresh install with empty config. The widget
     * "Powered by" line checks for empty-string and hides the badge
     * entirely if there's no brand, so returning '' on a misconfigured
     * install is preferable to leaking the platform's source name.
     */
    public static function brandName(): string
    {
        try {
            $siteName = trim((string) \App\Models\SystemSetting::get('site_name', ''));
            // Treat a literal "MailTrixy" stored in the DB the same as
            // an empty value. Previously the guard below only ran on the
            // APP_NAME fallback path, so a customer whose admin settings
            // form persisted the default "MailTrixy" string (resellers
            // routinely click Save without touching the field) saw the
            // platform's source name leak into the chat widget's
            // "Powered by" footer, password-reset emails, invoice issuer
            // line, etc. The blank-string return lets the calling code
            // (widget /status, layout footer) short-circuit and hide
            // the credit entirely. The Site Name input default has
            // since been changed to blank to prevent the persisted-leak
            // path going forward, but this guard catches every existing
            // install that already saved the bad value.
            if ($siteName !== '' && strcasecmp($siteName, 'MailTrixy') !== 0) {
                return $siteName;
            }
        } catch (\Throwable $e) {
            // DB not ready (fresh install) — fall through
        }
        $envName = trim((string) config('app.name', ''));
        // Refuse to return the literal source-product name as a fallback
        // (otherwise a customer with no Site Name set would see "Powered
        // by MailTrixy" on their live chat widget).
        if ($envName === '' || strcasecmp($envName, 'MailTrixy') === 0) {
            return '';
        }
        return $envName;
    }
}
