<?php

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

/**
 * Website Builder v3 — the page + block tree.
 *
 * Additive only. `website_sections` is left untouched so the legacy renderer
 * keeps working for every already-deployed tenant; the entrypoint runs
 * `migrate --force` on every container start, so nothing here may be destructive.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('website_pages')) {
            Schema::create('website_pages', function (Blueprint $table) {
                $table->id();
                $table->foreignId('academy_id')->constrained('academies');
                $table->uuid('uuid')->unique();

                $table->string('slug', 160);
                $table->string('title')->nullable();          // Arabic (default locale)
                $table->string('title_en')->nullable();

                // SEO
                $table->string('meta_title', 180)->nullable();
                $table->string('meta_title_en', 180)->nullable();
                $table->string('meta_description', 320)->nullable();
                $table->string('meta_description_en', 320)->nullable();
                $table->string('og_image_path', 500)->nullable();
                $table->boolean('noindex')->default(false);

                $table->string('layout', 30)->default('default');
                $table->boolean('is_homepage')->default(false);
                $table->boolean('is_published')->default(false);
                $table->timestamp('published_at')->nullable();
                $table->unsignedSmallInteger('sort_order')->default(0);

                $table->jsonb('settings')->default('{}');

                $table->foreignId('created_by')->nullable()->constrained('users');
                $table->timestamps();
                $table->softDeletes();

                $table->unique(['academy_id', 'slug']);
                $table->index(['academy_id', 'is_published']);
                $table->index(['academy_id', 'sort_order']);
            });

            DB::statement("ALTER TABLE website_pages ADD CONSTRAINT website_pages_layout_check
                CHECK (layout IN ('default', 'full_width', 'narrow', 'blank', 'landing'))");

            // Exactly one homepage per academy — but unlimited non-homepages.
            DB::statement('CREATE UNIQUE INDEX website_pages_single_homepage
                ON website_pages (academy_id) WHERE is_homepage AND deleted_at IS NULL');
        }

        if (! Schema::hasTable('website_blocks')) {
            Schema::create('website_blocks', function (Blueprint $table) {
                $table->id();
                $table->foreignId('academy_id')->constrained('academies');
                $table->uuid('uuid')->unique();

                // Null page_id = a reusable/global block (navbar, footer, popup).
                $table->foreignId('website_page_id')->nullable()
                    ->constrained('website_pages')->cascadeOnDelete();
                $table->foreignId('parent_id')->nullable()
                    ->constrained('website_blocks')->cascadeOnDelete();

                $table->string('slot', 40)->default('default');
                $table->string('type', 50);
                $table->string('variant', 50)->default('default');

                $table->unsignedSmallInteger('sort_order')->default(0);
                $table->boolean('is_enabled')->default(true);

                // Content fields. Bilingual values live inline as {"ar": "...", "en": "..."}.
                $table->jsonb('data')->default('{}');
                // Presentation: background, padding, animation, visibility, custom classes.
                $table->jsonb('style')->default('{}');

                $table->timestamps();

                $table->index(['academy_id', 'website_page_id', 'sort_order']);
                $table->index(['academy_id', 'parent_id', 'sort_order']);
                $table->index(['academy_id', 'type']);
            });

            // A block belongs to a page OR to a parent — never floating with neither.
            DB::statement('ALTER TABLE website_blocks ADD CONSTRAINT website_blocks_parent_or_page_check
                CHECK (website_page_id IS NOT NULL OR parent_id IS NOT NULL)');
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('website_blocks');
        Schema::dropIfExists('website_pages');
    }
};
