<?php

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

/**
 * 1. facility_activities — which sports a facility can host.
 *
 *    Without this the schedule builder offered every group in the academy for
 *    every facility, so a football court listed swimming groups.
 *    A facility with NO rows declared hosts anything (existing behaviour), so
 *    this is additive and nothing breaks until an academy opts in.
 *
 * 2. A default layout for every facility that has none — the reason the grid
 *    silently failed to appear on newly created facilities.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('facility_activities', function (Blueprint $table) {
            $table->id();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('facility_id')->constrained('facilities')->cascadeOnDelete();
            $table->foreignId('activity_id')->constrained('activities')->cascadeOnDelete();
            $table->timestamps();

            $table->unique(['facility_id', 'activity_id'], 'facility_activities_unique');
            $table->index(['academy_id', 'activity_id']);
        });

        $this->backfillDefaultLayouts();
    }

    /**
     * Every facility needs at least one layout or the schedule grid renders empty.
     * A 1x1 grid ("the whole facility") is the honest default — it says the space
     * is not subdivided yet, rather than inventing a subdivision nobody asked for.
     */
    private function backfillDefaultLayouts(): void
    {
        $facilities = DB::table('facilities')
            ->whereNull('deleted_at')
            ->whereNotExists(function ($q) {
                $q->selectRaw('1')->from('space_layouts')
                    ->whereColumn('space_layouts.facility_id', 'facilities.id');
            })
            ->get(['id', 'academy_id', 'created_by', 'operating_start', 'operating_end']);

        foreach ($facilities as $facility) {
            $layoutId = DB::table('space_layouts')->insertGetId([
                'uuid'                  => (string) Str::uuid(),
                'academy_id'            => $facility->academy_id,
                'facility_id'           => $facility->id,
                'name'                  => 'Default layout',
                'name_ar'               => 'التقسيم الافتراضي',
                'layout_type'           => 'grid',
                'layout_config'         => json_encode(['rows' => 1, 'columns' => 1]),
                'is_recurring'          => true,
                'effective_day_of_week' => null,
                'effective_date'        => null,
                'start_time'            => $facility->operating_start ?: '00:00:00',
                'end_time'              => $facility->operating_end ?: '23:59:00',
                'is_active'             => true,
                'sort_order'            => 0,
                'metadata'              => json_encode(['auto_created' => true]),
                'created_by'            => $facility->created_by,
                'created_at'            => now(),
                'updated_at'            => now(),
            ]);

            DB::table('space_segments')->insert([
                'uuid'            => (string) Str::uuid(),
                'space_layout_id' => $layoutId,
                'code'            => 'R1C1',
                'name'            => 'Whole facility',
                'name_ar'         => 'المنشأة كاملة',
                'row_index'       => 1,
                'col_index'       => 1,
                'sort_order'      => 0,
                'created_at'      => now(),
                'updated_at'      => now(),
            ]);
        }
    }

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

        // Only remove layouts this migration created.
        $ids = DB::table('space_layouts')->where('metadata->auto_created', true)->pluck('id');
        DB::table('space_segments')->whereIn('space_layout_id', $ids)->delete();
        DB::table('space_layouts')->whereIn('id', $ids)->delete();
    }
};
