<?php

namespace Daniv04\HaciendaPackage\Traits;

trait GenerateSecurityCode
{
    /**
     * Generate a security code of 8 digits based on a hash of the provided seed or unique data
     *
     * @param string|null $seed Optional seed to generate the hash (e.g., consecutive, timestamp)
     * @return string 8-digit code
     */
    public function generateSecurityCode(?string $seed = null): string
    {

        if ($seed === null) {
            $seed = uniqid(more_entropy: true) . microtime() . random_bytes(16);
        }
        
        $hash = hash('sha256', $seed);
        
        $numbers = preg_replace('/[^0-9]/', '', $hash);
        
        $code = substr($numbers, 0, 8);
        
        if (strlen($code) < 8) {
            $code = str_pad($code, 8, (string)random_int(0, 9), STR_PAD_RIGHT);
        }
        return $code;
    }

    

}
