<?php
/**
 * Delegate Accommodation Registration
 * GHAMECC Choir Management Platform
 * 
 * This page allows administrators to register accommodations for individual delegates.
 */

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Include required files
require_once '../includes/auth.php';
require_once '../config/database.php';
require_once '../includes/functions.php';

// Try to include SMS functions with error handling
$smsAvailable = false;
$smsFilePath = '../includes/sms_functions.php';
$absolutePath = __DIR__ . '/../includes/sms_functions.php';

// Log debugging information
if (function_exists('logInfo')) {
    logInfo('SMS functions loading attempt', [
        'relative_path' => $smsFilePath,
        'absolute_path' => $absolutePath,
        'relative_exists' => file_exists($smsFilePath),
        'absolute_exists' => file_exists($absolutePath),
        'current_dir' => __DIR__
    ]);
}

// Try to load SMS functions with proper error handling
try {
    // Try relative path first
    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');
        
        if (function_exists('logInfo')) {
            logInfo('SMS functions loaded successfully', [
                'method' => 'relative_path',
                'function_exists' => $smsAvailable,
                'sms_enabled' => defined('SMS_ENABLED') ? SMS_ENABLED : 'undefined',
                'all_user_functions' => array_filter(get_defined_functions()['user'], function($func) {
                    return strpos($func, 'sms') !== false || strpos($func, 'SMS') !== false;
                }),
                'sendSMS_exists' => function_exists('sendSMS'),
                'sendDelegateNotificationSMS_exists' => function_exists('sendDelegateNotificationSMS'),
                'sendAccommodationAssignmentSMS_exists' => function_exists('sendAccommodationAssignmentSMS'),
                'global_conn_available' => isset($GLOBALS['conn']) ? 'yes' : 'no'
            ]);
        }
    } elseif (file_exists($absolutePath)) {
        // Try absolute path as fallback
        if (!defined('SMS_ENABLED')) {
            require_once __DIR__ . '/../config/mnotify.php';
        }
        if (!function_exists('logInfo')) {
            require_once __DIR__ . '/../config/logger.php';
        }
        
        require_once $absolutePath;
        $smsAvailable = function_exists('sendAccommodationAssignmentSMS');
        
        if (function_exists('logInfo')) {
            logInfo('SMS functions loaded successfully', [
                'method' => 'absolute_path',
                'function_exists' => $smsAvailable,
                'sms_enabled' => defined('SMS_ENABLED') ? SMS_ENABLED : 'undefined',
                'all_user_functions' => array_filter(get_defined_functions()['user'], function($func) {
                    return strpos($func, 'sms') !== false || strpos($func, 'SMS') !== false;
                }),
                'sendSMS_exists' => function_exists('sendSMS'),
                'sendDelegateNotificationSMS_exists' => function_exists('sendDelegateNotificationSMS'),
                'sendAccommodationAssignmentSMS_exists' => function_exists('sendAccommodationAssignmentSMS'),
                'global_conn_available' => isset($GLOBALS['conn']) ? 'yes' : 'no'
            ]);
        }
    } else {
        if (function_exists('logWarning')) {
            logWarning('SMS functions file not found', [
                'relative_path' => $smsFilePath,
                'absolute_path' => $absolutePath,
                'current_working_dir' => getcwd()
            ]);
        }
    }
} catch (Exception $e) {
    if (function_exists('logError')) {
        logError('Error loading SMS functions', [
            'error' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine()
        ]);
    }
}

// Create fallback function if SMS functions aren't available
if (!$smsAvailable) {
    function sendAccommodationAssignmentSMS($registration_id, $room_number, $accommodation_type, $check_in_date, $check_out_date, $notes = '') {
        if (function_exists('logInfo')) {
            logInfo('SMS function called but not available - accommodation assignment', [
                'registration_id' => $registration_id,
                'room_number' => $room_number,
                'accommodation_type' => $accommodation_type
            ]);
        }
        return [
            'status' => 'disabled',
            'message' => 'SMS functionality is not available'
        ];
    }
}

// Require login
requireLogin();

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

// Get conference ID and member ID from URL
$conferenceId = isset($_GET['conference_id']) ? (int)$_GET['conference_id'] : 0;
$memberId = isset($_GET['member_id']) ? (int)$_GET['member_id'] : 0;
$registrationId = isset($_GET['registration_id']) ? (int)$_GET['registration_id'] : 0;

// If no conference ID or member ID provided, redirect to conference selection
if (!$conferenceId || (!$memberId && !$registrationId)) {
    header("Location: select_conference.php?target=accommodations");
    exit("Missing required parameters");
}

// Get user information
$userId = $_SESSION['user_id'];
$userRole = $_SESSION['role'];

// Check user roles
$isAdmin = hasRole(['admin']);
$isDiocesanRole = hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_music_director', 'diocesan_treasurer']);
$isCircuitRole = hasRole(['circuit_chairman', 'circuit_secretary', 'circuit_music_director', 'circuit_treasurer']);

// Only admin and diocesan roles can access this page
if (!$isAdmin && !$isDiocesanRole) {
    header("Location: ../index.php");
    exit("Unauthorized access");
}

// Get user's diocese ID based on role
$userDioceseId = 0;

// Get user's diocese if they have a diocesan role
if ($isDiocesanRole) {
    $userDioceseQuery = "SELECT diocese_id FROM users WHERE id = $userId";
    $userDioceseResult = fetchRow($userDioceseQuery);
    if ($userDioceseResult && isset($userDioceseResult['diocese_id'])) {
        $userDioceseId = $userDioceseResult['diocese_id'];
    }
}

// Get conference details
$conference = fetchRow("SELECT c.*, 
                      CASE 
                          WHEN c.type = 'circuit' THEN ct.name 
                          WHEN c.type = 'diocese' THEN d.name 
                      END as entity_name,
                      c.type as conference_type,
                      c.entity_id
                      FROM conferences c
                      LEFT JOIN circuits ct ON (c.entity_id = ct.id AND c.type = 'circuit')
                      LEFT JOIN dioceses d ON (c.entity_id = d.id AND c.type = 'diocese')
                      WHERE c.id = $conferenceId");

// If conference not found, redirect
if (!$conference) {
    header("Location: select_conference.php?target=accommodations");
    exit("Conference not found");
}

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

// Admin has access to all conferences
if ($isAdmin) {
    $hasAccess = true;
}
// For diocese conferences, check if user belongs to the conference's diocese
elseif ($isDiocesanRole && $conference['conference_type'] == 'diocese' && $userDioceseId == $conference['entity_id']) {
    $hasAccess = true;
}

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

// Get member details and registration information
$member = null;
$registration = null;

if ($registrationId) {
    // Get registration and member details using registration ID
    $registration = fetchRow("SELECT cr.*, m.id as member_id, m.first_name, m.last_name as surname, 
                            m.email, m.contact_number as phone, m.sex as gender, m.part as voice_part,
                            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.id = $registrationId AND cr.conference_id = $conferenceId");
    
    if ($registration) {
        $memberId = $registration['member_id'];
        $member = [
            'id' => $registration['member_id'],
            'first_name' => $registration['first_name'],
            'surname' => $registration['surname'],
            'email' => $registration['email'],
            'phone' => $registration['phone'],
            'gender' => $registration['gender'],
            'voice_part' => $registration['voice_part'],
            'society_name' => $registration['society_name'],
            'circuit_name' => $registration['circuit_name']
        ];
    }
} else {
    // Get member details
    $member = fetchRow("SELECT m.*, s.name as society_name, c.name as circuit_name
                      FROM members m
                      JOIN societies s ON m.society_id = s.id
                      JOIN circuits c ON s.circuit_id = c.id
                      WHERE m.id = $memberId");
    
    // Check if member is already registered for this conference
    if ($member) {
        $registration = fetchRow("SELECT * FROM conference_registrations 
                               WHERE conference_id = $conferenceId AND member_id = $memberId");
        
        if ($registration) {
            $registrationId = $registration['id'];
        }
    }
}

// If member not found, redirect
if (!$member) {
    header("Location: diocese_conference_delegates.php?conference_id=$conferenceId");
    exit("Member not found");
}

// Get all accommodation types for this conference
$accommodationTypes = fetchRows("SELECT id, name, description, capacity, total_rooms 
                               FROM conference_accommodation_types 
                               WHERE conference_id = $conferenceId
                               ORDER BY name");

// Check if accommodation is already assigned
$accommodationAssigned = false;
$accommodationDetails = null;

if ($registrationId) {
    $assignmentQuery = "SELECT cra.*, cat.name as accommodation_type_name, cat.description
                      FROM conference_room_assignments cra
                      JOIN conference_accommodation_types cat ON cra.accommodation_type_id = cat.id
                      WHERE cra.registration_id = $registrationId";
    $accommodationDetails = fetchRow($assignmentQuery);
    $accommodationAssigned = ($accommodationDetails && isset($accommodationDetails['id']));
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle accommodation request
    if (isset($_POST['update_accommodation'])) {
        $requestAccommodation = isset($_POST['accommodation_required']) ? 1 : 0;
        
        if ($registrationId) {
            // Update existing registration
            $updateQuery = "UPDATE conference_registrations 
                           SET accommodation_required = $requestAccommodation,
                               updated_at = NOW(),
                               updated_by = $userId
                           WHERE id = $registrationId";
            
            if (mysqli_query($conn, $updateQuery)) {
                if ($registration) {
                    $registration['accommodation_required'] = $requestAccommodation;
                }
                $message = "Accommodation request updated successfully.";
                $messageType = "success";
            } else {
                $message = "Error updating accommodation request: " . mysqli_error($conn);
                $messageType = "danger";
            }
        } else {
            // Create new registration
            $insertQuery = "INSERT INTO conference_registrations 
                           (conference_id, member_id, accommodation_required, created_by, created_at)
                           VALUES ($conferenceId, $memberId, $requestAccommodation, $userId, NOW())";
            
            if (mysqli_query($conn, $insertQuery)) {
                $registrationId = mysqli_insert_id($conn);
                $registration = [
                    'id' => $registrationId,
                    'conference_id' => $conferenceId,
                    'member_id' => $memberId,
                    'accommodation_required' => $requestAccommodation
                ];
                $message = "Conference registration with accommodation request created successfully.";
                $messageType = "success";
            } else {
                $message = "Error creating registration: " . mysqli_error($conn);
                $messageType = "danger";
            }
        }
    }
    
    // Handle accommodation assignment
    if (isset($_POST['assign_accommodation']) && $registrationId) {
        $accommodationTypeId = isset($_POST['accommodation_type_id']) ? (int)$_POST['accommodation_type_id'] : 0;
        $notes = isset($_POST['notes']) ? mysqli_real_escape_string($conn, $_POST['notes']) : '';
        $checkInDate = isset($_POST['check_in_date']) ? mysqli_real_escape_string($conn, $_POST['check_in_date']) : null;
        $checkOutDate = isset($_POST['check_out_date']) ? mysqli_real_escape_string($conn, $_POST['check_out_date']) : null;
        
        // Get accommodation type name to use as room number
        $roomNumber = '';
        if ($accommodationTypeId > 0) {
            $typeQuery = "SELECT name FROM conference_accommodation_types WHERE id = $accommodationTypeId";
            $typeResult = mysqli_query($conn, $typeQuery);
            if ($typeResult && $typeRow = mysqli_fetch_assoc($typeResult)) {
                $roomNumber = trim($typeRow['name']); // Use accommodation type name as room number
            }
        }
        
        if ($accommodationAssigned) {
            // Update existing assignment
            $updateQuery = "UPDATE conference_room_assignments 
                           SET accommodation_type_id = $accommodationTypeId,
                               room_number = '$roomNumber',
                               notes = '$notes',
                               check_in_date = " . ($checkInDate ? "'$checkInDate'" : "NULL") . ",
                               check_out_date = " . ($checkOutDate ? "'$checkOutDate'" : "NULL") . ",
                               updated_at = NOW(),
                               updated_by = $userId
                           WHERE registration_id = $registrationId";
            
            if (mysqli_query($conn, $updateQuery)) {
                $message = "Accommodation assignment updated successfully.";
                $messageType = "success";
                
                // Refresh accommodation details
                $accommodationDetails = fetchRow($assignmentQuery);
                
                // Send SMS notification for accommodation update
                if ($accommodationDetails) {
                    $smsResult = sendAccommodationAssignmentSMS(
                        $registrationId,
                        $roomNumber,
                        $accommodationDetails['accommodation_type_name'],
                        $checkInDate ? date('F d, Y', strtotime($checkInDate)) : 'TBD',
                        $checkOutDate ? date('F d, Y', strtotime($checkOutDate)) : 'TBD',
                        $notes
                    );
                    
                    if (isset($smsResult['status']) && $smsResult['status'] === 'success') {
                        $message .= " SMS notification sent successfully.";
                    } else {
                        $message .= " However, SMS notification failed to send.";
                    }
                }
            } else {
                $message = "Error updating accommodation assignment: " . mysqli_error($conn);
                $messageType = "danger";
            }
        } else {
            // Create new assignment
            $insertQuery = "INSERT INTO conference_room_assignments 
                           (registration_id, accommodation_type_id, room_number, notes, check_in_date, check_out_date, created_by, created_at)
                           VALUES ($registrationId, $accommodationTypeId, '$roomNumber', '$notes', " . 
                           ($checkInDate ? "'$checkInDate'" : "NULL") . ", " . 
                           ($checkOutDate ? "'$checkOutDate'" : "NULL") . ", $userId, NOW())";
            
            if (mysqli_query($conn, $insertQuery)) {
                $message = "Accommodation assigned successfully.";
                $messageType = "success";
                $accommodationAssigned = true;
                
                // Refresh accommodation details
                $accommodationDetails = fetchRow($assignmentQuery);
                
                // Send SMS notification for accommodation assignment
                if ($accommodationDetails) {
                    $smsResult = sendAccommodationAssignmentSMS(
                        $registrationId,
                        $roomNumber,
                        $accommodationDetails['accommodation_type_name'],
                        $checkInDate ? date('F d, Y', strtotime($checkInDate)) : 'TBD',
                        $checkOutDate ? date('F d, Y', strtotime($checkOutDate)) : 'TBD',
                        $notes
                    );
                    
                    if (isset($smsResult['status']) && $smsResult['status'] === 'success') {
                        $message .= " SMS notification sent successfully.";
                    } else {
                        $message .= " However, SMS notification failed to send.";
                    }
                }
            } else {
                $message = "Error assigning accommodation: " . mysqli_error($conn);
                $messageType = "danger";
            }
        }
    }
    
    // Handle accommodation removal
    if (isset($_POST['remove_accommodation']) && $registrationId && $accommodationAssigned) {
        $deleteQuery = "DELETE FROM conference_room_assignments WHERE registration_id = $registrationId";
        
        if (mysqli_query($conn, $deleteQuery)) {
            $message = "Accommodation assignment removed successfully.";
            $messageType = "success";
            $accommodationAssigned = false;
            $accommodationDetails = null;
            
            // Send SMS notification for accommodation removal
            $message = "Your accommodation assignment for " . $conference['name'] . " has been removed.";
            sendSMS($member['phone'], $message);
        } else {
            $message = "Error removing accommodation assignment: " . mysqli_error($conn);
            $messageType = "danger";
        }
    }
}

// Page title
$pageTitle = "Delegate Accommodation Registration";
?>

<!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">Delegate Accommodation Registration</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="diocese_conference_delegates.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-secondary me-2">
                            <i class="fas fa-arrow-left me-1"></i> Back to Delegates List
                        </a>
                        <a href="accommodations.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-primary me-2">
                            <i class="fas fa-bed me-1"></i> All Accommodations
                        </a>
                    </div>
                </div>
                
                <?php if (!empty($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; ?>
                
                <div class="row">
                    <div class="col-md-4">
                        <!-- Member Information Card -->
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Delegate Information</h6>
                            </div>
                            <div class="card-body">
                                <h5><?php echo htmlspecialchars($member['first_name'] . ' ' . $member['surname']); ?></h5>
                                <p class="mb-1"><strong>Society:</strong> <?php echo htmlspecialchars($member['society_name']); ?></p>
                                <p class="mb-1"><strong>Circuit:</strong> <?php echo htmlspecialchars($member['circuit_name']); ?></p>
                                
                                <?php if (!empty($member['phone'])): ?>
                                <p class="mb-1"><strong>Phone:</strong> <?php echo htmlspecialchars($member['phone']); ?></p>
                                <?php endif; ?>
                                
                                <?php if (!empty($member['email'])): ?>
                                <p class="mb-1"><strong>Email:</strong> <?php echo htmlspecialchars($member['email']); ?></p>
                                <?php endif; ?>
                                
                                <p class="mb-1"><strong>Gender:</strong> <?php echo htmlspecialchars(ucfirst($member['gender'] ?? 'Not specified')); ?></p>
                                <p class="mb-1"><strong>Voice Part:</strong> <?php echo htmlspecialchars(ucfirst($member['voice_part'] ?? 'Not specified')); ?></p>
                            </div>
                        </div>
                        
                        <!-- Conference Information Card -->
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Conference Information</h6>
                            </div>
                            <div class="card-body">
                                <h5><?php echo htmlspecialchars($conference['name']); ?></h5>
                                <p class="mb-1"><strong>Type:</strong> <?php echo ucfirst(htmlspecialchars($conference['conference_type'])); ?></p>
                                <p class="mb-1"><strong><?php echo $conference['conference_type'] == 'diocese' ? 'Diocese' : 'Circuit'; ?>:</strong> <?php echo htmlspecialchars($conference['entity_name']); ?></p>
                                <p class="mb-1"><strong>Start Date:</strong> <?php echo date('F d, Y', strtotime($conference['start_date'])); ?></p>
                                <p class="mb-1"><strong>End Date:</strong> <?php echo date('F d, Y', strtotime($conference['end_date'])); ?></p>
                                <p class="mb-1"><strong>Venue:</strong> <?php echo htmlspecialchars($conference['venue']); ?></p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-8">
                        <!-- Accommodation Registration Card -->
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Accommodation Registration</h6>
                            </div>
                            <div class="card-body">
                                <?php if (!$registration): ?>
                                <div class="alert alert-warning">
                                    <i class="fas fa-exclamation-triangle me-2"></i> This delegate is not yet registered for the conference. Please register them for accommodation below.
                                </div>
                                <?php endif; ?>
                                
                                <form method="post" action="" class="mb-4">
                                    <div class="form-check mb-3">
                                        <input class="form-check-input" type="checkbox" name="accommodation_required" id="accommodation_required" <?php echo ($registration && $registration['accommodation_required']) ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="accommodation_required">
                                            This delegate requires accommodation for the conference
                                        </label>
                                    </div>
                                    
                                    <button type="submit" name="update_accommodation" class="btn btn-primary">
                                        <i class="fas fa-save me-1"></i> <?php echo $registration ? 'Update' : 'Register'; ?> Accommodation Request
                                    </button>
                                </form>
                                
                                <?php if ($registration && $registration['accommodation_required']): ?>
                                
                                <?php if ($accommodationAssigned): ?>
                                <!-- Accommodation Assignment Details -->
                                <div class="card border-success mb-3">
                                    <div class="card-header bg-success text-white">
                                        <h5 class="mb-0">Current Accommodation Assignment</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <p><strong>Accommodation Type:</strong> <?php echo htmlspecialchars($accommodationDetails['accommodation_type_name']); ?></p>
                                                <p><strong>Room Number:</strong> <?php echo htmlspecialchars($accommodationDetails['room_number']); ?></p>
                                            </div>
                                            <div class="col-md-6">
                                                <?php if ($accommodationDetails['check_in_date']): ?>
                                                <p><strong>Check-in Date:</strong> <?php echo date('F d, Y', strtotime($accommodationDetails['check_in_date'])); ?></p>
                                                <?php endif; ?>
                                                
                                                <?php if ($accommodationDetails['check_out_date']): ?>
                                                <p><strong>Check-out Date:</strong> <?php echo date('F d, Y', strtotime($accommodationDetails['check_out_date'])); ?></p>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        
                                        <?php if (!empty($accommodationDetails['notes'])): ?>
                                        <div class="mt-3">
                                            <p><strong>Notes:</strong></p>
                                            <p><?php echo nl2br(htmlspecialchars($accommodationDetails['notes'])); ?></p>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="mt-3">
                                            <button type="button" class="btn btn-warning" data-bs-toggle="collapse" data-bs-target="#editAccommodation">
                                                <i class="fas fa-edit me-1"></i> Edit Assignment
                                            </button>
                                            
                                            <form method="post" action="" class="d-inline">
                                                <button type="submit" name="remove_accommodation" class="btn btn-danger ms-2" onclick="return confirm('Are you sure you want to remove this accommodation assignment?');">
                                                    <i class="fas fa-trash-alt me-1"></i> Remove Assignment
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Edit Accommodation Form (Collapsed by default) -->
                                <div class="collapse" id="editAccommodation">
                                    <div class="card border-warning mb-3">
                                        <div class="card-header bg-warning text-dark">
                                            <h5 class="mb-0">Edit Accommodation Assignment</h5>
                                        </div>
                                        <div class="card-body">
                                            <form method="post" action="">
                                                <div class="mb-3">
                                                    <label for="accommodation_type_id" class="form-label">Accommodation Type</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 ($accommodationDetails['accommodation_type_id'] == $type['id']) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($type['name']); ?> (<?php echo $type['capacity']; ?> person(s) per room)
                                                        </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="room_number" class="form-label">Room Number</label>
                                                    <input type="text" readonly class="form-control" id="room_number" name="room_number" required>
                                                </div>
                                                
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label for="check_in_date" class="form-label">Check-in Date</label>
                                                            <input type="date" class="form-control" id="check_in_date" name="check_in_date" value="<?php echo $accommodationDetails['check_in_date']; ?>">
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label for="check_out_date" class="form-label">Check-out Date</label>
                                                            <input type="date" class="form-control" id="check_out_date" name="check_out_date" value="<?php echo $accommodationDetails['check_out_date']; ?>">
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="notes" class="form-label">Notes</label>
                                                    <textarea class="form-control" id="notes" name="notes" rows="3"><?php echo htmlspecialchars($accommodationDetails['notes']); ?></textarea>
                                                </div>
                                                
                                                <button type="submit" name="assign_accommodation" class="btn btn-primary">
                                                    <i class="fas fa-save me-1"></i> Update Assignment
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                
                                <?php else: ?>
                                <!-- New Accommodation Assignment Form -->
                                <div class="card border-primary mb-3">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0">Assign Accommodation</h5>
                                    </div>
                                    <div class="card-body">
                                        <?php if (empty($accommodationTypes)): ?>
                                        <div class="alert alert-warning">
                                            No accommodation types have been defined for this conference yet.
                                            <a href="accommodation_types.php?conference_id=<?php echo $conferenceId; ?>" class="alert-link">Click here to add accommodation types</a>.
                                        </div>
                                        <?php else: ?>
                                        <form method="post" action="">
                                            <div class="mb-3">
                                                <label for="accommodation_type_id" class="form-label">Accommodation Type</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']); ?> (<?php echo $type['capacity']; ?> person(s) per room)
                                                    </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label for="room_number" class="form-label">Room Number</label>
                                                <input type="text" readonly class="form-control" id="room_number" name="room_number" required>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="mb-3">
                                                        <label for="check_in_date" class="form-label">Check-in Date</label>
                                                        <input type="date" class="form-control" id="check_in_date" name="check_in_date">
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="mb-3">
                                                        <label for="check_out_date" class="form-label">Check-out Date</label>
                                                        <input type="date" class="form-control" id="check_out_date" name="check_out_date">
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label for="notes" class="form-label">Notes</label>
                                                <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                                            </div>
                                            
                                            <button type="submit" name="assign_accommodation" class="btn btn-primary">
                                                <i class="fas fa-bed me-1"></i> Assign Accommodation
                                            </button>
                                        </form>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <?php endif; ?>
                                
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </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>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Function to auto-populate room number with accommodation type name
        function populateRoomNumber(selectElement) {
            var selectedOption = selectElement.find('option:selected');
            var roomNumberField = selectElement.closest('form').find('input[name="room_number"]');
            
            if (selectedOption.val() && selectedOption.text() !== 'Select Accommodation Type') {
                // Extract accommodation type name (remove the capacity part in parentheses)
                var accommodationTypeName = selectedOption.text().split(' (')[0];
                roomNumberField.val(accommodationTypeName);
            } else {
                roomNumberField.val('');
            }
        }
        
        // Bind the function to both accommodation type dropdowns
        $('select[name="accommodation_type_id"]').on('change', function() {
            populateRoomNumber($(this));
        });
    });
    </script>
</body>
</html>
