<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('simbhpjenis', function (Blueprint $table) {
            if (!Schema::hasColumn('simbhpjenis', 'barcode_besar')) {
                $table->string('barcode_besar', 20)->nullable()->after('kodejenis');
            }
            if (!Schema::hasColumn('simbhpjenis', 'barcode_kecil')) {
                $table->string('barcode_kecil', 20)->nullable()->after('barcode_besar');
            }
        });

        if (!Schema::hasColumn('simbhpjenis', 'barcode_besar')) {
            return;
        }

        DB::table('simbhpjenis')
            ->orderBy('id', 'ASC')
            ->chunkById(200, function ($rows) {
                foreach ($rows as $row) {
                    $id = (int) ($row->id ?? 0);
                    if ($id <= 0) {
                        continue;
                    }

                    $idPart = str_pad((string) $id, 8, '0', STR_PAD_LEFT);
                    $barcodeBesar = '91' . $idPart . '1';

                    $existingBesar = isset($row->barcode_besar) ? trim((string) $row->barcode_besar) : '';
                    $existingKecil = isset($row->barcode_kecil) ? trim((string) $row->barcode_kecil) : '';

                    $satuanKecil = isset($row->satuan_kecil) ? trim((string) $row->satuan_kecil) : '';
                    $konversi = (int) ($row->konversi_kecil ?? 1);
                    if ($konversi <= 0) {
                        $konversi = 1;
                    }
                    $hasBreakdown = ($satuanKecil !== '' && $konversi > 1);

                    $update = [];
                    if ($existingBesar === '') {
                        $update['barcode_besar'] = $barcodeBesar;
                    }

                    if ($hasBreakdown) {
                        $barcodeKecil = '91' . $idPart . '2';
                        if ($existingKecil === '') {
                            $update['barcode_kecil'] = $barcodeKecil;
                        }
                    }

                    if (count($update) > 0) {
                        DB::table('simbhpjenis')->where('id', $id)->update($update);
                    }
                }
            }, 'id');
    }

    public function down(): void
    {
        Schema::table('simbhpjenis', function (Blueprint $table) {
            if (Schema::hasColumn('simbhpjenis', 'barcode_kecil')) {
                $table->dropColumn('barcode_kecil');
            }
            if (Schema::hasColumn('simbhpjenis', 'barcode_besar')) {
                $table->dropColumn('barcode_besar');
            }
        });
    }
};

