<?php

use App\Modules\BaseModule;
use App\Modules\Module;
use App\Modules\ModuleContract;
use App\Modules\ModuleRepository;
use App\Modules\TurkmenNumberFormatter\Repositories\TurkmenNumberFormatter;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * Application locales
 *
 * @return array<array-key, mixed>
 */
function appLocales(): array
{
    return config()->array('app.locales');
}

/**
 * Return modular repo
 */
function modular(): ModuleRepository
{
    return app(ModuleRepository::class);
}

/**
 * Modules directory path
 */
function modules_path(string $path = ''): string
{
    return modular()->path().'/'.$path;
}

/**
 * Get module
 */
function module(string $moduleName): ModuleContract
{
    return modular()->module($moduleName);
}

/**
 * Modules
 *
 * @return Collection<array-key, BaseModule>
 */
function modules(bool $withDisabled = false): Collection
{
    return $withDisabled ? modular()->allModules() : modular()->modules();
}

/**
 * Empty module
 */
function emptyModule(): ModuleContract
{
    return modular()->emptyModule();
}

/**
 * Temprory cache for single request
 *
 * @return ($key is '' ? CacheRepository : mixed)
 */
function temp_cache(string $key = ''): mixed
{
    $tempCache = cache()->driver('array');

    return ($key === '') ? $tempCache : $tempCache->get($key);
}

/**
 * Log
 */
function logDB(): void
{
    if (! app()->isLocal()) {
        return;
    }

    DB::listen(function ($query) {
        Log::info($query->sql, $query->bindings, $query->time);
    });
}

/**
 * Get latest number
 */
function getLatestNumber(string $tableName = 'incoming_letters', string $column = 'number'): int
{
    /** @var null|object{max_number: string} $data */
    $data = DB::table($tableName)->select(DB::raw("MAX(CAST(REGEXP_REPLACE({$column}, '[^0-9]', '') AS UNSIGNED)) AS max_number"))->first();

    return $data ? intval($data->max_number) : 0;
}

/**
 * Written format of money in turkmen
 */
function moneyFormatInTurkmenLetter(int|float|string $money): string
{
    return TurkmenNumberFormatter::format(floatval($money));
}
