<?php

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

/**
 * Sales order configuration moves from the tenant's own `app_settings` to the
 * landlord-controlled `tenant_settings`, alongside the POS master switches.
 *
 * The deadline window and auto-invoice flag were originally put on the tenant
 * side on the reasoning that "how urgent is a deadline" is an operational
 * judgement the shop should own. Reversed by product decision: these are now
 * configured from Master Control with the rest of the tenant's setup, joined by
 * the WhatsApp destination an order is sent to (which is landlord-provisioned
 * infrastructure, not a shop-floor preference).
 *
 * `app_settings` is deliberately left in place, values and all: dropping it is
 * a separate, reversible step once this has been running in production, and
 * keeping it means a rollback of this migration restores working settings
 * rather than defaults.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('tenant_settings', function (Blueprint $table) {
            $table->unsignedSmallInteger('sales_order_deadline_warning_days')->nullable()->after('pos_vouchers_enabled');
            $table->boolean('sales_order_auto_invoice')->nullable()->after('sales_order_deadline_warning_days');
            $table->string('sales_order_whatsapp_target', 255)->nullable()->after('sales_order_auto_invoice');
        });

        if (! Schema::hasTable('app_settings')) {
            return;
        }

        // Carry every tenant's existing choices across, so nobody's configured
        // deadline window or auto-invoice switch silently reverts to default.
        // Only tenants that already have a tenant_settings row are updated;
        // one without a row has never been configured from Master Control, and
        // the defaults it would get are the same ones app_settings gave it.
        foreach (DB::table('app_settings')->whereNotNull('tenant_id')->get() as $row) {
            DB::table('tenant_settings')
                ->where('tenant_id', $row->tenant_id)
                ->update([
                    'sales_order_deadline_warning_days' => $row->sales_order_deadline_warning_days,
                    'sales_order_auto_invoice' => $row->sales_order_auto_invoice,
                ]);
        }
    }

    public function down(): void
    {
        Schema::table('tenant_settings', function (Blueprint $table) {
            $table->dropColumn([
                'sales_order_deadline_warning_days',
                'sales_order_auto_invoice',
                'sales_order_whatsapp_target',
            ]);
        });
    }
};
