<?php

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

// ══════════════════════════════════════════════════════════════════
//  InPractice — Survey Upgrade + Question Bank
//
//  What this migration does:
//    1. Upgrades the existing `surveys` table — adds link_token
//       so members can generate a public shareable link.
//    2. Upgrades `survey_responses` — adds respondent demographics
//       (name, title, company, gender, age, ip_address) for
//       public / external respondents who are not members.
//    3. Creates `question_bank_sections` — Finance, Marketing,
//       Sales, General. Seeded, not user-created.
//    4. Creates `question_bank_items` — reusable bilingual questions
//       that members can pull into their surveys.
//
//  Note: `survey_questions` stores options as JSON columns
//  (options_en / options_ar) — no separate options table needed.
// ══════════════════════════════════════════════════════════════════

return new class extends Migration
{
    public function up(): void
    {
        // ── 1. Upgrade surveys table ───────────────────────────
        Schema::table('surveys', function (Blueprint $table) {
            // Link token for public shareable URL
            // null = draft / members-only, set = public link generated
            $table->string('link_token', 64)
                  ->unique()
                  ->nullable()
                  ->after('response_count');
        });

        // ── 2. Upgrade survey_responses table ─────────────────
        // These columns are filled by public (non-member) respondents.
        // Members responding inside the platform have user_id set instead.
        Schema::table('survey_responses', function (Blueprint $table) {
            $table->string('respondent_name')->nullable()->after('user_id');
            $table->string('respondent_title')->nullable()->after('respondent_name');
            $table->string('respondent_company')->nullable()->after('respondent_title');
            $table->enum('respondent_gender', ['male', 'female', 'prefer_not_to_say'])
                  ->nullable()
                  ->after('respondent_company');
            $table->unsignedTinyInteger('respondent_age')->nullable()->after('respondent_gender');
            $table->string('ip_address', 45)->nullable()->after('respondent_age');
        });

        // ── 3. Question bank sections ──────────────────────────
        // Seeded: Finance, Marketing, Sales, General
        // Members cannot create sections — platform-defined categories.
        Schema::create('question_bank_sections', function (Blueprint $table) {
            $table->id();
            $table->string('name_en');
            $table->string('name_ar')->nullable();
            $table->string('color', 20)->default('teal'); // teal, blue, coral, gray
            $table->unsignedTinyInteger('sort_order')->default(0);
            $table->timestamps();
        });

        // ── 4. Question bank items ─────────────────────────────
        // Bilingual reusable questions. Members add these to surveys
        // instead of writing from scratch. usage_count drives ordering.
        Schema::create('question_bank_items', function (Blueprint $table) {
            $table->id();

            $table->foreignId('question_bank_section_id')
                  ->nullable()
                  ->constrained('question_bank_sections')
                  ->nullOnDelete();

            // ── Question content ───────────────────────────────
            $table->text('question_en');
            $table->text('question_ar')->nullable();

            // ── Question type ──────────────────────────────────
            $table->enum('type', [
                'multiple_choice',
                'multi_select',
                'rating',
                'text',
                'yes_no',
            ]);

            // ── Options (for multiple_choice, multi_select) ────
            $table->json('options_en')->nullable();
            $table->json('options_ar')->nullable();

            // ── Rating config ──────────────────────────────────
            $table->unsignedTinyInteger('rating_min')->default(1);
            $table->unsignedTinyInteger('rating_max')->default(5);

            // ── Settings ──────────────────────────────────────
            $table->boolean('is_required')->default(true);
            $table->string('placeholder_en')->nullable();
            $table->string('placeholder_ar')->nullable();

            // ── Popularity ────────────────────────────────────
            $table->unsignedInteger('usage_count')->default(0);

            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('question_bank_items');
        Schema::dropIfExists('question_bank_sections');

        Schema::table('survey_responses', function (Blueprint $table) {
            $table->dropColumn([
                'respondent_name',
                'respondent_title',
                'respondent_company',
                'respondent_gender',
                'respondent_age',
                'ip_address',
            ]);
        });

        Schema::table('surveys', function (Blueprint $table) {
            $table->dropColumn('link_token');
        });
    }
};
