<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;

Route::get('/update', function () { 
    $files = DB::table('files')->get();
    foreach ($files as $file) {
        $shortKey = shortKeyFiles('files', 'short_key', 6);
        DB::table('files')
            ->where('id', $file->id)
            ->update(['short_key' => $shortKey]);
    }
    echo 'Update is OK.';
});

function shortKeyFiles(
    $dbTable, 
    $dbColumn,
    $length = 6
): mixed {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz'
        . 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersNumber = strlen($characters);
    $codeLength = $length;


    $code = '';
    while (strlen($code) < $codeLength) {
        $position = rand(0, $charactersNumber - 1);
        $character = $characters[$position];
        $code = $code.$character;
    }

    if (DB::table($dbTable)->where($dbColumn, $code)->exists()) {
        return uniqueCode($dbTable, $dbColumn);
    }

    return $code;
}