<?php
/**
 * Conference Accommodation Types Management
 * GHAMECC Choir Management Platform
 * 
 * This page allows administrators to manage accommodation types for conferences
 * including creating, editing, and deleting accommodation types.
 */

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

// Require login
requireLogin();

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

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

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

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

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

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

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

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

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

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

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

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

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

// Handle create/update accommodation type
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_accommodation_type'])) {
    $typeId = isset($_POST['type_id']) ? (int)$_POST['type_id'] : 0;
    $name = isset($_POST['name']) ? mysqli_real_escape_string($conn, trim($_POST['name'])) : '';
    $description = isset($_POST['description']) ? mysqli_real_escape_string($conn, trim($_POST['description'])) : '';
    $capacity = isset($_POST['capacity']) ? (int)$_POST['capacity'] : 1;
    $totalRooms = isset($_POST['total_rooms']) ? (int)$_POST['total_rooms'] : 0;
    
    if (empty($name)) {
        $message = "Accommodation type name is required.";
        $messageType = "danger";
    } elseif ($capacity < 1) {
        $message = "Capacity must be at least 1.";
        $messageType = "danger";
    } elseif ($totalRooms < 1) {
        $message = "Total rooms must be at least 1.";
        $messageType = "danger";
    } else {
        if ($typeId) {
            // Update existing accommodation type
            $updateQuery = "UPDATE conference_accommodation_types 
                          SET name = '$name', 
                              description = '$description', 
                              capacity = $capacity, 
                              total_rooms = $totalRooms,
                              updated_at = NOW() 
                          WHERE id = $typeId AND conference_id = $conferenceId";
            
            if (mysqli_query($conn, $updateQuery)) {
                $message = "Accommodation type updated successfully.";
                $messageType = "success";
            } else {
                $message = "Error updating accommodation type: " . mysqli_error($conn);
                $messageType = "danger";
            }
        } else {
            // Create new accommodation type
            $insertQuery = "INSERT INTO conference_accommodation_types 
                          (conference_id, name, description, capacity, total_rooms, created_by, created_at) 
                          VALUES ($conferenceId, '$name', '$description', $capacity, $totalRooms, $userId, NOW())";
            
            if (mysqli_query($conn, $insertQuery)) {
                $message = "Accommodation type created successfully.";
                $messageType = "success";
            } else {
                $message = "Error creating accommodation type: " . mysqli_error($conn);
                $messageType = "danger";
            }
        }
    }
}

// Handle delete accommodation type
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_accommodation_type'])) {
    $typeId = isset($_POST['type_id']) ? (int)$_POST['type_id'] : 0;
    
    if ($typeId) {
        // Check if there are any room assignments using this accommodation type
        $checkAssignmentsQuery = "SELECT COUNT(*) as count FROM conference_room_assignments 
                                WHERE accommodation_type_id = $typeId";
        $assignmentsResult = fetchRow($checkAssignmentsQuery);
        
        if ($assignmentsResult && $assignmentsResult['count'] > 0) {
            $message = "Cannot delete: This accommodation type is currently assigned to " . $assignmentsResult['count'] . " delegates.";
            $messageType = "danger";
        } else {
            // Delete the accommodation type
            $deleteQuery = "DELETE FROM conference_accommodation_types 
                          WHERE id = $typeId AND conference_id = $conferenceId";
            
            if (mysqli_query($conn, $deleteQuery)) {
                $message = "Accommodation type deleted successfully.";
                $messageType = "success";
            } else {
                $message = "Error deleting accommodation type: " . mysqli_error($conn);
                $messageType = "danger";
            }
        }
    }
}

// Get all accommodation types for this conference
$accommodationTypesQuery = "SELECT cat.*, 
                          (SELECT COUNT(*) FROM conference_room_assignments cra WHERE cra.accommodation_type_id = cat.id) as assigned_rooms,
                          u.full_name as created_by_name
                          FROM conference_accommodation_types cat
                          LEFT JOIN users u ON cat.created_by = u.id
                          WHERE cat.conference_id = $conferenceId
                          ORDER BY cat.name";
$accommodationTypesResult = mysqli_query($conn, $accommodationTypesQuery);
$accommodationTypes = [];

if ($accommodationTypesResult) {
    while ($row = mysqli_fetch_assoc($accommodationTypesResult)) {
        $accommodationTypes[] = $row;
    }
}

// Get accommodation type for editing (if ID provided)
$editType = null;
if (isset($_GET['edit']) && (int)$_GET['edit'] > 0) {
    $editId = (int)$_GET['edit'];
    $editQuery = "SELECT * FROM conference_accommodation_types 
                WHERE id = $editId AND conference_id = $conferenceId";
    $editType = fetchRow($editQuery);
}

// Calculate statistics
$totalCapacity = 0;
$totalRooms = 0;
$totalAssigned = 0;

foreach ($accommodationTypes as $type) {
    $totalCapacity += ($type['capacity'] * $type['total_rooms']);
    $totalRooms += $type['total_rooms'];
    $totalAssigned += $type['assigned_rooms'];
}

// Get total registrations requiring accommodation
$registrationsQuery = "SELECT COUNT(*) as count FROM conference_registrations 
                     WHERE conference_id = $conferenceId AND accommodation_required = 1";
$registrationsResult = fetchRow($registrationsQuery);
$totalRequiringAccommodation = $registrationsResult ? $registrationsResult['count'] : 0;

// Calculate available rooms
$availableRooms = $totalRooms - $totalAssigned;

// Calculate accommodation coverage
$accommodationCoverage = $totalRequiringAccommodation > 0 ? 
    round(($totalCapacity / $totalRequiringAccommodation) * 100, 1) : 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>
        .stats-card {
            border-left: 4px solid;
            margin-bottom: 15px;
        }
        .stats-card.primary {
            border-left-color: #4e73df;
        }
        .stats-card.success {
            border-left-color: #1cc88a;
        }
        .stats-card.warning {
            border-left-color: #f6c23e;
        }
        .stats-card.danger {
            border-left-color: #e74a3b;
        }
        .stats-card .card-body {
            padding: 15px;
        }
        .stats-card .stats-title {
            text-transform: uppercase;
            font-size: 0.8rem;
            font-weight: bold;
            color: #4e73df;
            margin-bottom: 5px;
        }
        .stats-card .stats-value {
            font-size: 1.5rem;
            font-weight: bold;
            margin-bottom: 0;
        }
        .accommodation-assigned {
            background-color: rgba(28, 200, 138, 0.1);
        }
        .accommodation-pending {
            background-color: rgba(246, 194, 62, 0.1);
        }
    </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 Accommodation Types</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="index.php" class="btn btn-sm btn-secondary me-2">
                            <i class="fas fa-arrow-left"></i> Back to Conferences
                        </a>
                        <a href="accommodations.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-primary me-2">
                            <i class="fas fa-bed"></i> View Accommodations
                        </a>
                        <a href="room_assignments.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-info">
                            <i class="fas fa-user-check"></i> Room Assignments
                        </a>
                    </div>
                </div>
                
                <!-- Conference Info -->
                <div class="alert alert-info mb-4">
                    <h5 class="mb-1">
                        <i class="fas fa-calendar-alt me-2"></i> 
                        <?php echo htmlspecialchars($conference['name']); ?>
                    </h5>
                    <div>
                        <strong>Diocese:</strong> <?php echo htmlspecialchars($conference['diocese_name']); ?> |
                        <strong>Dates:</strong> <?php echo date('M d, Y', strtotime($conference['start_date'])); ?> - 
                        <?php echo date('M d, Y', strtotime($conference['end_date'])); ?> |
                        <strong>Venue:</strong> <?php echo htmlspecialchars($conference['venue']); ?>
                    </div>
                </div>
                
                <?php if ($message): ?>
                <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                    <?php echo $message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-xl-3 col-md-6">
                        <div class="card stats-card primary shadow h-100">
                            <div class="card-body">
                                <div class="stats-title">Total Accommodation Types</div>
                                <div class="stats-value"><?php echo count($accommodationTypes); ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="card stats-card success shadow h-100">
                            <div class="card-body">
                                <div class="stats-title">Total Capacity</div>
                                <div class="stats-value"><?php echo $totalCapacity; ?> people</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="card stats-card warning shadow h-100">
                            <div class="card-body">
                                <div class="stats-title">Available Rooms</div>
                                <div class="stats-value"><?php echo $availableRooms; ?> of <?php echo $totalRooms; ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="card stats-card <?php echo $accommodationCoverage >= 100 ? 'success' : 'danger'; ?> shadow h-100">
                            <div class="card-body">
                                <div class="stats-title">Accommodation Coverage</div>
                                <div class="stats-value"><?php echo $accommodationCoverage; ?>%</div>
                                <small><?php echo $totalRequiringAccommodation; ?> delegates need accommodation</small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <!-- Accommodation Types List -->
                    <div class="col-lg-8">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Accommodation Types</h6>
                            </div>
                            <div class="card-body">
                                <?php if (empty($accommodationTypes)): ?>
                                <div class="alert alert-warning">
                                    <i class="fas fa-exclamation-triangle me-2"></i> No accommodation types have been defined for this conference yet.
                                </div>
                                <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Name</th>
                                                <th>Capacity</th>
                                                <th>Total Rooms</th>
                                                <th>Assigned</th>
                                                <th>Available</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php $counter = 1; ?>
                                            <?php foreach ($accommodationTypes as $type): ?>
                                            <tr>
                                                <td><?php echo $counter++; ?></td>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($type['name']); ?></strong>
                                                    <?php if ($type['description']): ?>
                                                    <br><small class="text-muted"><?php echo htmlspecialchars($type['description']); ?></small>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?php echo $type['capacity']; ?> per room</td>
                                                <td><?php echo $type['total_rooms']; ?> rooms</td>
                                                <td><?php echo $type['assigned_rooms']; ?> rooms</td>
                                                <td><?php echo $type['total_rooms'] - $type['assigned_rooms']; ?> rooms</td>
                                                <td>
                                                    <a href="?conference_id=<?php echo $conferenceId; ?>&edit=<?php echo $type['id']; ?>" class="btn btn-sm btn-primary">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal<?php echo $type['id']; ?>">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                    
                                                    <!-- Delete Modal -->
                                                    <div class="modal fade" id="deleteModal<?php echo $type['id']; ?>" tabindex="-1" aria-labelledby="deleteModalLabel<?php echo $type['id']; ?>" aria-hidden="true">
                                                        <div class="modal-dialog">
                                                            <div class="modal-content">
                                                                <div class="modal-header">
                                                                    <h5 class="modal-title" id="deleteModalLabel<?php echo $type['id']; ?>">Confirm Delete</h5>
                                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                </div>
                                                                <div class="modal-body">
                                                                    Are you sure you want to delete the accommodation type <strong><?php echo htmlspecialchars($type['name']); ?></strong>?
                                                                    <?php if ($type['assigned_rooms'] > 0): ?>
                                                                    <div class="alert alert-danger mt-3">
                                                                        <i class="fas fa-exclamation-triangle me-2"></i> This accommodation type is currently assigned to <?php echo $type['assigned_rooms']; ?> delegates. You cannot delete it until all assignments are removed.
                                                                    </div>
                                                                    <?php endif; ?>
                                                                </div>
                                                                <div class="modal-footer">
                                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                                    <?php if ($type['assigned_rooms'] == 0): ?>
                                                                    <form method="post" action="">
                                                                        <input type="hidden" name="type_id" value="<?php echo $type['id']; ?>">
                                                                        <button type="submit" name="delete_accommodation_type" class="btn btn-danger">Delete</button>
                                                                    </form>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Add/Edit Accommodation Type Form -->
                    <div class="col-lg-4">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">
                                    <?php echo $editType ? 'Edit Accommodation Type' : 'Add New Accommodation Type'; ?>
                                </h6>
                            </div>
                            <div class="card-body">
                                <form method="post" action="">
                                    <?php if ($editType): ?>
                                    <input type="hidden" name="type_id" value="<?php echo $editType['id']; ?>">
                                    <?php endif; ?>
                                    
                                    <div class="mb-3">
                                        <label for="name" class="form-label">Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="name" name="name" required 
                                               value="<?php echo $editType ? htmlspecialchars($editType['name']) : ''; ?>">
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="description" class="form-label">Description</label>
                                        <textarea class="form-control" id="description" name="description" rows="3"><?php echo $editType ? htmlspecialchars($editType['description']) : ''; ?></textarea>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="capacity" class="form-label">Capacity (per room) <span class="text-danger">*</span></label>
                                        <input type="number" class="form-control" id="capacity" name="capacity" min="1" required 
                                               value="<?php echo $editType ? $editType['capacity'] : '1'; ?>">
                                        <small class="text-muted">Number of people that can stay in each room</small>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="total_rooms" class="form-label">Total Rooms <span class="text-danger">*</span></label>
                                        <input type="number" class="form-control" id="total_rooms" name="total_rooms" min="1" required 
                                               value="<?php echo $editType ? $editType['total_rooms'] : ''; ?>">
                                        <small class="text-muted">Total number of rooms available of this type</small>
                                    </div>
                                    
                                    <div class="d-grid gap-2">
                                        <button type="submit" name="save_accommodation_type" class="btn btn-primary">
                                            <i class="fas fa-save me-2"></i> <?php echo $editType ? 'Update' : 'Save'; ?> Accommodation Type
                                        </button>
                                        <?php if ($editType): ?>
                                        <a href="?conference_id=<?php echo $conferenceId; ?>" class="btn btn-secondary">
                                            <i class="fas fa-times me-2"></i> Cancel
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </form>
                            </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>
</body>
</html>
