<?php
/**
 * Event Capacity Helper Functions
 * Handles automatic waitlist assignment when events reach capacity
 */

// Prevent redeclaration of functions
if (!function_exists('checkEventCapacity')) {

/**
 * Check if an event is at capacity and determine if new participants should be waitlisted
 * @param mysqli $conn Database connection
 * @param int $eventId Event ID
 * @return array Array with 'at_capacity' boolean and 'waitlist_status' (0 or 1)
 */
function checkEventCapacity($conn, $eventId) {
    // Get event capacity
    $eventStmt = $conn->prepare("SELECT places_total FROM Events WHERE id = ?");
    $eventStmt->bind_param("i", $eventId);
    $eventStmt->execute();
    $eventStmt->bind_result($placesTotal);
    $eventStmt->fetch();
    $eventStmt->close();
    
    // DEBUG: Alert showing capacity check
    echo "<script>alert('DEBUG: checkEventCapacity() - EventId: $eventId, places_total: $placesTotal');</script>";
    
    if (!$placesTotal) {
        // If no capacity set, allow unlimited participants
        return ['at_capacity' => false, 'waitlist_status' => 0];
    }
    
    // Count current non-waitlist participants
    $countStmt = $conn->prepare("SELECT COUNT(*) FROM EventUsers WHERE EventId = ? AND waitlist = 0");
    $countStmt->bind_param("i", $eventId);
    $countStmt->execute();
    $countStmt->bind_result($currentParticipants);
    $countStmt->fetch();
    $countStmt->close();
    
    $atCapacity = ($currentParticipants >= $placesTotal);
    $waitlistStatus = $atCapacity ? 1 : 0;
    
    return [
        'at_capacity' => $atCapacity,
        'waitlist_status' => $waitlistStatus,
        'current_participants' => $currentParticipants,
        'total_capacity' => $placesTotal
    ];
}

/**
 * Get event capacity information for display
 * @param mysqli $conn Database connection
 * @param int $eventId Event ID
 * @return array Capacity information
 */
function getEventCapacityInfo($conn, $eventId) {
    $capacity = checkEventCapacity($conn, $eventId);
    
    return [
        'current_participants' => $capacity['current_participants'],
        'total_capacity' => $capacity['total_capacity'],
        'available_spots' => max(0, $capacity['total_capacity'] - $capacity['current_participants']),
        'waitlist_count' => getWaitlistCount($conn, $eventId),
        'at_capacity' => $capacity['at_capacity']
    ];
}

/**
 * Get count of waitlisted participants
 * @param mysqli $conn Database connection
 * @param int $eventId Event ID
 * @return int Number of waitlisted participants
 */
function getWaitlistCount($conn, $eventId) {
    $waitlistStmt = $conn->prepare("SELECT COUNT(*) FROM EventUsers WHERE EventId = ? AND waitlist = 1");
    $waitlistStmt->bind_param("i", $eventId);
    $waitlistStmt->execute();
    $waitlistStmt->bind_result($waitlistCount);
    $waitlistStmt->fetch();
    $waitlistStmt->close();
    
    return $waitlistCount;
}

/**
 * Add participant with automatic waitlist assignment
 * @param mysqli $conn Database connection
 * @param int $eventId Event ID
 * @param int $userId User ID (null for guests)
 * @param int $guestId Guest ID (null for users)
 * @param int $isGuest 0 for user, 1 for guest
 * @param string $observations Additional observations
 * @return array Result with success status and waitlist info
 */
function addParticipantWithCapacityCheck($conn, $eventId, $userId = null, $guestId = null, $isGuest = 0, $observations = '') {
    $capacity = checkEventCapacity($conn, $eventId);
    $waitlistStatus = $capacity['waitlist_status'];
    
    // Insert participant with appropriate waitlist status
    $stmt = $conn->prepare("INSERT INTO EventUsers 
        (flight, tee, observations, waitlist, guest, createdAt, updatedAt, UserId, EventId, GuestId, teebox, Seqno, places, starter, main, desert)
        VALUES (0, 1, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?, ?, ?, 0, NULL, 0, 'zzzzz', 'zzzzz', 'zzzzz')");
    
    $stmt->bind_param("siiii", $observations, $waitlistStatus, $isGuest, $userId, $eventId, $guestId);
    
    if ($stmt->execute()) {
        $participantId = $conn->insert_id;
        $stmt->close();
        
        return [
            'success' => true,
            'participant_id' => $participantId,
            'waitlist_status' => $waitlistStatus,
            'at_capacity' => $capacity['at_capacity'],
            'message' => $waitlistStatus ? 'Added to waitlist' : 'Added as participant'
        ];
    } else {
        $stmt->close();
        return [
            'success' => false,
            'error' => $stmt->error,
            'message' => 'Failed to add participant'
        ];
    }
}

} // End of function_exists check
?>
