<form action="{{ route('admin.api.key.store') }}" method="post" enctype="multipart/form-data" class="form-validate form">
    @csrf
    <div class="mb-2">
        <label for="title" class="form-label"> {{ __('title') }} <span class="text-danger">*</span> </label>
        <input type="text" class="form-control rounded-2" id="title" name="title" value="{{ old('title') }}"
            placeholder="{{ __('api_title') }}">
        <div class="nk-block-des text-danger">
            <p class="error">{{ $errors->first('title') }}</p>
        </div>
    </div>
    <!-- API Key Field -->
    <div class="mb-2">
        <label for="api_key" class="form-label"> {{ __('api_key') }} <span class="text-danger">*</span> </label>
        <div class="input-group">
            <input type="text" class="form-control rounded-start" id="api_key" name="api_key"
                value="{{ old('api_key', Str::random(16)) }}" readonly>
            <button type="button" class="btn btn-outline-secondary" id="generateKey"> <i
                    class="las la-redo-alt"></i></button>
        </div>
        <div class="nk-block-des text-danger">
            <p class="error">{{ $errors->first('api_key') }}</p>
        </div>
    </div>

    <button type="submit" class="btn sg-btn-primary">{{ __('submit') }}</button>
    @include('layouts.loading_button', ['class' => 'btn sg-btn-primary'])
</form>
<script>
    "use strict";

    document.getElementById('generateKey').addEventListener('click', function() {
        const length = 16;
        const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        let randomKey = "";
        const randomValues = crypto.getRandomValues(new Uint32Array(length));

        for (let i = 0; i < length; i++) {
            randomKey += charset[randomValues[i] % charset.length];
        }

        document.getElementById('api_key').value = randomKey;
    });
</script>
