<?php
/**
 * Event ID Generator — Cache-safe, collision-proof 64-bit event IDs.
 *
 * Generates unique event IDs for server-side events.
 * Browser-side event IDs are generated via JavaScript crypto.getRandomValues().
 *
 * Format: evt_{16-char hex}_{13-digit timestamp}
 * Entropy: 64-bit (random_bytes(8)) → collision probability ≈ 0
 *
 * @package CapiFlow
 */

namespace CapiFlow\Core;

defined('ABSPATH') || exit;

class Event_ID_Generator
{

    /**
     * Generate a unique event ID (server-side).
     *
     * Used for: Purchase, InitiateCheckout, AddPaymentInfo,
     * Negative events, DeliveryConfirmed.
     *
     * @return string Unique event ID in format: evt_{hex}_{timestamp}
     */
    public static function generate()
    {
        $random = bin2hex(random_bytes(8)); // 64-bit = 16 hex chars.
        $timestamp = substr((string) (microtime(true) * 1000), 0, 13);

        return 'evt_' . $random . '_' . $timestamp;
    }

    /**
     * Validate an event ID format.
     *
     * Accepts both server-generated (evt_...) and client-generated (browser crypto) IDs.
     *
     * @param string $event_id Event ID to validate.
     * @return bool True if valid format.
     */
    public static function validate($event_id)
    {
        if (empty($event_id) || !is_string($event_id)) {
            return false;
        }

        // Server-generated: evt_{16 hex}_{13 digits}
        // Client-generated: cevt_{16 hex}_{13 digits}
        if (preg_match('/^c?evt_[a-f0-9]{12,16}_\d{13}$/', $event_id)) {
            return true;
        }

        // Client-generated: any alphanumeric string 10-64 chars (browser crypto).
        if (preg_match('/^[a-zA-Z0-9_-]{10,64}$/', $event_id)) {
            return true;
        }

        return false;
    }
}
