<?php

use App\Key;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

if (!function_exists('gen_api_key')) {
    function gen_api_key()
    {
        $key = bin2hex(openssl_random_pseudo_bytes(10));
        while (Key::all()->where('api_key', '=', $key)->count() > 0) {
            $key = bin2hex(openssl_random_pseudo_bytes(10));
        }
        return $key;
    }
}


if (!function_exists('gen_token')) {
    function gen_token($type_token)
    {
        $token = Str::random(80);
        while (DB::table('login_history')->where($type_token, '=', $token)->count() > 0) {
            $token = Str::random(80);
        }
        return $token;
    }
}


if (!function_exists('gen_client_key')) {
    function gen_client_key()
    {
        $key = bin2hex(openssl_random_pseudo_bytes(10));
        while (DB::table('customer_software')->where("client_key", $key)->count() > 0) {
            $key = bin2hex(openssl_random_pseudo_bytes(10));
        }
        return $key;
    }
}


if (!function_exists('gen_bd_name')) {
    function gen_bd_name($dbname)
    {
        $dbname = strtolower(str_replace(' ', '', $dbname));
        while (DB::table('customer_software')->where("bd", $dbname)->count() > 0) {
            $dbname .= mt_rand(0, 1000);
        }
        return $dbname;
    }
}

if (!function_exists('gen_disk_name')) {
    function gen_disk_name($disk)
    {
        $disk = strtolower(str_replace(' ', '', $disk));
        while (DB::table('customer_software')->where("folder_disk", $disk)->count() > 0) {
            $disk .= mt_rand(0, 1000);
        }
        return $disk;
    }
}

