<?php
// filepath: c:\stylescore2025\htdocs\v2\admin\ajax_generate_bib.php
include '../includes/auth.php';
include '../includes/db.php';

header('Content-Type: application/json');

try {
    // Get the highest BIB number and add 1
    $stmt = $pdo->query("SELECT MAX(CAST(bib AS UNSIGNED)) as max_bib FROM participants WHERE bib REGEXP '^[0-9]+$'");
    $result = $stmt->fetch();
    
    $next_bib = ($result['max_bib'] ?? 0) + 1;
    
    // Format with leading zeros if needed (e.g., 001, 002, etc.)
    $formatted_bib = str_pad($next_bib, 3, '0', STR_PAD_LEFT);
    
    echo json_encode([
        'success' => true,
        'next_bib' => $formatted_bib
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>