<?php
/**
 * ERENQVP_Barcode — optional internal SKU/barcode generation.
 *
 * Generalized from the original hard-coded "ALR…" prefix: the prefix is configurable
 * and generation is opt-in (many stores don't use barcodes at all).
 *
 * @package ErenLabs\QuickVariableProducts
 */

defined( 'ABSPATH' ) || exit;

class ERENQVP_Barcode {

	const OPT_PREFIX = 'erenqvp_sku_prefix';

	/**
	 * Configured SKU prefix (sanitized, uppercase, alnum). Empty = auto-SKU disabled.
	 *
	 * @return string
	 */
	public static function prefix() {
		$p = (string) get_option( self::OPT_PREFIX, '' );
		$p = strtoupper( preg_replace( '/[^A-Za-z0-9]/', '', $p ) );
		return substr( $p, 0, 8 );
	}

	/**
	 * Generate a unique internal code: PREFIX + base36(random). Falls back to a "ERENQVP" prefix
	 * when none is configured, so the value is still recognizably ours.
	 *
	 * @return string
	 */
	public static function generate() {
		$prefix = self::prefix();
		if ( '' === $prefix ) {
			$prefix = 'ERENQVP';
		}
		$code  = '';
		$tries = 0;
		do {
			$code = $prefix . strtoupper( base_convert( (string) wp_rand( 1000000, 99999999 ), 10, 36 ) );
		} while ( wc_get_product_id_by_sku( $code ) && ++$tries < 8 );
		return $code;
	}
}
