<?php

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

/**
 * Branding lives in four uncoordinated stores today — `academies` columns,
 * `system_settings` (group `branding`), `website_settings` and `media` — with
 * `primary_color` defined three times with three different defaults.
 *
 * Two concrete defects this fixes:
 *
 *  - `academies.address` does not exist. AcademySettings reads and writes it
 *    on every save and Eloquent silently drops it, so an academy's address has
 *    never once been stored. It is also the only place the portal and the
 *    website can get a postal address from.
 *
 *  - `branding.academy_name` is read by the parent layout and by every printed
 *    sheet, and written by nothing — so both fall back to the literal string
 *    "الكابتن" on every tenant. It is seeded here from the academy's own name.
 *
 * `branding_version` is the cache key BrandingService reads a whole profile
 * under. It is bumped on save, which is what makes a cached profile safe to
 * hold forever instead of re-issuing ~16 SELECTs per admin render.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('academies')) {
            return;
        }

        Schema::table('academies', function (Blueprint $table) {
            if (! Schema::hasColumn('academies', 'address')) {
                $table->text('address')->nullable()->after('phone');
            }

            if (! Schema::hasColumn('academies', 'branding_version')) {
                $table->unsignedInteger('branding_version')->default(1)->after('settings');
            }
        });

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

        foreach (DB::table('academies')->get(['id', 'name', 'name_ar']) as $academy) {
            $this->seedSetting($academy->id, 'branding.academy_name', $academy->name_ar ?: $academy->name, 'string');

            // New branding slots the portal, the PWA manifest and the Flutter
            // shell all read. Seeded so a fresh tenant is never unbranded.
            $this->seedSetting($academy->id, 'branding.theme_color', '#2563eb', 'string');
            $this->seedSetting($academy->id, 'branding.theme_mode', 'light', 'string');
            $this->seedSetting($academy->id, 'branding.app_icon', '', 'string');
            $this->seedSetting($academy->id, 'branding.splash_image', '', 'string');
            $this->seedSetting($academy->id, 'branding.app_short_name', $academy->name_ar ?: $academy->name, 'string');
        }
    }

    private function seedSetting(int $academyId, string $key, ?string $value, string $type): void
    {
        $exists = DB::table('system_settings')
            ->where('academy_id', $academyId)
            ->where('key', $key)
            ->exists();

        if ($exists) {
            return;
        }

        DB::table('system_settings')->insert([
            'academy_id' => $academyId,
            'key' => $key,
            'value' => (string) $value,
            'group' => 'branding',
            'type' => $type,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    public function down(): void
    {
        if (Schema::hasTable('academies')) {
            Schema::table('academies', function (Blueprint $table) {
                if (Schema::hasColumn('academies', 'branding_version')) {
                    $table->dropColumn('branding_version');
                }
                if (Schema::hasColumn('academies', 'address')) {
                    $table->dropColumn('address');
                }
            });
        }
    }
};
