<?php
/**
 * Utility class for generating unique ID numbers.
 *
 * @package    Cloudi7_ID_Card_Generator
 * @subpackage Cloudi7_ID_Card_Generator/includes
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Cloudi7_ICG_ID_Generator
 *
 * Provides a method to generate a unique ID number for new cards.
 */
class Cloudi7_ICG_ID_Generator {

	/**
	 * Generate a unique ID number.
	 *
	 * Format: ID-00001, ID-00002, etc.
	 *
	 * @return string The generated ID number.
	 */
	public static function generate_id() {
		global $wpdb;

		$cloudi7_icg_table_name = $wpdb->prefix . 'cloudi7_icg_cards';

		// Get the latest ID number from the database.
		$cloudi7_icg_cache_key = 'cloudi7_icg_data_last_id_number';
		$cloudi7_icg_last_id_number = wp_cache_get( $cloudi7_icg_cache_key );
		if ( false === $cloudi7_icg_last_id_number ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
			$cloudi7_icg_last_id_number = $wpdb->get_var( "SELECT id_number FROM {$wpdb->prefix}cloudi7_icg_cards ORDER BY id DESC LIMIT 1" );
			wp_cache_set( $cloudi7_icg_cache_key, $cloudi7_icg_last_id_number );
		}

		$cloudi7_icg_next_number = 1;

		if ( $cloudi7_icg_last_id_number ) {
			// Extract the numeric part from the ID (e.g., "00001" from "ID-00001").
			$cloudi7_icg_parts = explode( '-', $cloudi7_icg_last_id_number );
			if ( isset( $cloudi7_icg_parts[1] ) ) {
				$cloudi7_icg_next_number = intval( $cloudi7_icg_parts[1] ) + 1;
			}
		}

		// Format the next number with leading zeros (e.g., ID-00001).
		return 'ID-' . str_pad( $cloudi7_icg_next_number, 5, '0', STR_PAD_LEFT );
	}
}
