<?php
// hostels.php - Hostels Management Page
session_start();

// Check if the admin is NOT logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

$pageTitle = 'Hostels - Hostel Management';
require_once 'config.php'; // Include the database configuration
include_once '_header.php';
include_once '_sidebar.php';

// --- PHP Logic to Fetch Hostels Data ---
$hostels = []; // Initialize an empty array to hold hostel data
try {
    // Prepare a SELECT statement to retrieve all hostels
   $sql = "SELECT *, name AS hostel_name FROM hostels ORDER BY name ASC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $hostels = $stmt->fetchAll(PDO::FETCH_ASSOC); // Fetch all results as an associative array
} catch (PDOException $e) {
    // Log the error for debugging purposes (don't show detailed error to user in production)
    error_log("Error fetching hostels: " . $e->getMessage());
    // You might want to display a user-friendly error message on the page
    $errorMessage = "Could not load hostels data. Please try again later.";
}
?>
    <main class="container-fluid" id="appContent">
        <h5 class="mb-4">Hostel Management</h5>

        <!-- Button to Toggle Add New Hostel Form -->
        <div class="d-flex justify-content-end mb-3">
            <button class="btn btn-primary" id="toggleAddHostelFormBtn">
                <i class="fas fa-plus me-2"></i> Add New Hostel
            </button>
        </div>

        <!-- Add Hostel Form -->
        <div class="card mb-4" id="addHostelFormCard" style="display: none;">
            <div class="card-header">
                Add New Hostel
            </div>
            <div class="card-body">
                <form id="addHostelForm">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="hostelName" class="form-label">Hostel Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="hostelName" name="hostelName" placeholder="e.g., Green Valley Hostel" required>
                        </div>
                        <div class="col-md-6">
                            <label for="contactPerson" class="form-label">Contact Person <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="contactPerson" name="contactPerson" placeholder="e.g., John Doe" required>
                        </div>
                        <div class="col-md-6">
                            <label for="contactNumber" class="form-label">Contact Number <span class="text-danger">*</span></label>
                            <input type="tel" class="form-control" id="contactNumber" name="contactNumber" placeholder="e.g., +91-9876543210" required>
                        </div>
                        <div class="col-md-6">
                            <label for="email" class="form-label">Email (Optional)</label>
                            <input type="email" class="form-control" id="email" name="email" placeholder="e.g., info@hostel.com">
                        </div>
                        <div class="col-12">
                            <label for="address" class="form-label">Address <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="address" name="address" rows="3" placeholder="Street, Locality" required></textarea>
                        </div>
                        <div class="col-md-4">
                            <label for="city" class="form-label">City <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="city" name="city" placeholder="e.g., Kota" required>
                        </div>
                        <div class="col-md-4">
                            <label for="state" class="form-label">State <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="state" name="state" placeholder="e.g., Rajasthan" required>
                        </div>
                        <div class="col-md-4">
                            <label for="pincode" class="form-label">Pincode <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="pincode" name="pincode" placeholder="e.g., 324001" required>
                        </div>
                        <div class="col-12">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="hostelStatus" name="hostelStatus" checked>
                                <label class="form-check-label" for="hostelStatus">Active Hostel</label>
                            </div>
                        </div>
                        <div class="col-12 text-end">
                            <button type="submit" class="btn btn-primary">Add Hostel</button>
                        </div>
                    </div>
                </form>
                <div id="hostelMessage" class="mt-3 alert d-none" role="alert">
                    <!-- Message will be displayed here -->
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                View/Manage Hostels
            </div>
            <div class="card-body">
                <?php if (isset($errorMessage)): ?>
                    <div class="alert alert-danger" role="alert">
                        <?php echo htmlspecialchars($errorMessage); ?>
                    </div>
                <?php else: ?>
                    <?php if (empty($hostels)): ?>
                        <div class="alert alert-info" role="alert">
                            No hostels found. Click "Add New Hostel" to get started!
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Hostel Name</th>
                                        <th>Contact Person</th>
                                        <th>Contact No.</th>
                                        <th>Address</th>
                                        <th>City</th>
                                        <th>State</th>
                                        <th>Pincode</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($hostels as $hostel): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($hostel['hostel_id']); ?></td>
                                            <td><?php echo htmlspecialchars($hostel['hostel_name']); ?></td>
                                            <td><?php echo htmlspecialchars($hostel['contact_person']); ?></td>
                                            <td><?php echo htmlspecialchars($hostel['contact_number']); ?></td>
                                            <td><?php echo htmlspecialchars($hostel['address']); ?></td>
                                            <td><?php echo htmlspecialchars($hostel['city']); ?></td>
                                            <td><?php echo htmlspecialchars($hostel['state']); ?></td>
                                            <td><?php echo htmlspecialchars($hostel['pincode']); ?></td>
                                            <td>
                                                <?php
                                                $statusClass = ($hostel['status'] === 'active') ? 'bg-success' : 'bg-danger';
                                                ?>
                                                <span class="badge <?php echo $statusClass; ?> rounded-pill">
                                                    <?php echo htmlspecialchars(ucfirst($hostel['status'])); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <button class="btn btn-sm btn-warning rounded-pill me-1 edit-hostel-btn" data-id="<?php echo htmlspecialchars($hostel['hostel_id']); ?>">
                                                    <i class="fas fa-edit"></i> Edit
                                                </button>
                                                <button class="btn btn-sm btn-danger rounded-pill delete-hostel-btn" data-id="<?php echo htmlspecialchars($hostel['hostel_id']); ?>" data-name="<?php echo htmlspecialchars($hostel['hostel_name']); ?>">
                                                    <i class="fas fa-trash-alt"></i> Delete
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <!-- Edit Hostel Modal -->
    <div class="modal fade" id="editHostelModal" tabindex="-1" aria-labelledby="editHostelModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editHostelModalLabel">Edit Hostel Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editHostelForm">
                        <input type="hidden" id="editHostelId" name="hostel_id">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="editHostelName" class="form-label">Hostel Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="editHostelName" name="hostelName" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editContactPerson" class="form-label">Contact Person <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="editContactPerson" name="contactPerson" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editContactNumber" class="form-label">Contact Number <span class="text-danger">*</span></label>
                                <input type="tel" class="form-control" id="editContactNumber" name="contactNumber" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editEmail" class="form-label">Email (Optional)</label>
                                <input type="email" class="form-control" id="editEmail" name="email">
                            </div>
                            <div class="col-12">
                                <label for="editAddress" class="form-label">Address <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="editAddress" name="address" rows="3" required></textarea>
                            </div>
                            <div class="col-md-4">
                                <label for="editCity" class="form-label">City <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="editCity" name="city" required>
                            </div>
                            <div class="col-md-4">
                                <label for="editState" class="form-label">State <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="editState" name="state" required>
                            </div>
                            <div class="col-md-4">
                                <label for="editPincode" class="form-label">Pincode <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="editPincode" name="pincode" required>
                            </div>
                            <div class="col-12">
                                <label for="editHostelStatus" class="form-label">Status <span class="text-danger">*</span></label>
                                <select class="form-select" id="editHostelStatus" name="hostelStatus" required>
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </div>
                        </div>
                    </form>
                    <div id="editHostelMessage" class="mt-3 alert d-none" role="alert">
                        <!-- Message will be displayed here -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="saveEditHostelBtn">Save changes</button>
                </div>
            </div>
        </div>
    </div>


    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const toggleAddHostelFormBtn = document.getElementById('toggleAddHostelFormBtn');
            const addHostelFormCard = document.getElementById('addHostelFormCard');
            const addHostelForm = document.getElementById('addHostelForm');
            const hostelMessage = document.getElementById('hostelMessage');

            // Edit Modal elements
            const editHostelModal = new bootstrap.Modal(document.getElementById('editHostelModal'));
            const editHostelForm = document.getElementById('editHostelForm');
            const editHostelIdInput = document.getElementById('editHostelId');
            const editHostelNameInput = document.getElementById('editHostelName');
            const editContactPersonInput = document.getElementById('editContactPerson');
            const editContactNumberInput = document.getElementById('editContactNumber');
            const editEmailInput = document.getElementById('editEmail');
            const editAddressInput = document.getElementById('editAddress');
            const editCityInput = document.getElementById('editCity');
            const editStateInput = document.getElementById('editState');
            const editPincodeInput = document.getElementById('editPincode');
            const editHostelStatusSelect = document.getElementById('editHostelStatus');
            const saveEditHostelBtn = document.getElementById('saveEditHostelBtn');
            const editHostelMessage = document.getElementById('editHostelMessage');


            // Function to display messages (for Add Hostel Form)
            function showMessage(message, type) {
                hostelMessage.textContent = message;
                hostelMessage.className = `mt-3 alert alert-${type}`; // alert-success, alert-danger, etc.
                hostelMessage.classList.remove('d-none');
                setTimeout(() => {
                    hostelMessage.classList.add('d-none');
                }, 5000); // Hide message after 5 seconds
            }

            // Function to display messages (for Edit Hostel Modal)
            function showEditMessage(message, type) {
                editHostelMessage.textContent = message;
                editHostelMessage.className = `mt-3 alert alert-${type}`;
                editHostelMessage.classList.remove('d-none');
                setTimeout(() => {
                    editHostelMessage.classList.add('d-none');
                }, 5000);
            }


            // Toggle Add Hostel Form visibility
            toggleAddHostelFormBtn.addEventListener('click', function() {
                if (addHostelFormCard.style.display === 'none') {
                    addHostelFormCard.style.display = 'block';
                    toggleAddHostelFormBtn.innerHTML = '<i class="fas fa-minus me-2"></i> Hide Form';
                } else {
                    addHostelFormCard.style.display = 'none';
                    toggleAddHostelFormBtn.innerHTML = '<i class="fas fa-plus me-2"></i> Add New Hostel';
                    addHostelForm.reset(); // Clear form when hidden
                    addHostelForm.classList.remove('was-validated'); // Remove validation styling
                    hostelMessage.classList.add('d-none'); // Hide any previous messages
                }
            });

            // Handle Add Hostel Form submission
            addHostelForm.addEventListener('submit', async function(event) {
                event.preventDefault(); // Prevent actual form submission

                // Basic client-side validation (Bootstrap's built-in validation)
                if (!addHostelForm.checkValidity()) {
                    event.stopPropagation();
                    addHostelForm.classList.add('was-validated'); // Add Bootstrap validation styling
                    showMessage('Please fill all required fields correctly.', 'warning');
                    return;
                } else {
                    addHostelForm.classList.remove('was-validated'); // Remove validation styling if valid
                }

                // Collect form data
                const formData = new FormData(addHostelForm);
                const hostelData = {};
                for (let [key, value] of formData.entries()) {
                    hostelData[key] = value;
                }
                // Handle checkbox value explicitly
                hostelData['hostelStatus'] = addHostelForm.elements['hostelStatus'].checked ? 'active' : 'inactive';

                console.log('Submitting Add Hostel data:', hostelData);
                showMessage('Adding hostel...', 'info'); // Show loading message

                try {
                    const response = await fetch('add_hostel_process.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json', // Tell the server we're sending JSON
                        },
                        body: JSON.stringify(hostelData), // Convert JS object to JSON string
                    });

                    const result = await response.json(); // Parse the JSON response from the server

                    if (result.success) {
                        showMessage(result.message, 'success');
                        addHostelForm.reset(); // Clear the form on success
                        addHostelForm.classList.remove('was-validated'); // Clear validation styling
                        // IMPORTANT: Reload the page to show the newly added hostel in the table
                        // In a more advanced app, you might dynamically add the row without a full reload
                        setTimeout(() => {
                            location.reload();
                        }, 1000); // Reload after 1 second to give message time to show
                    } else {
                        showMessage(result.message, 'danger');
                    }
                } catch (error) {
                    console.error('Error adding hostel:', error);
                    showMessage('An unexpected error occurred. Please try again.', 'danger');
                }
            });

            // --- JavaScript for Action Buttons (Edit/Delete) ---
            // Event delegation for edit and delete buttons
            document.querySelector('table').addEventListener('click', async function(event) {
                // Check if the clicked element or its parent is an edit button
                if (event.target.closest('.edit-hostel-btn')) {
                    const button = event.target.closest('.edit-hostel-btn');
                    const hostelId = button.dataset.id;
                    console.log('Edit button clicked for Hostel ID:', hostelId);

                    // Fetch hostel data for editing
                    try {
                        const response = await fetch(`get_hostel_details.php?id=${hostelId}`);
                        const data = await response.json();

                        if (data.success && data.hostel) {
                            const hostel = data.hostel;
                            editHostelIdInput.value = hostel.hostel_id;
                            editHostelNameInput.value = hostel.name;
                            editContactPersonInput.value = hostel.contact_person;
                            editContactNumberInput.value = hostel.contact_number;
                            editEmailInput.value = hostel.email;
                            editAddressInput.value = hostel.address;
                            editCityInput.value = hostel.city;
                            editStateInput.value = hostel.state;
                            editPincodeInput.value = hostel.pincode;
                            editHostelStatusSelect.value = hostel.status; // 'active' or 'inactive'

                            editHostelModal.show(); // Show the modal
                            showEditMessage('', ''); // Clear any previous messages in the modal
                            editHostelForm.classList.remove('was-validated'); // Clear validation styling
                        } else {
                            showEditMessage(data.message || 'Failed to fetch hostel details.', 'danger');
                        }
                    } catch (error) {
                        console.error('Error fetching hostel details:', error);
                        showEditMessage('An error occurred while fetching details.', 'danger');
                    }
                }

                // Check if the clicked element or its parent is a delete button
                if (event.target.closest('.delete-hostel-btn')) {
                    const button = event.target.closest('.delete-hostel-btn');
                    const hostelId = button.dataset.id;
                    const hostelName = button.dataset.name;

                    // Use a custom alert/confirm for better UI, as window.confirm is blocking
                    const confirmDelete = confirm('Are you sure you want to delete hostel "' + hostelName + '" (ID: ' + hostelId + ')? This action cannot be undone.');

                    if (confirmDelete) {
                        console.log('Confirmed deletion for Hostel ID:', hostelId);
                        showMessage('Deleting hostel...', 'info'); // Show loading message on main page

                        try {
                            const response = await fetch('delete_hostel_process.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                body: JSON.stringify({ hostel_id: hostelId }),
                            });

                            const result = await response.json();

                            if (result.success) {
                                showMessage(result.message, 'success');
                                // Reload the page to show updated data
                                setTimeout(() => {
                                    location.reload();
                                }, 1000);
                            } else {
                                showMessage(result.message, 'danger');
                            }
                        } catch (error) {
                            console.error('Error deleting hostel:', error);
                            showMessage('An unexpected error occurred during deletion. Please try again.', 'danger');
                        }
                    } else {
                        showMessage('Deletion cancelled.', 'secondary');
                    }
                }
            });

            // Handle Save Changes button in Edit Modal
            saveEditHostelBtn.addEventListener('click', async function() {
                // Basic client-side validation for edit form
                if (!editHostelForm.checkValidity()) {
                    event.stopPropagation();
                    editHostelForm.classList.add('was-validated');
                    showEditMessage('Please fill all required fields correctly.', 'warning');
                    return;
                } else {
                    editHostelForm.classList.remove('was-validated');
                }

                const formData = new FormData(editHostelForm);
                const updatedHostelData = {};
                for (let [key, value] of formData.entries()) {
                    updatedHostelData[key] = value;
                }
                // The status is already correctly handled by the select element's value

                console.log('Submitting updated hostel data:', updatedHostelData);
                showEditMessage('Saving changes...', 'info');

                try {
                    const response = await fetch('update_hostel_process.php', { // This will be our new PHP file
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(updatedHostelData),
                    });

                    const result = await response.json();

                    if (result.success) {
                        showEditMessage(result.message, 'success');
                        // Reload the page to show updated data in the table
                        setTimeout(() => {
                            editHostelModal.hide(); // Hide modal first
                            location.reload();
                        }, 1000);
                    } else {
                        showEditMessage(result.message, 'danger');
                    }
                } catch (error) {
                    console.error('Error updating hostel:', error);
                    showEditMessage('An unexpected error occurred while saving changes. Please try again.', 'danger');
                }
            });
        });
    </script>
<?php include_once 'footer.php'; ?>
