<?php
// generate_prime_id.php
header('Content-Type: application/json');

// Initialize JSON file if it doesn't exist
if (!file_exists('data/students.json')) {
    file_put_contents('data/students.json', json_encode([]));
}

// Get existing students
$students = json_decode(file_get_contents('data/students.json'), true);

// Function to generate a unique PRIME ID
function generatePrimeId($existingStudents) {
    $existingIds = [];
    foreach ($existingStudents as $student) {
        $existingIds[] = $student['prime_id'];
    }
    
    $prefix = "PRIME";
    $maxAttempts = 1000;
    $attempt = 0;
    
    do {
        $number = str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        $newId = $prefix . $number;
        $attempt++;
        
        if ($attempt > $maxAttempts) {
            return null; // Safety fallback
        }
    } while (in_array($newId, $existingIds));
    
    return $newId;
}

// Generate the ID
$primeId = generatePrimeId($students);

if ($primeId) {
    echo json_encode(['success' => true, 'prime_id' => $primeId]);
} else {
    echo json_encode(['success' => false, 'message' => 'Could not generate a unique PRIME ID']);
}
?>