<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * Add a per-widget `powered_by_text` field so the admin can type the
 * exact string they want at the bottom of the chat widget — no longer
 * tied to the global Site Name.
 *
 * Why this column exists:
 *   The widget's "Powered by ..." line previously derived its brand name
 *   from system_settings.site_name via WhiteLabel::brandName(). That
 *   helper deliberately rejects the literal "MailTrixy" string (so a
 *   reseller who forgot to change the default Site Name doesn't leak
 *   the source product name into every visitor's chat). The side effect
 *   was that customers who actually wanted ANY credit shown had no way
 *   to set it short of changing their global Site Name. This column
 *   gives them a dedicated input — they type whatever they want here
 *   and the widget shows it verbatim.
 *
 * Resolution order at /api/widget/status:
 *   1. chat_widgets.powered_by_text  (this column, if non-empty)
 *   2. WhiteLabel::brandName()       (falls through with MailTrixy guard)
 *   3. show_branding := false        (no footer rendered)
 *
 * Idempotent — checks for the column before adding, so re-running on
 * a partially-migrated install is safe.
 */
return new class extends Migration {
    public function up(): void
    {
        if (!Schema::hasColumn('chat_widgets', 'powered_by_text')) {
            Schema::table('chat_widgets', function (Blueprint $table) {
                // Nullable VARCHAR(60) — long enough for "Powered by Acme
                // Customer Care" but short enough to stay readable in the
                // single-line footer. Empty / null → fall back to
                // WhiteLabel::brandName() in the status payload.
                $table->string('powered_by_text', 60)->nullable()->after('show_branding');
            });
        }
    }

    public function down(): void
    {
        if (Schema::hasColumn('chat_widgets', 'powered_by_text')) {
            Schema::table('chat_widgets', function (Blueprint $table) {
                $table->dropColumn('powered_by_text');
            });
        }
    }
};
