<?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('businesses', function (Blueprint $table): void {
            $table->string('phone_country_code', 4)->default('255')->after('country');
        });

        $countryCode = preg_replace('/\D+/', '', (string) (DB::table('businesses')->where('id', 1)->value('phone_country_code') ?: '255')) ?: '255';

        $normalize = static function (mixed $value) use ($countryCode): mixed {
            if ($value === null || trim((string) $value) === '') {
                return $value;
            }

            $digits = preg_replace('/\D+/', '', (string) $value) ?? '';

            if (str_starts_with($digits, $countryCode)) {
                $local = substr($digits, strlen($countryCode));
                return preg_match('/^[67]\d{8}$/', $local) === 1 ? $countryCode.$local : $value;
            }

            if (preg_match('/^0[67]\d{8}$/', $digits) === 1) {
                return $countryCode.substr($digits, 1);
            }

            if (preg_match('/^[67]\d{8}$/', $digits) === 1) {
                return $countryCode.$digits;
            }

            return $value;
        };

        foreach ([
            'businesses' => ['phone', 'phone_alt'],
            'branches' => ['phone'],
            'users' => ['phone'],
            'customers' => ['phone', 'alternative_phone'],
            'next_of_kin' => ['phone'],
            'guarantors' => ['phone'],
        ] as $table => $columns) {
            if (! Schema::hasTable($table)) {
                continue;
            }

            foreach ($columns as $column) {
                if (! Schema::hasColumn($table, $column)) {
                    continue;
                }

                DB::table($table)
                    ->select('id', $column)
                    ->whereNotNull($column)
                    ->orderBy('id')
                    ->chunkById(250, function ($rows) use ($table, $column, $normalize): void {
                        foreach ($rows as $row) {
                            $normalized = $normalize($row->{$column});
                            if ($normalized !== $row->{$column}) {
                                DB::table($table)->where('id', $row->id)->update([$column => $normalized]);
                            }
                        }
                    });
            }
        }
    }

    public function down(): void
    {
        Schema::table('businesses', function (Blueprint $table): void {
            $table->dropColumn('phone_country_code');
        });
    }
};
