<?php
/**
 * Conference Room Assignments Management
 * GHAMECC Choir Management Platform
 * 
 * This page allows administrators to assign delegates to accommodation rooms
 * for conference events.
 */

require_once '../includes/auth.php';
require_once '../config/database.php';

// Try to include SMS functions with error handling
$smsAvailable = false;
$smsFilePath = '../includes/sms_functions.php';
if (file_exists($smsFilePath)) {
    // Ensure dependencies are loaded first
    if (!defined('SMS_ENABLED')) {
        require_once '../config/mnotify.php';
    }
    if (!function_exists('logInfo')) {
        require_once '../config/logger.php';
    }
    
    require_once $smsFilePath;
    $smsAvailable = function_exists('sendAccommodationAssignmentSMS');
}

// Set base path for includes
$basePath = '..';

// Basic variables
$pageTitle = "Conference Room Assignments";
$userId = $_SESSION['user_id'];
$isDioceseRole = hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_treasurer', 'diocesan_dom']);

// Check if user has appropriate permissions (only diocese roles)
if (!hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_treasurer', 'diocesan_dom'])) {
    header("Location: ../index.php");
    exit("Unauthorized access");
}

// Get user's diocese
$userDioceseId = 0;
if ($isDioceseRole) {
    $userDioceseQuery = "SELECT diocese_id FROM users WHERE id = $userId";
    $userDioceseResult = fetchRow($userDioceseQuery);
    if ($userDioceseResult && isset($userDioceseResult['diocese_id'])) {
        $userDioceseId = $userDioceseResult['diocese_id'];
    }
}

// If no diocese ID found, redirect to index
if (!$userDioceseId) {
    header("Location: ../index.php");
    exit("No diocese assigned to your account");
}

// Get conference ID from URL
$conferenceId = isset($_GET['conference_id']) ? (int)$_GET['conference_id'] : 0;

// If no conference ID provided, redirect to conferences list
if (!$conferenceId) {
    header("Location: select_conference.php?target=room_assignments");
    exit("No conference selected");
}

// Get conference details - check for diocese conferences
$conference = fetchRow("SELECT c.*, d.name as diocese_name
                       FROM conferences c
                       LEFT JOIN dioceses d ON (c.entity_id = d.id AND c.type = 'diocese')
                       WHERE c.id = $conferenceId AND c.type = 'diocese'");

// If conference not found, redirect
if (!$conference) {
    header("Location: index.php");
    exit("Conference not found or not a diocese conference");
}

// Check if diocese has access to this conference
$hasAccess = false;

// For diocese conferences, check if user belongs to the conference's diocese
if ($userDioceseId == $conference['entity_id']) {
    $hasAccess = true;
}

// Redirect if no access
if (!$hasAccess) {
    header("Location: index.php");
    exit("You don't have access to this conference");
}

// Process form submissions
$message = '';
$messageType = '';

// Get all accommodation types for this conference
$accommodationTypesQuery = "SELECT * FROM conference_accommodation_types 
                           WHERE conference_id = $conferenceId 
                           ORDER BY name";
$accommodationTypes = fetchRows($accommodationTypesQuery);

// Get all unassigned delegates who need accommodation
$unassignedDelegatesQuery = "SELECT cr.id, m.id as member_id, m.first_name, m.last_name, m.sex as gender, 
                            s.name as society_name, c.name as circuit_name
                            FROM conference_registrations cr
                            JOIN members m ON cr.member_id = m.id
                            JOIN societies s ON m.society_id = s.id
                            JOIN circuits c ON s.circuit_id = c.id
                            WHERE cr.conference_id = $conferenceId 
                            AND cr.accommodation_required = 1
                            AND cr.id NOT IN (
                                SELECT registration_id FROM conference_room_assignments
                            )
                            ORDER BY m.sex, s.name, m.last_name, m.first_name";
$unassignedDelegates = fetchRows($unassignedDelegatesQuery);

// Count total delegates requiring accommodation
$totalRequiringQuery = "SELECT COUNT(*) as total 
                       FROM conference_registrations 
                       WHERE conference_id = $conferenceId 
                       AND accommodation_required = 1";
$totalRequiringResult = fetchRow($totalRequiringQuery);
$totalRequiringAccommodation = $totalRequiringResult ? $totalRequiringResult['total'] : 0;

// Get all assigned delegates grouped by accommodation type and room number
$assignedDelegatesQuery = "SELECT cra.id as assignment_id, cra.room_number, 
                          cr.id as registration_id, m.id as member_id, 
                          m.first_name, m.last_name, m.sex as gender,
                          s.name as society_name, c.name as circuit_name,
                          cat.id as accommodation_type_id, cat.name as accommodation_type_name
                          FROM conference_room_assignments cra
                          JOIN conference_registrations cr ON cra.registration_id = cr.id
                          JOIN members m ON cr.member_id = m.id
                          JOIN societies s ON m.society_id = s.id
                          JOIN circuits c ON s.circuit_id = c.id
                          JOIN conference_accommodation_types cat ON cra.accommodation_type_id = cat.id
                          WHERE cr.conference_id = $conferenceId
                          ORDER BY cat.name, cra.room_number, m.sex, m.last_name, m.first_name";
$assignedDelegatesResult = fetchRows($assignedDelegatesQuery);

// Group assigned delegates by accommodation type and room number
$assignedDelegatesByType = [];
if ($assignedDelegatesResult) {
    foreach ($assignedDelegatesResult as $delegate) {
        $typeId = $delegate['accommodation_type_id'];
        $roomNumber = $delegate['room_number'];
        
        if (!isset($assignedDelegatesByType[$typeId])) {
            $assignedDelegatesByType[$typeId] = [
                'name' => $delegate['accommodation_type_name'],
                'rooms' => []
            ];
        }
        
        if (!isset($assignedDelegatesByType[$typeId]['rooms'][$roomNumber])) {
            $assignedDelegatesByType[$typeId]['rooms'][$roomNumber] = [];
        }
        
        $assignedDelegatesByType[$typeId]['rooms'][$roomNumber][] = $delegate;
    }
}

// Calculate statistics
$totalDelegatesNeedingAccommodation = $totalRequiringAccommodation;
if ($assignedDelegatesResult) {
    $totalDelegatesNeedingAccommodation += count($assignedDelegatesResult);
}
$totalAssigned = $assignedDelegatesResult ? count($assignedDelegatesResult) : 0;
$totalUnassigned = count($unassignedDelegates);
$assignmentProgress = $totalDelegatesNeedingAccommodation > 0 ? 
    round(($totalAssigned / $totalDelegatesNeedingAccommodation) * 100) : 0;

// Diagnostic query to check if there are any delegates requiring accommodation
$diagnosticQuery = "SELECT COUNT(*) as total_requiring_accommodation 
                   FROM conference_registrations 
                   WHERE conference_id = $conferenceId 
                   AND accommodation_required = 1";
$diagnosticResult = fetchRow($diagnosticQuery);
$totalRequiringAccommodation = $diagnosticResult ? $diagnosticResult['total_requiring_accommodation'] : 0;

// Add to message if it exists
if (isset($message)) {
    $message .= " | Diagnostic: $totalRequiringAccommodation delegates require accommodation.";
} else {
    $message = "Diagnostic: $totalRequiringAccommodation delegates require accommodation.";
    $messageType = "info";
}

// Handle form submission for assigning a room
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_room'])) {
    $registrationId = isset($_POST['registration_id']) ? (int)$_POST['registration_id'] : 0;
    $accommodationTypeId = isset($_POST['accommodation_type_id']) ? (int)$_POST['accommodation_type_id'] : 0;
    $roomNumber = isset($_POST['room_number']) ? mysqli_real_escape_string($conn, trim($_POST['room_number'])) : '';
    
    // Validate inputs
    $errors = [];
    
    if (!$registrationId) {
        $errors[] = "Invalid delegate selection.";
    }
    
    if (!$accommodationTypeId) {
        $errors[] = "Please select an accommodation type.";
    }
    
    if (empty($roomNumber)) {
        $errors[] = "Room number is required.";
    }
    
    // Check if the accommodation type exists and belongs to this conference
    if ($accommodationTypeId) {
        $typeCheck = fetchRow("SELECT * FROM conference_accommodation_types 
                              WHERE id = $accommodationTypeId 
                              AND conference_id = $conferenceId");
        if (!$typeCheck) {
            $errors[] = "Invalid accommodation type selected.";
        }
    }
    
    // Check if the delegate is already assigned to a room
    if ($registrationId) {
        $existingAssignment = fetchRow("SELECT * FROM conference_room_assignments 
                                       WHERE registration_id = $registrationId");
        if ($existingAssignment) {
            $errors[] = "This delegate is already assigned to a room.";
        }
    }
    
    // Check room capacity (optional, can be implemented based on requirements)
    // For example, you might want to limit the number of delegates per room
    
    // If no errors, proceed with assignment
    if (empty($errors)) {
        $insertQuery = "INSERT INTO conference_room_assignments 
                       (registration_id, accommodation_type_id, room_number, assigned_by, assigned_at) 
                       VALUES ($registrationId, $accommodationTypeId, '$roomNumber', $userId, NOW())";
        
        if (mysqli_query($conn, $insertQuery)) {
            $message = "Delegate successfully assigned to room $roomNumber.";
            $messageType = "success";
            
            // Send SMS notification if available
            if ($smsAvailable) {
                $delegate = fetchRow("SELECT m.first_name, m.last_name, m.phone_number 
                                      FROM conference_registrations cr
                                      JOIN members m ON cr.member_id = m.id
                                      WHERE cr.id = $registrationId");
                if ($delegate) {
                    $smsMessage = "You have been assigned to room $roomNumber for the $conference[name] conference.";
                    sendAccommodationAssignmentSMS($delegate['phone_number'], $smsMessage);
                }
            }
            
            // Redirect to refresh the page and prevent form resubmission
            header("Location: room_assignments.php?conference_id=$conferenceId&message=" . urlencode($message) . "&type=$messageType");
            exit;
        } else {
            $message = "Error assigning room: " . mysqli_error($conn);
            $messageType = "danger";
        }
    } else {
        $message = "Please correct the following errors: " . implode(" ", $errors);
        $messageType = "danger";
    }
}

// Handle form submission for removing a room assignment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_assignment'])) {
    $assignmentId = isset($_POST['assignment_id']) ? (int)$_POST['assignment_id'] : 0;
    
    if ($assignmentId) {
        $deleteQuery = "DELETE FROM conference_room_assignments WHERE id = $assignmentId";
        
        if (mysqli_query($conn, $deleteQuery)) {
            $message = "Room assignment successfully removed.";
            $messageType = "success";
            
            // Redirect to refresh the page and prevent form resubmission
            header("Location: room_assignments.php?conference_id=$conferenceId&message=" . urlencode($message) . "&type=$messageType");
            exit;
        } else {
            $message = "Error removing assignment: " . mysqli_error($conn);
            $messageType = "danger";
        }
    } else {
        $message = "Invalid assignment selected.";
        $messageType = "danger";
    }
}

// Handle bulk SMS notification for all assigned delegates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_bulk_sms'])) {
    // Log the bulk SMS attempt
    if (function_exists('logInfo')) {
        logInfo('Bulk SMS request initiated', [
            'conference_id' => $conferenceId,
            'user_id' => $userId,
            'sms_available' => $smsAvailable
        ]);
    }
    
    if (!$smsAvailable) {
        $message = "SMS functionality is not available at this time.";
        $messageType = "warning";
        
        if (function_exists('logWarning')) {
            logWarning('Bulk SMS failed - SMS not available', [
                'conference_id' => $conferenceId,
                'user_id' => $userId
            ]);
        }
    } else {
        // Get all assigned delegates with their room information
        $bulkSMSQuery = "SELECT cra.id as assignment_id, cra.room_number, 
                        cr.id as registration_id, m.id as member_id, 
                        m.first_name, m.last_name, m.contact_number,
                        cat.name as accommodation_type_name,
                        c.name as conference_name, c.start_date, c.end_date
                        FROM conference_room_assignments cra
                        JOIN conference_registrations cr ON cra.registration_id = cr.id
                        JOIN members m ON cr.member_id = m.id
                        JOIN conference_accommodation_types cat ON cra.accommodation_type_id = cat.id
                        JOIN conferences c ON cr.conference_id = c.id
                        WHERE cr.conference_id = $conferenceId
                        AND m.contact_number IS NOT NULL 
                        AND m.contact_number != ''";
        
        if (function_exists('logInfo')) {
            logInfo('Executing bulk SMS query', [
                'query' => $bulkSMSQuery,
                'conference_id' => $conferenceId
            ]);
        }
        
        $bulkSMSDelegates = fetchRows($bulkSMSQuery);
        
        if (function_exists('logInfo')) {
            logInfo('Bulk SMS query results', [
                'delegates_found' => count($bulkSMSDelegates),
                'conference_id' => $conferenceId
            ]);
        }
        
        if (empty($bulkSMSDelegates)) {
            $message = "No assigned delegates with valid phone numbers found.";
            $messageType = "warning";
            
            if (function_exists('logWarning')) {
                logWarning('No delegates found for bulk SMS', [
                    'conference_id' => $conferenceId,
                    'total_assigned' => $totalAssigned
                ]);
            }
        } else {
            $successCount = 0;
            $failureCount = 0;
            $totalDelegates = count($bulkSMSDelegates);
            
            if (function_exists('logInfo')) {
                logInfo('Starting bulk SMS sending', [
                    'total_delegates' => $totalDelegates,
                    'conference_id' => $conferenceId
                ]);
            }
            
            foreach ($bulkSMSDelegates as $delegate) {
                $checkInDate = date('F d, Y', strtotime($delegate['start_date']));
                $checkOutDate = date('F d, Y', strtotime($delegate['end_date']));
                
                if (function_exists('logInfo')) {
                    logInfo('Sending SMS to delegate', [
                        'delegate_name' => $delegate['first_name'] . ' ' . $delegate['last_name'],
                        'phone' => $delegate['contact_number'],
                        'room' => $delegate['room_number'],
                        'registration_id' => $delegate['registration_id']
                    ]);
                }
                
                $smsResult = sendAccommodationAssignmentSMS(
                    $delegate['registration_id'],
                    $delegate['room_number'],
                    $delegate['accommodation_type_name'],
                    $checkInDate,
                    $checkOutDate,
                    "Please arrive on time and bring valid identification."
                );
                
                if (function_exists('logInfo')) {
                    logInfo('SMS result for delegate', [
                        'delegate_name' => $delegate['first_name'] . ' ' . $delegate['last_name'],
                        'sms_result' => $smsResult
                    ]);
                }
                
                if (isset($smsResult['status']) && ($smsResult['status'] === 'success' || $smsResult['status'] === 'disabled')) {
                    $successCount++;
                } else {
                    $failureCount++;
                }
                
                // Add small delay between SMS sends to avoid rate limiting
                usleep(500000); // 0.5 second delay
            }
            
            if ($failureCount === 0) {
                $message = "Successfully sent SMS notifications to all $successCount assigned delegates.";
                $messageType = "success";
            } else {
                $message = "SMS notifications sent: $successCount successful, $failureCount failed out of $totalDelegates total.";
                $messageType = $successCount > 0 ? "warning" : "danger";
            }
            
            // Log the bulk SMS operation results
            if (function_exists('logInfo')) {
                logInfo('Bulk SMS operation completed', [
                    'conference_id' => $conferenceId,
                    'total_delegates' => $totalDelegates,
                    'success_count' => $successCount,
                    'failure_count' => $failureCount,
                    'user_id' => $userId,
                    'final_message' => $message
                ]);
            }
        }
    }
    
    // Redirect to show the result message
    header("Location: room_assignments.php?conference_id=$conferenceId&message=" . urlencode($message) . "&type=$messageType");
    exit;
}

// Check for messages in URL (from redirects)
if (isset($_GET['message'])) {
    $message = $_GET['message'];
    $messageType = isset($_GET['type']) ? $_GET['type'] : 'info';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - GHAMECC</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    
    <!-- Custom styles -->
    <link rel="stylesheet" href="<?php echo $basePath; ?>/css/style.css">
</head>
<body>
    <!-- Navigation -->
    <?php include '../includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include '../includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Conference Room Assignments</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="accommodation_types.php" class="btn btn-sm btn-outline-secondary me-2">
                            <i class="fas fa-building me-1"></i> Manage Accommodation Types
                        </a>
                        <a href="select_conference.php?target=accommodations" class="btn btn-sm btn-outline-secondary me-2">
                            <i class="fas fa-bed me-1"></i> Manage Accommodations
                        </a>
                        <?php if ($totalAssigned > 0): ?>
                        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#sendBulkSMSModal">
                            <i class="fas fa-sms me-1"></i> Send Bulk SMS
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Conference Info -->
                <div class="alert alert-info mb-4">
                    <strong>Conference:</strong> <?php echo htmlspecialchars($conference['name']); ?> | 
                    <strong>Diocese:</strong> <?php echo htmlspecialchars($conference['diocese_name']); ?> | 
                    <strong>Dates:</strong> <?php echo date('M d, Y', strtotime($conference['start_date'])); ?> - 
                    <?php echo date('M d, Y', strtotime($conference['end_date'])); ?>
                </div>
                
                <?php if ($message): ?>
                <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                    <?php echo $message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-primary shadow h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                            Total Delegates Needing Accommodation</div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $totalDelegatesNeedingAccommodation; ?></div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-users fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-success shadow h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                            Assigned Delegates</div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $totalAssigned; ?></div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-check-circle fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-warning shadow h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                            Unassigned Delegates</div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $totalUnassigned; ?></div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-exclamation-triangle fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-info shadow h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Assignment Progress
                                        </div>
                                        <div class="row no-gutters align-items-center">
                                            <div class="col-auto">
                                                <div class="h5 mb-0 mr-3 font-weight-bold text-gray-800"><?php echo $assignmentProgress; ?>%</div>
                                            </div>
                                            <div class="col">
                                                <div class="progress progress-sm mr-2">
                                                    <div class="progress-bar bg-info" role="progressbar"
                                                        style="width: <?php echo $assignmentProgress; ?>%" aria-valuenow="<?php echo $assignmentProgress; ?>" aria-valuemin="0"
                                                        aria-valuemax="100"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-clipboard-list fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <!-- Unassigned Delegates -->
                    <div class="col-lg-12 mb-4">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                                <h6 class="m-0 font-weight-bold text-primary">Unassigned Delegates</h6>
                            </div>
                            <div class="card-body">
                                <?php 
                                // Check if there are any delegates requiring accommodation
                                $hasAccommodationNeeds = ($totalRequiringAccommodation > 0);
                                
                                if (empty($unassignedDelegates)): 
                                    if ($hasAccommodationNeeds): 
                                ?>
                                <div class="alert alert-success">
                                    <i class="fas fa-check-circle me-2"></i> All delegates have been assigned to rooms.
                                </div>
                                <?php else: ?>
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i> No delegates requiring accommodation for this conference.
                                </div>
                                <?php endif; else: ?>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Name</th>
                                                <th>Gender</th>
                                                <th>Society</th>
                                                <th>Circuit</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php $counter = 1; ?>
                                            <?php foreach ($unassignedDelegates as $delegate): ?>
                                            <tr>
                                                <td><?php echo $counter++; ?></td>
                                                <td><?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['last_name']); ?></td>
                                                <td><?php echo htmlspecialchars($delegate['gender']); ?></td>
                                                <td><?php echo htmlspecialchars($delegate['society_name']); ?></td>
                                                <td><?php echo htmlspecialchars($delegate['circuit_name']); ?></td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#assignRoomModal<?php echo $delegate['id']; ?>">
                                                        <i class="fas fa-bed me-1"></i> Assign Room
                                                    </button>
                                                    
                                                    <!-- Assign Room Modal -->
                                                    <div class="modal fade" id="assignRoomModal<?php echo $delegate['id']; ?>" tabindex="-1" aria-labelledby="assignRoomModalLabel<?php echo $delegate['id']; ?>" aria-hidden="true">
                                                        <div class="modal-dialog">
                                                            <div class="modal-content">
                                                                <div class="modal-header">
                                                                    <h5 class="modal-title" id="assignRoomModalLabel<?php echo $delegate['id']; ?>">Assign Room to <?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['last_name']); ?></h5>
                                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                </div>
                                                                <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'] . '?conference_id=' . $conferenceId); ?>">
                                                                    <div class="modal-body">
                                                                        <input type="hidden" name="registration_id" value="<?php echo $delegate['id']; ?>">
                                                                        
                                                                        <div class="mb-3">
                                                                            <label for="accommodation_type_id" class="form-label">Accommodation Type <span class="text-danger">*</span></label>
                                                                            <select class="form-select" id="accommodation_type_id" name="accommodation_type_id" required>
                                                                                <option value="">Select Accommodation Type</option>
                                                                                <?php foreach ($accommodationTypes as $type): ?>
                                                                                <option value="<?php echo $type['id']; ?>"><?php echo htmlspecialchars($type['name']); ?></option>
                                                                                <?php endforeach; ?>
                                                                            </select>
                                                                        </div>
                                                                        
                                                                        <div class="mb-3">
                                                                            <label for="room_number" class="form-label">Room Number <span class="text-danger">*</span></label>
                                                                            <input type="text" class="form-control" id="room_number" name="room_number" required>
                                                                        </div>
                                                                    </div>
                                                                    <div class="modal-footer">
                                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                                        <button type="submit" name="assign_room" class="btn btn-primary">Assign Room</button>
                                                                    </div>
                                                                </form>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Assigned Delegates -->
                    <div class="col-lg-12">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Assigned Delegates</h6>
                            </div>
                            <div class="card-body">
                                <?php 
                                // Use the same $hasAccommodationNeeds variable from above
                                if (empty($assignedDelegatesByType)): 
                                    if ($hasAccommodationNeeds):
                                ?>
                                <div class="alert alert-warning">
                                    <i class="fas fa-exclamation-triangle me-2"></i> No delegates have been assigned to rooms yet.
                                </div>
                                <?php else: ?>
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i> No room assignments needed for this conference.
                                </div>
                                <?php endif; else: ?>
                                <div class="accordion" id="assignedDelegatesAccordion">
                                    <?php foreach ($assignedDelegatesByType as $typeId => $typeData): ?>
                                    <div class="accordion-item">
                                        <h2 class="accordion-header" id="heading<?php echo $typeId; ?>">
                                            <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapse<?php echo $typeId; ?>" aria-expanded="true" aria-controls="collapse<?php echo $typeId; ?>">
                                                <?php echo htmlspecialchars($typeData['name']); ?> 
                                                <span class="badge bg-primary ms-2"><?php echo count($typeData['rooms']); ?> Room(s)</span>
                                            </button>
                                        </h2>
                                        <div id="collapse<?php echo $typeId; ?>" class="accordion-collapse collapse show" aria-labelledby="heading<?php echo $typeId; ?>" data-bs-parent="#assignedDelegatesAccordion">
                                            <div class="accordion-body">
                                                <?php foreach ($typeData['rooms'] as $roomNumber => $delegates): ?>
                                                <div class="card mb-3">
                                                    <div class="card-header bg-light">
                                                        <h6 class="mb-0">Room <?php echo htmlspecialchars($roomNumber); ?> 
                                                        <span class="badge bg-secondary ms-2"><?php echo count($delegates); ?> Delegate(s)</span></h6>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="table-responsive">
                                                            <table class="table table-sm table-bordered">
                                                                <thead>
                                                                    <tr>
                                                                        <th>Name</th>
                                                                        <th>Gender</th>
                                                                        <th>Society</th>
                                                                        <th>Circuit</th>
                                                                        <th>Actions</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                    <?php foreach ($delegates as $delegate): ?>
                                                                    <tr>
                                                                        <td><?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['last_name']); ?></td>
                                                                        <td><?php echo htmlspecialchars($delegate['gender']); ?></td>
                                                                        <td><?php echo htmlspecialchars($delegate['society_name']); ?></td>
                                                                        <td><?php echo htmlspecialchars($delegate['circuit_name']); ?></td>
                                                                        <td>
                                                                            <div class="btn-group">
                                                                                <a href="check_in_out.php?assignment_id=<?php echo $delegate['assignment_id']; ?>&conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-primary me-1">
                                                                                    <i class="fas fa-clipboard-check me-1"></i> Check-In/Out
                                                                                </a>
                                                                                <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'] . '?conference_id=' . $conferenceId); ?>" onsubmit="return confirm('Are you sure you want to remove this room assignment?');">
                                                                                    <input type="hidden" name="assignment_id" value="<?php echo $delegate['assignment_id']; ?>">
                                                                                    <button type="submit" name="remove_assignment" class="btn btn-sm btn-danger">
                                                                                        <i class="fas fa-times me-1"></i> Remove
                                                                                    </button>
                                                                                </form>
                                                                            </div>
                                                                        </td>
                                                                    </tr>
                                                                    <?php endforeach; ?>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </div>
                                                </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Send Bulk SMS Modal -->
    <div class="modal fade" id="sendBulkSMSModal" tabindex="-1" aria-labelledby="sendBulkSMSModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="sendBulkSMSModalLabel">Send Bulk SMS to Assigned Delegates</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'] . '?conference_id=' . $conferenceId); ?>">
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            This will send SMS notifications to all <strong><?php echo $totalAssigned; ?> assigned delegates</strong> with their room assignment details.
                        </div>
                        <p><strong>SMS will include:</strong></p>
                        <ul>
                            <li>Room number and accommodation type</li>
                            <li>Conference dates</li>
                            <li>Check-in instructions</li>
                        </ul>
                        <p class="text-muted">Are you sure you want to proceed?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="send_bulk_sms" class="btn btn-primary">
                            <i class="fas fa-paper-plane me-1"></i> Send SMS to All
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
