<?php

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

// ══════════════════════════════════════════════════════════════════
//  InPractice — Survey Tables
//
//  Members can create surveys and circulate them to other
//  members for feedback, research, or polling.
//
//  Always optional — members receive a notification but
//  can skip any survey without consequence.
//
//  Question types:
//    multiple_choice  → pick one answer from a list
//    multi_select     → pick one or more answers
//    rating           → 1-5 star or 1-10 scale
//    text             → open written response
//    yes_no           → simple yes / no
//
//  Audience:
//    all   → every member on the platform
//    hub   → members of a specific hub only
//    custom → selected individual members
// ══════════════════════════════════════════════════════════════════

return new class extends Migration
{
    public function up(): void
    {
        // ── Surveys ────────────────────────────────────────────
        Schema::create('surveys', function (Blueprint $table) {
            $table->id();

            $table->foreignId('created_by')
                  ->constrained('users')
                  ->cascadeOnDelete();

            // ── Survey Info ───────────────────────────────────
            $table->string('title_en');
            $table->string('title_ar')->nullable();
            $table->text('description_en')->nullable();
            $table->text('description_ar')->nullable();
            $table->string('language', 2)->default('en');

            // ── Audience ──────────────────────────────────────
            $table->enum('audience', ['all', 'hub', 'custom'])->default('all');
            $table->foreignId('hub_id')
                  ->nullable()
                  ->constrained('hubs')
                  ->nullOnDelete();                           // if audience = hub

            // ── Settings ──────────────────────────────────────
            $table->boolean('anonymous_responses')->default(true);   // hide who answered
            $table->boolean('show_results_to_members')->default(false); // share results publicly

            // ── Timing ────────────────────────────────────────
            $table->timestamp('closes_at')->nullable();      // optional expiry date

            // ── Status ────────────────────────────────────────
            $table->enum('status', [
                'draft',
                'active',            // live and accepting responses
                'closed',            // no longer accepting responses
            ])->default('draft');

            // ── Response Counter ──────────────────────────────
            $table->unsignedInteger('response_count')->default(0);

            $table->timestamps();
        });

        // ── Survey Questions ───────────────────────────────────
        Schema::create('survey_questions', function (Blueprint $table) {
            $table->id();

            $table->foreignId('survey_id')
                  ->constrained('surveys')
                  ->cascadeOnDelete();

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

            // ── Question Type ─────────────────────────────────
            $table->enum('type', [
                'multiple_choice',   // pick one from a list
                'multi_select',      // pick multiple from a list
                'rating',            // 1-5 or 1-10 scale
                'text',              // open text response
                'yes_no',            // yes or no
            ]);

            // ── Options (for multiple_choice and multi_select) ─
            $table->json('options_en')->nullable();          // array of answer choices
            $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->unsignedTinyInteger('sort_order')->default(0);

            $table->timestamps();
        });

        // ── Survey Responses ───────────────────────────────────
        Schema::create('survey_responses', function (Blueprint $table) {
            $table->id();

            $table->foreignId('survey_id')
                  ->constrained('surveys')
                  ->cascadeOnDelete();

            // Nullable if anonymous responses enabled
            $table->foreignId('user_id')
                  ->nullable()
                  ->constrained('users')
                  ->nullOnDelete();

            // ── All answers stored as JSON ─────────────────────
            // Format: { "question_id": "answer", ... }
            $table->json('answers');

            $table->timestamp('submitted_at')->useCurrent();

            $table->timestamps();
        });

        // ── Survey Custom Audience ─────────────────────────────
        // When audience = custom, specific users are targeted here
        Schema::create('survey_audience', function (Blueprint $table) {
            $table->id();
            $table->foreignId('survey_id')
                  ->constrained('surveys')
                  ->cascadeOnDelete();
            $table->foreignId('user_id')
                  ->constrained('users')
                  ->cascadeOnDelete();
            $table->boolean('has_responded')->default(false);
            $table->unique(['survey_id', 'user_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('survey_audience');
        Schema::dropIfExists('survey_responses');
        Schema::dropIfExists('survey_questions');
        Schema::dropIfExists('surveys');
    }
};
