<?php
// Load configuration with fallback support
require_once __DIR__ . '/config_manager.php';

// Database configuration from configuration manager
define('DB_HOST', getRequiredConfig('DB_HOST'));
define('DB_NAME', getRequiredConfig('DB_NAME'));
define('DB_USER', getRequiredConfig('DB_USER'));
define('DB_PASS', getRequiredConfig('DB_PASS'));

// Database connection function
function getDBConnection() {
    try {
        $pdo = new PDO(
            "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false
            ]
        );
        return $pdo;
    } catch (PDOException $e) {
        error_log("Database connection failed: " . $e->getMessage());
        throw new Exception("Database connection failed");
    }
}

// Generate unique registration number
function generateRegistrationNumber() {
    $pdo = getDBConnection();
    $maxAttempts = 10;
    $attempt = 0;
    
    do {
        // Generate 6-character random alphanumeric string
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $random = '';
        for ($i = 0; $i < 6; $i++) {
            $random .= $characters[rand(0, strlen($characters) - 1)];
        }
        $registrationNumber = "XC25-{$random}";
        
        // Check if this registration number already exists
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE registration_number = ?");
        $stmt->execute([$registrationNumber]);
        $exists = $stmt->fetchColumn() > 0;
        
        $attempt++;
        
        if (!$exists) {
            return $registrationNumber;
        }
        
    } while ($attempt < $maxAttempts);
    
    // Fallback: use timestamp-based number if all random attempts failed
    return "XC25-" . strtoupper(substr(md5(microtime()), 0, 6));
}

// Validate registration data
function validateRegistrationData($data) {
    $errors = [];
    
    // Basic required fields
    $basic_required = ['delegateType', 'delegateCount', 'paymentMethod'];
    foreach ($basic_required as $field) {
        if (empty($data[$field])) {
            $errors[] = "Missing required field: {$field}";
        }
    }
    
    // Contact information validation
    if (empty($data['contact']) || !is_array($data['contact'])) {
        $errors[] = "Missing contact information";
    } else {
        $contact_required = [
            'fullName' => 'Full Name',
            'designation' => 'Designation',
            'department' => 'Department',
            'email' => 'Email',
            'mobile' => 'Mobile',
            'university' => 'University',
            'country' => 'Country'
        ];
        
        foreach ($contact_required as $field => $label) {
            if (empty($data['contact'][$field])) {
                $errors[] = "Missing required field: {$label}";
            }
        }
        
        // Email validation
        if (!empty($data['contact']['email']) && !filter_var($data['contact']['email'], FILTER_VALIDATE_EMAIL)) {
            $errors[] = "Invalid email format";
        }
    }
    
    // Delegate count validation
    if (!empty($data['delegateCount'])) {
        $count = intval($data['delegateCount']);
        if ($count < 1 || $count > 50) {
            $errors[] = "Delegate count must be between 1 and 50";
        }
    }
    
    // Delegates data validation
    if (!empty($data['delegates']) && is_array($data['delegates'])) {
        foreach ($data['delegates'] as $index => $delegate) {
            if (empty($delegate['fullName'])) {
                $errors[] = "Delegate " . ($index + 1) . " full name is required";
            }
            if (empty($delegate['badgeName'])) {
                $errors[] = "Delegate " . ($index + 1) . " badge name is required";
            }
            if (empty($delegate['designation'])) {
                $errors[] = "Delegate " . ($index + 1) . " designation is required";
            }
        }
    }
    
    return $errors;
}
?>
