<?php
/**
 * Delegate Accommodations List
 * GHAMECC Choir Management Platform
 * 
 * This page displays all delegates for a selected conference and allows administrators
 * to select a delegate to manage their accommodation.
 */

// 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=delegate_accommodation");
    exit("Missing conference ID");
}

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

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

// Get conference details
$conferenceQuery = "SELECT c.*, 
                    CASE 
                        WHEN c.type = 'circuit' THEN ct.name 
                        WHEN c.type = 'diocese' THEN d.name 
                    END as entity_name
                    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";
$conference = fetchRow($conferenceQuery);

if (!$conference) {
    header("Location: select_conference.php?target=delegate_accommodation");
    exit("Conference not found");
}

// Get all delegates for this conference
$delegatesQuery = "SELECT cr.id as registration_id, m.id as member_id, 
                  m.first_name, m.last_name as surname, 
                  m.sex as gender, m.part as voice_part, m.contact_number as phone, m.email, 
                  s.name as society_name, c.name as circuit_name, cr.payment_status,
                  (SELECT COUNT(*) FROM conference_room_assignments ra WHERE ra.registration_id = cr.id) as has_accommodation
                  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
                  ORDER BY c.name, s.name, m.last_name, m.first_name";
$delegates = fetchRows($delegatesQuery);

// Page title
$pageTitle = "Delegate Accommodations List";
?>

<!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">
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    
    <!-- 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 Accommodations List</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="select_conference.php?target=delegate_accommodation" class="btn btn-sm btn-secondary me-2">
                            <i class="fas fa-arrow-left me-1"></i> Select Different Conference
                        </a>
                        <a href="accommodations.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-primary">
                            <i class="fas fa-bed me-1"></i> Manage All Accommodations
                        </a>
                    </div>
                </div>
                
                <!-- Conference Info 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">
                        <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['type'])); ?></p>
                                <p><strong>Entity:</strong> <?php echo htmlspecialchars($conference['entity_name']); ?></p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>Start Date:</strong> <?php echo date('d M Y', strtotime($conference['start_date'])); ?></p>
                                <p><strong>End Date:</strong> <?php echo date('d M Y', strtotime($conference['end_date'])); ?></p>
                                <p><strong>Venue:</strong> <?php echo htmlspecialchars($conference['venue']); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Delegates List Card -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Registered Delegates</h6>
                    </div>
                    <div class="card-body">
                        <?php if (empty($delegates)): ?>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i> No delegates registered for this conference.
                        </div>
                        <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-bordered" id="delegatesTable" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Name</th>
                                        <th>Society</th>
                                        <th>Circuit</th>
                                        <th>Contact</th>
                                        <th>Gender</th>
                                        <th>Voice Part</th>
                                        <th>Payment Status</th>
                                        <th>Accommodation</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $counter = 1; ?>
                                    <?php foreach ($delegates as $delegate): ?>
                                    <tr>
                                        <td><?php echo $counter++; ?></td>
                                        <td><?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['surname']); ?></td>
                                        <td><?php echo htmlspecialchars($delegate['society_name']); ?></td>
                                        <td><?php echo htmlspecialchars($delegate['circuit_name']); ?></td>
                                        <td>
                                            <?php if (!empty($delegate['phone'])): ?>
                                            <i class="fas fa-phone me-1"></i> <?php echo htmlspecialchars($delegate['phone']); ?><br>
                                            <?php endif; ?>
                                            <?php if (!empty($delegate['email'])): ?>
                                            <i class="fas fa-envelope me-1"></i> <?php echo htmlspecialchars($delegate['email']); ?>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo htmlspecialchars(ucfirst($delegate['gender'] ?? 'Not specified')); ?></td>
                                        <td><?php echo htmlspecialchars(ucfirst($delegate['voice_part'] ?? 'Not specified')); ?></td>
                                        <td>
                                            <span class="badge bg-<?php echo $delegate['payment_status'] === 'paid' ? 'success' : ($delegate['payment_status'] === 'waived' ? 'info' : 'warning'); ?>">
                                                <?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', $delegate['payment_status']))); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($delegate['has_accommodation'] > 0): ?>
                                            <span class="badge bg-success">Assigned</span>
                                            <?php else: ?>
                                            <span class="badge bg-warning">Not Assigned</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a href="delegate_accommodation.php?conference_id=<?php echo $conferenceId; ?>&registration_id=<?php echo $delegate['registration_id']; ?>" class="btn btn-sm btn-primary">
                                                <i class="fas fa-bed me-1"></i> Manage
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php endif; ?>
                    </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>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
        $(document).ready(function() {
            $('#delegatesTable').DataTable({
                "pageLength": 25,
                "order": [[2, "asc"], [1, "asc"]] // Sort by society then name
            });
        });
    </script>
</body>
</html>
