<?php
/**
 * Conference Accommodations Registration
 * GHAMECC Choir Management Platform
 * 
 * This page allows delegates to register for accommodations for a selected conference.
 */

// 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';

// Require login
requireLogin();

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

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

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

// 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']);
$isSocietyRole = hasRole(['choirmaster', 'society_secretary', 'society_treasurer']);
$isMember = hasRole(['member']);

// Get user's society, circuit, and diocese IDs based on role
$userSocietyId = 0;
$userCircuitId = 0;
$userDioceseId = 0;

// Get user's society if they have a society role
if ($isSocietyRole || $isMember) {
    $userSocietyQuery = "SELECT society_id FROM users WHERE id = $userId";
    $userSocietyResult = fetchRow($userSocietyQuery);
    if ($userSocietyResult && isset($userSocietyResult['society_id'])) {
        $userSocietyId = $userSocietyResult['society_id'];
        
        // Get circuit and diocese for this society
        $societyInfo = fetchRow("SELECT s.circuit_id, c.diocese_id 
                                FROM societies s 
                                JOIN circuits c ON s.circuit_id = c.id 
                                WHERE s.id = $userSocietyId");
        
        if ($societyInfo) {
            $userCircuitId = $societyInfo['circuit_id'];
            $userDioceseId = $societyInfo['diocese_id'];
        }
    }
}

// Get user's circuit if they have a circuit role
if ($isCircuitRole && !$userCircuitId) {
    $userCircuitQuery = "SELECT circuit_id FROM users WHERE id = $userId";
    $userCircuitResult = fetchRow($userCircuitQuery);
    if ($userCircuitResult && isset($userCircuitResult['circuit_id'])) {
        $userCircuitId = $userCircuitResult['circuit_id'];
        
        // Get diocese for this circuit
        $circuitInfo = fetchRow("SELECT diocese_id FROM circuits WHERE id = $userCircuitId");
        if ($circuitInfo) {
            $userDioceseId = $circuitInfo['diocese_id'];
        }
    }
}

// Get user's diocese if they have a diocesan role
if ($isDiocesanRole && !$userDioceseId) {
    $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 ($conference['conference_type'] == 'diocese' && $userDioceseId == $conference['entity_id']) {
    $hasAccess = true;
}
// For circuit conferences, check if user belongs to the conference's circuit
elseif ($conference['conference_type'] == 'circuit' && $userCircuitId == $conference['entity_id']) {
    $hasAccess = true;
}
// For society members, check if their circuit/diocese matches the conference
elseif ($isSocietyRole || $isMember) {
    if ($conference['conference_type'] == 'diocese' && $userDioceseId == $conference['entity_id']) {
        $hasAccess = true;
    }
    elseif ($conference['conference_type'] == 'circuit' && $userCircuitId == $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 ID for the current user
$memberQuery = "SELECT member_id FROM users WHERE id = $userId";
$memberResult = fetchRow($memberQuery);
$memberId = ($memberResult && isset($memberResult['member_id'])) ? $memberResult['member_id'] : 0;

// Check if member is already registered for this conference
$isRegistered = false;
$registrationId = 0;
$accommodationRequired = 0;
$accommodationAssigned = false;

if ($memberId) {
    $registrationQuery = "SELECT id, accommodation_required FROM conference_registrations 
                         WHERE conference_id = $conferenceId AND member_id = $memberId";
    $registrationResult = fetchRow($registrationQuery);
    
    if ($registrationResult) {
        $isRegistered = true;
        $registrationId = $registrationResult['id'];
        $accommodationRequired = $registrationResult['accommodation_required'];
        
        // Check if accommodation is already assigned
        $assignmentQuery = "SELECT id FROM conference_room_assignments WHERE registration_id = $registrationId";
        $assignmentResult = fetchRow($assignmentQuery);
        $accommodationAssigned = ($assignmentResult && isset($assignmentResult['id']));
    }
}

// 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");

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle accommodation request
    if (isset($_POST['request_accommodation'])) {
        $requestAccommodation = isset($_POST['accommodation_required']) ? 1 : 0;
        
        if ($isRegistered) {
            // 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)) {
                $accommodationRequired = $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);
                $isRegistered = true;
                $accommodationRequired = $requestAccommodation;
                $message = "Conference registration with accommodation request created successfully.";
                $messageType = "success";
            } else {
                $message = "Error creating registration: " . mysqli_error($conn);
                $messageType = "danger";
            }
        }
    }
}

// Get accommodation details if assigned
$accommodationDetails = null;
if ($isRegistered && $accommodationRequired && $accommodationAssigned) {
    $accommodationQuery = "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($accommodationQuery);
}

// Page title
$pageTitle = "Conference Accommodations 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">Conference Accommodations Registration</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="select_conference.php?target=accommodations" class="btn btn-sm btn-secondary me-2">
                            <i class="fas fa-arrow-left me-1"></i> Select Different Conference
                        </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="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Conference Details</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong>Conference Name:</strong> <?php echo htmlspecialchars($conference['name']); ?></p>
                                <p><strong>Type:</strong> <?php echo ucfirst(htmlspecialchars($conference['conference_type'])); ?></p>
                                <p><strong><?php echo $conference['conference_type'] == 'diocese' ? 'Diocese' : 'Circuit'; ?>:</strong> <?php echo htmlspecialchars($conference['entity_name']); ?></p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>Start Date:</strong> <?php echo date('F d, Y', strtotime($conference['start_date'])); ?></p>
                                <p><strong>End Date:</strong> <?php echo date('F d, Y', strtotime($conference['end_date'])); ?></p>
                                <p><strong>Venue:</strong> <?php echo htmlspecialchars($conference['venue']); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php if (!$memberId): ?>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i> Your user account is not linked to a member profile. Please contact an administrator to link your account to a member profile before registering for accommodations.
                </div>
                <?php else: ?>
                
                <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 ($accommodationAssigned): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i> Your accommodation has been assigned.
                        </div>
                        
                        <div class="card border-success mb-3">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">Your Accommodation Details</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>
                        </div>
                        
                        <?php elseif ($isRegistered && $accommodationRequired): ?>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i> Your accommodation request has been submitted and is pending assignment. You will be notified once your accommodation has been assigned.
                        </div>
                        
                        <form method="post" action="">
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" name="accommodation_required" id="accommodation_required" <?php echo $accommodationRequired ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="accommodation_required">
                                    I require accommodation for this conference
                                </label>
                            </div>
                            
                            <button type="submit" name="request_accommodation" class="btn btn-warning">
                                <i class="fas fa-times-circle me-1"></i> Cancel Accommodation Request
                            </button>
                        </form>
                        
                        <?php else: ?>
                        <form method="post" action="">
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" name="accommodation_required" id="accommodation_required" <?php echo $accommodationRequired ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="accommodation_required">
                                    I require accommodation for this conference
                                </label>
                            </div>
                            
                            <button type="submit" name="request_accommodation" class="btn btn-primary">
                                <i class="fas fa-bed me-1"></i> <?php echo $isRegistered ? 'Update' : 'Submit'; ?> Accommodation Request
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php if (!empty($accommodationTypes)): ?>
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Available Accommodation Types</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>Type</th>
                                        <th>Description</th>
                                        <th>Capacity</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($accommodationTypes as $type): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($type['name']); ?></td>
                                        <td><?php echo htmlspecialchars($type['description']); ?></td>
                                        <td><?php echo $type['capacity']; ?> person(s) per room</td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="small text-muted mt-2">
                            Note: Accommodation assignments are made by conference organizers based on availability and other factors.
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <?php endif; ?>
            </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>
</body>
</html>
