<?php

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

/**
 * SIFA P3-T7 (scheduling upgrade) — additive schedule-pattern columns on the
 * existing clc_doctor_schedules table (spec §7 provider_schedule.patterns).
 *
 * All additive + nullable / safe-defaulted so every existing schedule row and
 * the legacy slot computation keep working untouched. Guarded with
 * Schema::hasColumn so the migration is safe to re-run.
 *
 *   effective_from / effective_to  - date window the pattern is valid within
 *                                    (null = no bound). The availability engine
 *                                    skips a schedule outside its window.
 *   max_per_slot                   - capacity per slot (spec max_patients_per_slot)
 *   overbooking_allowed            - allow booking beyond max_per_slot
 *   overbooking_max                - extra bookings permitted when overbooking
 *   break_from / break_to          - a single break period (e.g. lunch) subtracted
 *                                    from the working window
 *   location_id                    - FK to business_locations (branch scoping)
 */
class AddPatternColumnsToClcDoctorSchedules extends Migration
{
    public function up()
    {
        Schema::table('clc_doctor_schedules', function (Blueprint $table) {
            if (!Schema::hasColumn('clc_doctor_schedules', 'effective_from')) {
                $table->date('effective_from')->nullable()->after('day_of_week');
            }
            if (!Schema::hasColumn('clc_doctor_schedules', 'effective_to')) {
                $table->date('effective_to')->nullable()->after('effective_from');
            }
            if (!Schema::hasColumn('clc_doctor_schedules', 'max_per_slot')) {
                $table->unsignedSmallInteger('max_per_slot')->default(1)->after('slot_duration_minutes');
            }
            if (!Schema::hasColumn('clc_doctor_schedules', 'overbooking_allowed')) {
                $table->boolean('overbooking_allowed')->default(false)->after('max_per_slot');
            }
            if (!Schema::hasColumn('clc_doctor_schedules', 'overbooking_max')) {
                $table->unsignedSmallInteger('overbooking_max')->default(0)->after('overbooking_allowed');
            }
            if (!Schema::hasColumn('clc_doctor_schedules', 'break_from')) {
                $table->time('break_from')->nullable()->after('overbooking_max');
            }
            if (!Schema::hasColumn('clc_doctor_schedules', 'break_to')) {
                $table->time('break_to')->nullable()->after('break_from');
            }
            if (!Schema::hasColumn('clc_doctor_schedules', 'location_id')) {
                $table->unsignedInteger('location_id')->nullable()->after('department_id');
            }
        });

        // Soft FK to business_locations — only when the referenced table exists
        // and the column was just added (keeps this safe across install orders).
        if (Schema::hasColumn('clc_doctor_schedules', 'location_id')
            && Schema::hasTable('business_locations')) {
            try {
                Schema::table('clc_doctor_schedules', function (Blueprint $table) {
                    $table->foreign('location_id')
                          ->references('id')->on('business_locations')
                          ->nullOnDelete();
                });
            } catch (\Throwable $e) {
                // FK may already exist on re-run — ignore.
                \Log::info('clc_doctor_schedules.location_id FK skipped: ' . $e->getMessage());
            }
        }
    }

    public function down()
    {
        if (Schema::hasColumn('clc_doctor_schedules', 'location_id')) {
            try {
                Schema::table('clc_doctor_schedules', function (Blueprint $table) {
                    $table->dropForeign(['location_id']);
                });
            } catch (\Throwable $e) {
                // ignore
            }
        }

        foreach ([
            'effective_from', 'effective_to', 'max_per_slot', 'overbooking_allowed',
            'overbooking_max', 'break_from', 'break_to', 'location_id',
        ] as $col) {
            if (Schema::hasColumn('clc_doctor_schedules', $col)) {
                Schema::table('clc_doctor_schedules', function (Blueprint $table) use ($col) {
                    $table->dropColumn($col);
                });
            }
        }
    }
}
