<?php
// floors.php - Floors Management Page
session_start();

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

$pageTitle = 'Floors - Hostel Management';
require_once 'config.php'; // $pdo must be defined here
include_once '_header.php';
include_once '_sidebar.php';

// --- Fetch Hostels + Floors ---
$hostels = [];
$floors  = [];
try {
    // Hostels for selects
    $stmtHostels = $pdo->prepare("SELECT hostel_id, name FROM hostels ORDER BY name ASC");
    $stmtHostels->execute();
    $hostels = $stmtHostels->fetchAll(PDO::FETCH_ASSOC);

    // Floors table
    $stmtFloors = $pdo->prepare("
        SELECT f.floor_id, f.hostel_id, h.name AS hostel_name, f.floor_number, 
               COALESCE(f.description,'') AS description, COALESCE(f.total_rooms,0) AS total_rooms, f.created_at
        FROM floors f
        JOIN hostels h ON f.hostel_id = h.hostel_id
        ORDER BY h.name ASC, f.floor_number ASC
    ");
    $stmtFloors->execute();
    $floors = $stmtFloors->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("floors.php fetch error: " . $e->getMessage());
    $errorMessage = "Could not load data. Please try again later.";
}
?>
<main class="container-fluid" id="appContent">
    <h5 class="mb-4">Floor Management</h5>

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

    <!-- Add Floor Form -->
    <div class="card mb-4" id="addFloorFormCard" style="display:none;">
        <div class="card-header">Add New Floor</div>
        <div class="card-body">
            <form id="addFloorForm" novalidate>
                <div class="row g-3">
                    <div class="col-md-4">
                        <label for="selectHostelFloor" class="form-label">Select Hostel <span class="text-danger">*</span></label>
                        <select class="form-select" id="selectHostelFloor" name="hostelId" required>
                            <option value="">Choose Hostel...</option>
                            <?php foreach ($hostels as $h): ?>
                                <option value="<?php echo (int)$h['hostel_id']; ?>">
                                    <?php echo htmlspecialchars($h['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="invalid-feedback">Please select a hostel.</div>
                    </div>
                    <div class="col-md-4">
                        <label for="floorNumber" class="form-label">Floor Number <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="floorNumber" name="floorNumber" min="0" required>
                        <div class="invalid-feedback">Please enter a valid floor number.</div>
                    </div>
                    <div class="col-md-4">
                        <label for="totalRooms" class="form-label">Total Rooms on Floor</label>
                        <input type="number" class="form-control" id="totalRooms" name="totalRooms" min="0" value="0">
                    </div>
                    <div class="col-12">
                        <label for="floorDescription" class="form-label">Description (Optional)</label>
                        <input type="text" class="form-control" id="floorDescription" name="description" placeholder="e.g., Ground Floor, Girls' Wing">
                    </div>
                    <div class="col-12 text-end">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Add Floor
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Floors Table -->
    <div class="card">
        <div class="card-header">View/Manage Floors</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($floors)): ?>
                    <div class="alert alert-info" role="alert">No floors found. Add new floors using the form above.</div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table id="floorsTable" class="table table-striped table-hover align-middle display nowrap" style="width:100%">
                            <thead class="table-dark">
                                <tr>
                                    <th>ID</th>
                                    <th>Hostel</th>
                                    <th>Floor #</th>
                                    <th>Description</th>
                                    <th>Total Rooms</th>
                                    <th>Created</th>
                                    <th style="min-width:160px;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($floors as $f): ?>
                                    <tr>
                                        <td><?php echo (int)$f['floor_id']; ?></td>
                                        <td><?php echo htmlspecialchars($f['hostel_name']); ?></td>
                                        <td><?php echo (int)$f['floor_number']; ?></td>
                                        <td><?php echo htmlspecialchars($f['description'] ?: '—'); ?></td>
                                        <td><?php echo (int)$f['total_rooms']; ?></td>
                                        <td><?php echo htmlspecialchars($f['created_at']); ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-warning rounded-pill me-1 edit-floor-btn" data-id="<?php echo (int)$f['floor_id']; ?>">
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                            <button class="btn btn-sm btn-danger rounded-pill delete-floor-btn"
                                                data-id="<?php echo (int)$f['floor_id']; ?>"
                                                data-floor-number="<?php echo (int)$f['floor_number']; ?>"
                                                data-hostel-name="<?php echo htmlspecialchars($f['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 Floor Modal -->
<div class="modal fade" id="editFloorModal" tabindex="-1" aria-labelledby="editFloorModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editFloorModalLabel">Edit Floor Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="editFloorForm" novalidate>
          <input type="hidden" id="editFloorId" name="floor_id">
          <div class="row g-3">
            <div class="col-md-6">
              <label for="editHostelSelect" class="form-label">Hostel <span class="text-danger">*</span></label>
              <select class="form-select" id="editHostelSelect" name="hostelId" required>
                <option value="">Choose Hostel...</option>
                <?php foreach ($hostels as $h): ?>
                  <option value="<?php echo (int)$h['hostel_id']; ?>">
                    <?php echo htmlspecialchars($h['name']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <div class="invalid-feedback">Please select a hostel.</div>
            </div>
            <div class="col-md-6">
              <label for="editFloorNumber" class="form-label">Floor Number <span class="text-danger">*</span></label>
              <input type="number" class="form-control" id="editFloorNumber" name="floorNumber" min="0" required>
              <div class="invalid-feedback">Please enter a valid floor number.</div>
            </div>
            <div class="col-12">
              <label for="editFloorDescription" class="form-label">Description (Optional)</label>
              <textarea class="form-control" id="editFloorDescription" name="description" rows="2"></textarea>
            </div>
            <div class="col-12">
              <label for="editTotalRooms" class="form-label">Total Rooms on Floor</label>
              <input type="number" class="form-control" id="editTotalRooms" name="totalRooms" min="0">
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" id="saveEditFloorBtn">Save changes</button>
      </div>
    </div>
  </div>
</div>

<!-- JS & CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css">

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Toggle Add form
    const toggleAddBtn = document.getElementById('toggleAddFloorFormBtn');
    const addCard     = document.getElementById('addFloorFormCard');
    const addForm     = document.getElementById('addFloorForm');

    toggleAddBtn.addEventListener('click', () => {
        const visible = addCard.style.display !== 'none';
        addCard.style.display = visible ? 'none' : 'block';
        toggleAddBtn.innerHTML = visible
            ? '<i class="fas fa-plus me-2"></i> Add New Floor'
            : '<i class="fas fa-minus me-2"></i> Hide Form';
        if (visible) addForm.reset();
    });

    // DataTable
    const table = $('#floorsTable').DataTable({
        responsive: true,
        scrollX: true,
        dom: "<'row mb-2'<'col-sm-12 col-md-6'B><'col-sm-12 col-md-6'f>>" +
             "<'row mb-2'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'ip>>" +
             "t",
        buttons: [
            { extend: 'copyHtml5',  title: 'Floors' },
            { extend: 'excelHtml5', title: 'Floors' },
            { extend: 'csvHtml5',   title: 'Floors' },
            { extend: 'print',      title: 'Floors' }
        ],
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]]
    });

    // Add Floor AJAX
    addForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        if (!addForm.checkValidity()) {
            addForm.classList.add('was-validated');
            return;
        }
        const data = Object.fromEntries(new FormData(addForm).entries());
        try {
            const res = await fetch('add_floor_process.php', {
                method: 'POST', headers: {'Content-Type':'application/json'},
                body: JSON.stringify(data)
            });
            const result = await res.json();
            if (result.success) {
                Swal.fire('Success', result.message, 'success').then(()=>location.reload());
            } else {
                Swal.fire('Error', result.message, 'error');
            }
        } catch(err){ Swal.fire('Error', 'Unexpected error', 'error'); }
    });

    // Edit button
    $(document).on('click','.edit-floor-btn', async function(){
        const id = $(this).data('id');
        try {
            const res = await fetch(`get_floor_details.php?id=${id}`);
            const data = await res.json();
            if (data.success) {
                $('#editFloorId').val(data.floor.floor_id);
                $('#editHostelSelect').val(data.floor.hostel_id);
                $('#editFloorNumber').val(data.floor.floor_number);
                $('#editFloorDescription').val(data.floor.description);
                $('#editTotalRooms').val(data.floor.total_rooms);
                new bootstrap.Modal(document.getElementById('editFloorModal')).show();
            } else {
                Swal.fire('Error', data.message, 'error');
            }
        } catch(err){ Swal.fire('Error', 'Failed to load floor', 'error'); }
    });

    // Save Edit
    $('#saveEditFloorBtn').on('click', async function(){
        const form = document.getElementById('editFloorForm');
        if (!form.checkValidity()) { form.classList.add('was-validated'); return; }
        const data = Object.fromEntries(new FormData(form).entries());
        try {
            const res = await fetch('update_floor_process.php', {
                method:'POST', headers:{'Content-Type':'application/json'},
                body: JSON.stringify(data)
            });
            const result = await res.json();
            if (result.success) {
                Swal.fire('Updated', result.message, 'success').then(()=>location.reload());
            } else {
                Swal.fire('Error', result.message, 'error');
            }
        } catch(err){ Swal.fire('Error', 'Update failed', 'error'); }
    });

    // Delete button
    $(document).on('click','.delete-floor-btn', function(){
        const id = $(this).data('id');
        const floor = $(this).data('floor-number');
        const hostel = $(this).data('hostel-name');
        Swal.fire({
            title: `Delete Floor ${floor} (${hostel})?`,
            text: "This action cannot be undone.",
            icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete'
        }).then(async (res)=>{
            if(res.isConfirmed){
                try {
                    const r = await fetch('delete_floor_process.php',{
                        method:'POST', headers:{'Content-Type':'application/json'},
                        body: JSON.stringify({floor_id:id})
                    });
                    const result = await r.json();
                    if(result.success){
                        Swal.fire('Deleted', result.message, 'success').then(()=>location.reload());
                    } else {
                        Swal.fire('Error', result.message, 'error');
                    }
                } catch(err){ Swal.fire('Error','Deletion failed','error'); }
            }
        });
    });
});
</script>
<?php include_once 'footer.php'; ?>
