<?php


use App\Models\ProjectReport;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('project_reports', function (Blueprint $table) {
            $table->date('end_date')->nullable();
            $table->integer('offset')->default(7);
        });
        ProjectReport::all()->each(function (ProjectReport $project_report) {
            $end_date = Carbon::parse(sprintf('%s-W%02d',$project_report->year,$project_report->week))->addDay(Carbon::THURSDAY);
            $project_report->update(['end_date' => $end_date]);
        });
        Schema::table('project_reports', function (Blueprint $table) {
            $table->dropColumn('week');
            $table->dropColumn('year');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('project_reports', function (Blueprint $table) {
            // Add back year and week columns
            $table->integer('year');
            $table->integer('week');
        });

        // Extract year and week from end_date (assuming logic applied in up() is reversible)
        ProjectReport::all()->each(function (ProjectReport $project_report) {
            if (!$project_report->end_date) {
                return; // Skip if end_date is null
            }
            $project_report->update(['year' => $project_report->end_date->format('Y'), 'week' => $project_report->end_date->format('W')]);
        });

        Schema::table('project_reports', function (Blueprint $table) {
            // Drop end_date and offset columns
            $table->dropColumn('end_date');
            $table->dropColumn('offset');
        });
    }

};
