<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('products', function (Blueprint $table) {
            // First drop the existing unique constraint on name if it exists.
            // Based on previous migrations, it might be named products_name_unique.
            $table->dropUnique('products_name_unique');
            
            // Re-add branch column
            $table->string('branch')->default('Cabang 1')->after('image');
        });

        // Set all existing products to Cabang 1
        \Illuminate\Support\Facades\DB::table('products')->update(['branch' => 'Cabang 1']);

        Schema::table('products', function (Blueprint $table) {
            // Add composite unique constraint for name and branch
            $table->unique(['name', 'branch']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('products', function (Blueprint $table) {
            $table->dropUnique(['name', 'branch']);
            $table->dropColumn('branch');
            $table->unique('name', 'products_name_unique');
        });
    }
};
