<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('websites', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('company_id')->unsigned()->nullable()->default(null);
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade')->onUpdate('cascade');
            $table->bigInteger('website_category_id')->unsigned()->nullable();
            $table->foreign('website_category_id')->references('id')->on('website_categories')->onDelete('set null')->onUpdate('cascade');
            $table->string('name');
            $table->string('slug');

            // Theme Configuration
            $table->string('theme_name')->nullable()->default('tailwind_theme');
            $table->string('theme_primary_color')->nullable()->default('#2563eb');
            $table->string('theme_secondary_color')->nullable();
            $table->enum('theme_mode', ['light', 'dark'])->default('light');

            $table->boolean('is_favourite')->default(false);

            // When true, this website will be accessible at root URL "/" (non-saas only)
            // Only one website per company can be primary
            $table->boolean('is_primary')->default(false);

            $table->text('custom_css')->nullable();
            $table->text('custom_js')->nullable();

            $table->boolean('use_same_header_across_all_pages')->default(true);
            $table->boolean('use_same_footer_across_all_pages')->default(true);

            $table->timestamps();
        });

        // Create default website for each company
        $companies = DB::table('companies')->get();
        foreach ($companies as $company) {
            DB::table('websites')->insert([
                'company_id' => $company->id,
                'website_category_id' => null,
                'name' => 'Webifly AI',
                'slug' => 'webifly',
                'theme_name' => 'tailwind_theme',
                'theme_primary_color' => '#2563eb',
                'theme_secondary_color' => null,
                'theme_mode' => 'light',
                'is_favourite' => false,
                'is_primary' => false,
                'custom_css' => null,
                'custom_js' => null,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('websites');
    }
};
