<?php

namespace Licenzo\Helper;

use Licenzo\Helper\Settings;

if (!defined('ABSPATH')) exit;

class LicenzoKey
{
    private const DEFAULT_CHARACTER_MAP = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    private const DEFAULT_CHUNKS = 4;
    private const DEFAULT_CHUNK_LENGTH = 5;

    public static function generate(): string
    {
        $config = Settings::getLicenseSettings();
        $characterMap = (string) ($config['character_map'] ?? static::DEFAULT_CHARACTER_MAP);
        if ($characterMap === '') {
            $characterMap = static::DEFAULT_CHARACTER_MAP;
        }

        $numberOfChunks = max(1, (int) ($config['number_of_chunks'] ?? static::DEFAULT_CHUNKS));
        $chunkLength = max(1, (int) ($config['chunk_length'] ?? static::DEFAULT_CHUNK_LENGTH));
        $separator = (string) ($config['separator'] ?? '-');
        $prefix = (string) ($config['prefix'] ?? '');
        $suffix = (string) ($config['suffix'] ?? '');

        $chunks = [];
        for ($i = 0; $i < $numberOfChunks; $i++) {
            $chunk = '';
            for ($j = 0; $j < $chunkLength; $j++) {
                $chunk .= $characterMap[random_int(0, strlen($characterMap) - 1)];
            }
            $chunks[] = $chunk;
        }

        $key = implode($separator, $chunks);

        if ($prefix !== '') {
            $key = $prefix . $separator . $key;
        }
        if ($suffix !== '') {
            $key .= $separator . $suffix;
        }

        return $key;
    }
}
