<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('device_schedules', function (Blueprint $table) {
            $table->text('schedule_windows')->nullable()->after('repush_hours');
            $table->boolean('use_public_holiday_mode')->default(false)->after('schedule_windows');
            // 0=Sun,1=Mon,...,6=Sat comma-separated public holiday day treatment
            $table->string('public_holiday_treat_as', 10)->default('weekend')->after('use_public_holiday_mode');
        });

        // Migrate existing data to JSON windows format
        DB::table('device_schedules')->get()->each(function ($row) {
            $windows = [
                [
                    'label' => 'Morning Peak',
                    'days'  => [1, 2, 3, 4, 5],
                    'start' => substr($row->weekday_green_start_1 ?? '06:00', 0, 5),
                    'end'   => substr($row->weekday_green_end_1   ?? '10:00', 0, 5),
                ],
                [
                    'label' => 'Evening Peak',
                    'days'  => [1, 2, 3, 4, 5],
                    'start' => substr($row->weekday_green_start_2 ?? '16:00', 0, 5),
                    'end'   => substr($row->weekday_green_end_2   ?? '20:00', 0, 5),
                ],
                [
                    'label' => 'Weekend',
                    'days'  => [0, 6],
                    'start' => substr($row->weekend_green_start ?? '10:00', 0, 5),
                    'end'   => substr($row->weekend_green_end   ?? '22:00', 0, 5),
                ],
            ];

            DB::table('device_schedules')
                ->where('id', $row->id)
                ->update(['schedule_windows' => json_encode($windows)]);
        });
    }

    public function down(): void
    {
        Schema::table('device_schedules', function (Blueprint $table) {
            $table->dropColumn(['schedule_windows', 'use_public_holiday_mode', 'public_holiday_treat_as']);
        });
    }
};
