<?php
/**
 * Accommodations Management for Diocese Conference
 * GHAMECC Choir Management Platform
 * 
 * This page displays and manages accommodation assignments for diocese conference delegates,
 * organized by circuits and societies.
 */

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

// Require login
requireLogin();

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

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

// Check if user has appropriate permissions (only diocese roles or admin)
if (!hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_treasurer', 'diocesan_music_director', 'admin'])) {
    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 and not admin, redirect to index
if (!$userDioceseId && !hasRole(['admin'])) {
    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: index.php");
    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;

// Admin has access to all conferences
if (hasRole(['admin'])) {
    $hasAccess = true;
    // If admin, get the diocese from the conference
    $userDioceseId = $conference['entity_id'];
}
// For diocese conferences, check if user belongs to the conference's diocese
elseif ($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 submission for accommodation assignment
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_accommodation'])) {
    $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']) ? trim($_POST['room_number']) : '';
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
    
    if ($registrationId && $accommodationTypeId && $roomNumber) {
        // Check if this registration already has an accommodation assignment
        $existingAssignment = fetchRow("SELECT id FROM conference_room_assignments 
                                      WHERE registration_id = $registrationId");
        
        if ($existingAssignment) {
            // Update existing assignment
            $updateQuery = "UPDATE conference_room_assignments 
                           SET accommodation_type_id = $accommodationTypeId,
                               room_number = '" . mysqli_real_escape_string($conn, $roomNumber) . "',
                               notes = '" . mysqli_real_escape_string($conn, $notes) . "',
                               updated_by = $userId,
                               updated_at = NOW()
                           WHERE registration_id = $registrationId";
            
            if (mysqli_query($conn, $updateQuery)) {
                $message = "Accommodation assignment updated successfully.";
                $messageType = "success";
            } 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, created_by, created_at)
                           VALUES ($registrationId, $accommodationTypeId, 
                                  '" . mysqli_real_escape_string($conn, $roomNumber) . "',
                                  '" . mysqli_real_escape_string($conn, $notes) . "',
                                  $userId, NOW())";
            
            if (mysqli_query($conn, $insertQuery)) {
                $message = "Accommodation assigned successfully.";
                $messageType = "success";
            } else {
                $message = "Error assigning accommodation: " . mysqli_error($conn);
                $messageType = "danger";
            }
        }
    } else {
        $message = "Please fill all required fields.";
        $messageType = "warning";
    }
}

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

// Get all registered delegates with their accommodation info for this conference from societies in circuits in this diocese
$delegates = fetchRows("SELECT 
                      cr.id as registration_id, 
                      cr.payment_status, 
                      cr.accommodation_required,
                      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, 
                      s.id as society_id,
                      c.name as circuit_name, 
                      c.id as circuit_id,
                      cra.id as assignment_id,
                      cra.room_number,
                      cra.notes as accommodation_notes,
                      cra.check_in_date,
                      cra.check_out_date,
                      cat.id as accommodation_type_id,
                      cat.name as accommodation_type_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
                      JOIN dioceses d ON c.diocese_id = d.id
                      LEFT JOIN conference_room_assignments cra ON cr.id = cra.registration_id
                      LEFT JOIN conference_accommodation_types cat ON cra.accommodation_type_id = cat.id
                      WHERE cr.conference_id = $conferenceId
                      AND d.id = $userDioceseId
                      AND cr.accommodation_required = 1
                      ORDER BY c.name, s.name, m.last_name, m.first_name");

// Group delegates by circuit and society
$delegatesByCircuit = [];
foreach ($delegates as $delegate) {
    $circuitId = $delegate['circuit_id'];
    $circuitName = $delegate['circuit_name'];
    $societyId = $delegate['society_id'];
    $societyName = $delegate['society_name'];
    
    if (!isset($delegatesByCircuit[$circuitId])) {
        $delegatesByCircuit[$circuitId] = [
            'name' => $circuitName,
            'societies' => []
        ];
    }
    
    if (!isset($delegatesByCircuit[$circuitId]['societies'][$societyId])) {
        $delegatesByCircuit[$circuitId]['societies'][$societyId] = [
            'name' => $societyName,
            'delegates' => []
        ];
    }
    
    $delegatesByCircuit[$circuitId]['societies'][$societyId]['delegates'][] = $delegate;
}

// Calculate statistics
$totalDelegates = count($delegates);
$assignedDelegates = 0;
$unassignedDelegates = 0;

foreach ($delegates as $delegate) {
    if (!empty($delegate['assignment_id'])) {
        $assignedDelegates++;
    } else {
        $unassignedDelegates++;
    }
}

// Get room usage statistics by accommodation type
$roomStats = [];
if (!empty($accommodationTypes)) {
    foreach ($accommodationTypes as $type) {
        $typeId = $type['id'];
        $assignedRooms = fetchRow("SELECT COUNT(DISTINCT room_number) as count 
                                 FROM conference_room_assignments 
                                 WHERE accommodation_type_id = $typeId");
        
        $roomStats[$typeId] = [
            'name' => $type['name'],
            'total' => $type['total_rooms'],
            'assigned' => $assignedRooms ? $assignedRooms['count'] : 0,
            'available' => $type['total_rooms'] - ($assignedRooms ? $assignedRooms['count'] : 0)
        ];
    }
}
?>

<!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>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- 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.4.0/css/all.min.css">
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    
    <!-- Custom CSS -->
    <link href="../assets/css/style.css" rel="stylesheet">
    
    <style>
        @media print {
            .no-print {
                display: none !important;
            }
            .print-only {
                display: block !important;
            }
            .container-fluid {
                width: 100% !important;
            }
            .card {
                break-inside: avoid;
            }
        }
        .print-only {
            display: none;
        }
        .accommodation-assigned {
            background-color: #d1e7dd !important;
        }
        .accommodation-pending {
            background-color: #fff3cd !important;
        }
    </style>
</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</h1>
                    <div class="btn-toolbar mb-2 mb-md-0 no-print">
                        <a href="index.php" class="btn btn-sm btn-secondary me-2">
                            <i class="fas fa-arrow-left me-1"></i> Back to Conferences
                        </a>
                        <a href="diocese_conference_delegates.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-primary me-2">
                            <i class="fas fa-users me-1"></i> View All Delegates
                        </a>
                        <a href="conference_accommodations.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-info me-2">
                            <i class="fas fa-user-check me-1"></i> Delegate Registration
                        </a>
                        <button class="btn btn-sm btn-outline-primary me-2" onclick="window.print()">
                            <i class="fas fa-print me-1"></i> Print List
                        </button>
                        <a href="export_accommodations.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-outline-success">
                            <i class="fas fa-file-excel me-1"></i> Export to Excel
                        </a>
                    </div>
                </div>
                
                <!-- Print Header -->
                <div class="print-only mb-4">
                    <h2 class="text-center">GHAMECC Choir Management Platform</h2>
                    <h3 class="text-center">Conference Accommodations</h3>
                </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="alert alert-info">
                    <div class="row">
                        <div class="col-md-6">
                            <strong>Conference:</strong> <?php echo htmlspecialchars($conference['name']); ?> <br>
                            <strong>Diocese:</strong> <?php echo htmlspecialchars($conference['diocese_name']); ?> <br>
                            <strong>Date:</strong> <?php echo date('F d, Y', strtotime($conference['start_date'])); ?> to <?php echo date('F d, Y', strtotime($conference['end_date'])); ?>
                        </div>
                        <div class="col-md-6">
                            <strong>Total Delegates Requiring Accommodation:</strong> <?php echo $totalDelegates; ?> <br>
                            <strong>Assigned:</strong> <?php echo $assignedDelegates; ?> <br>
                            <strong>Unassigned:</strong> <?php echo $unassignedDelegates; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Accommodation Types and Room Statistics -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Accommodation Types & Room Statistics</h6>
                    </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: ?>
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>Accommodation Type</th>
                                        <th>Description</th>
                                        <th>Capacity</th>
                                        <th>Total Rooms</th>
                                        <th>Assigned Rooms</th>
                                        <th>Available Rooms</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($roomStats as $typeId => $stats): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($stats['name']); ?></td>
                                        <td>
                                            <?php 
                                            $description = '';
                                            foreach ($accommodationTypes as $type) {
                                                if ($type['id'] == $typeId) {
                                                    $description = $type['description'];
                                                    break;
                                                }
                                            }
                                            echo htmlspecialchars($description); 
                                            ?>
                                        </td>
                                        <td>
                                            <?php 
                                            $capacity = 1;
                                            foreach ($accommodationTypes as $type) {
                                                if ($type['id'] == $typeId) {
                                                    $capacity = $type['capacity'];
                                                    break;
                                                }
                                            }
                                            echo $capacity; 
                                            ?>
                                        </td>
                                        <td><?php echo $stats['total']; ?></td>
                                        <td><?php echo $stats['assigned']; ?></td>
                                        <td>
                                            <span class="badge bg-<?php echo $stats['available'] > 0 ? 'success' : 'danger'; ?>">
                                                <?php echo $stats['available']; ?>
                                            </span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php if (empty($delegates)): ?>
                <div class="alert alert-info">
                    No delegates requiring accommodation have been registered for this conference yet.
                </div>
                <?php else: ?>
                
                <!-- Delegates by Circuit and Society -->
                <?php foreach ($delegatesByCircuit as $circuitId => $circuitData): ?>
                <div class="card shadow mb-4">
                    <div class="card-header py-3 bg-primary text-white">
                        <h5 class="m-0 font-weight-bold">
                            <?php echo htmlspecialchars($circuitData['name']); ?> Circuit
                        </h5>
                    </div>
                    
                    <?php foreach ($circuitData['societies'] as $societyId => $societyData): ?>
                    <div class="card-body border-bottom">
                        <h6 class="font-weight-bold text-primary mb-3">
                            <?php echo htmlspecialchars($societyData['name']); ?> Society
                            <span class="badge bg-secondary"><?php echo count($societyData['delegates']); ?> delegates</span>
                        </h6>
                        
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Name</th>
                                        <th>Gender</th>
                                        <th>Voice Part</th>
                                        <th>Accommodation</th>
                                        <th>Room</th>
                                        <th>Check-In/Out</th>
                                        <th class="no-print">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $counter = 1; ?>
                                    <?php foreach ($societyData['delegates'] as $delegate): ?>
                                    <tr class="<?php echo !empty($delegate['assignment_id']) ? 'accommodation-assigned' : 'accommodation-pending'; ?>">
                                        <td><?php echo $counter++; ?></td>
                                        <td>
                                            <?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['surname']); ?>
                                            <?php if (!empty($delegate['phone'])): ?>
                                            <br><small><i class="fas fa-phone me-1"></i> <?php echo htmlspecialchars($delegate['phone']); ?></small>
                                            <?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>
                                            <?php if (!empty($delegate['accommodation_type_name'])): ?>
                                            <?php echo htmlspecialchars($delegate['accommodation_type_name']); ?>
                                            <?php else: ?>
                                            <span class="text-warning">Not Assigned</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if (!empty($delegate['room_number'])): ?>
                                            <?php echo htmlspecialchars($delegate['room_number']); ?>
                                            <?php else: ?>
                                            <span class="text-warning">Not Assigned</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if (!empty($delegate['check_in_date'])): ?>
                                            <strong>In:</strong> <?php echo date('M d, Y', strtotime($delegate['check_in_date'])); ?><br>
                                            <strong>Out:</strong> <?php echo date('M d, Y', strtotime($delegate['check_out_date'])); ?>
                                            <?php else: ?>
                                            <span class="text-warning">Not Recorded</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="no-print">
                                            <?php if (!empty($delegate['assignment_id'])): ?>
                                            <div class="btn-group btn-group-sm" role="group">
                                                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#assignModal<?php echo $delegate['registration_id']; ?>">
                                                    <i class="fas fa-edit"></i> Edit
                                                </button>
                                                <a href="javascript:void(0);" onclick="window.location.href='check_in_out.php?assignment_id=<?php echo $delegate['assignment_id']; ?>'" class="btn btn-info">
                                                    <i class="fas fa-exchange-alt"></i> Check In/Out
                                                </a>
                                            </div>
                                            <?php else: ?>
                                            <button type="button" class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#assignModal<?php echo $delegate['registration_id']; ?>">
                                                <i class="fas fa-home"></i> Assign Room
                                            </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    
                                    <!-- Assign/Edit Accommodation Modal -->
                                    <div class="modal fade" id="assignModal<?php echo $delegate['registration_id']; ?>" tabindex="-1" aria-labelledby="assignModalLabel<?php echo $delegate['registration_id']; ?>" aria-hidden="true">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="assignModalLabel<?php echo $delegate['registration_id']; ?>">
                                                        <?php echo !empty($delegate['assignment_id']) ? 'Edit' : 'Assign'; ?> Accommodation
                                                    </h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <form method="post" action="">
                                                    <div class="modal-body">
                                                        <input type="hidden" name="registration_id" value="<?php echo $delegate['registration_id']; ?>">
                                                        
                                                        <div class="mb-3">
                                                            <label for="delegate<?php echo $delegate['registration_id']; ?>" class="form-label">Delegate</label>
                                                            <input type="text" class="form-control" id="delegate<?php echo $delegate['registration_id']; ?>" value="<?php echo htmlspecialchars($delegate['first_name'] . ' ' . $delegate['surname']); ?>" readonly>
                                                        </div>
                                                        
                                                        <div class="mb-3">
                                                            <label for="society<?php echo $delegate['registration_id']; ?>" class="form-label">Society</label>
                                                            <input type="text" class="form-control" id="society<?php echo $delegate['registration_id']; ?>" value="<?php echo htmlspecialchars($delegate['society_name']); ?>" readonly>
                                                        </div>
                                                        
                                                        <div class="mb-3">
                                                            <label for="accommodationType<?php echo $delegate['registration_id']; ?>" class="form-label">Accommodation Type</label>
                                                            <select class="form-select" id="accommodationType<?php echo $delegate['registration_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 ($delegate['accommodation_type_id'] == $type['id']) ? 'selected' : ''; ?>>
                                                                    <?php echo htmlspecialchars($type['name']); ?> (<?php echo $type['capacity']; ?> per room)
                                                                </option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </div>
                                                        
                                                        <div class="mb-3">
                                                            <label for="roomNumber<?php echo $delegate['registration_id']; ?>" class="form-label">Room Number</label>
                                                            <input type="text" class="form-control" id="roomNumber<?php echo $delegate['registration_id']; ?>" name="room_number" value="<?php echo htmlspecialchars($delegate['room_number'] ?? ''); ?>" required>
                                                        </div>
                                                        
                                                        <div class="mb-3">
                                                            <label for="notes<?php echo $delegate['registration_id']; ?>" class="form-label">Notes</label>
                                                            <textarea class="form-control" id="notes<?php echo $delegate['registration_id']; ?>" name="notes" rows="3"><?php echo htmlspecialchars($delegate['accommodation_notes'] ?? ''); ?></textarea>
                                                        </div>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                        <button type="submit" name="assign_accommodation" class="btn btn-primary">Save</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endforeach; ?>
                
                <?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>
    
    <script>
        $(document).ready(function() {
            // Initialize any JavaScript functionality here
        });
    </script>
</body>
</html>
