<?php
/**
 * UUID Generator for Idempotency
 * Prevents duplicate entries from double-clicks or network retries.
 */

class UUID {
    
    /**
     * Generate a v4 UUID
     */
    public static function generate(): string {
        $data = random_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Version 4
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Variant

        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }

    /**
     * Check if a UUID already exists in a table (Idempotency Guard)
     * Returns the existing record ID if found, null otherwise.
     */
    public static function checkIdempotency(PDO $db, string $table, string $uuid): ?int {
        if (empty($uuid)) return null;
        
        $stmt = $db->prepare("SELECT id FROM `{$table}` WHERE uuid = ? LIMIT 1");
        $stmt->execute([$uuid]);
        $row = $stmt->fetch();
        
        return $row ? (int)$row['id'] : null;
    }
}
