<?php
session_start();
require_once 'db.php';

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

$pageTitle = 'Assignments - Hostel Management';
include_once '_header.php';
include_once '_sidebar.php';
?>
<main class="container-fluid" id="appContent">
    <h1 class="mb-4">Student Assignments</h1>

    <!-- Assignment Form -->
    <?php if ($_SESSION['is_super_admin'] == 1): ?>
    <div class="card mb-4">
        <div class="card-header">Assign Hostel, Floor, Room, and Bed to Student</div>
        <div class="card-body">
            <form class="row g-3" method="POST" action="assign_student_action.php">
                <!-- Class -->
                <div class="col-md-6">
                    <label class="form-label">Select Class</label>
                    <select class="form-select" id="classSelect" required>
                        <option value="">Choose Class...</option>
                        <?php
                        $classes = $conn->query("SELECT DISTINCT class_grade FROM students ORDER BY class_grade ASC");
                        while ($c = $classes->fetch_assoc()) {
                            echo "<option value='".htmlspecialchars($c['class_grade'])."'>".htmlspecialchars($c['class_grade'])."</option>";
                        }
                        ?>
                    </select>
                </div>
                <!-- Student -->
                <div class="col-md-6">
                    <label class="form-label">Select Student</label>
                    <select class="form-select" id="studentSelect" name="unique_reg_number" required>
                        <option value="">Choose Student...</option>
                    </select>
                </div>
                <!-- Hostel -->
                <div class="col-md-6">
                    <label class="form-label">Select Hostel</label>
                    <select class="form-select" id="hostelSelect" name="hostel_id" required>
                        <option value="">Choose Hostel...</option>
                        <?php
                        $hostels = $conn->query("SELECT hostel_id, name FROM hostels WHERE status='active' ORDER BY name ASC");
                        while ($h = $hostels->fetch_assoc()) {
                            echo "<option value='{$h['hostel_id']}'>".htmlspecialchars($h['name'])."</option>";
                        }
                        ?>
                    </select>
                </div>
                <!-- Floor -->
                <div class="col-md-6">
                    <label class="form-label">Select Floor</label>
                    <select class="form-select" id="floorSelect" name="floor_id" required>
                        <option value="">Choose Floor...</option>
                    </select>
                </div>
                <!-- Room -->
                <div class="col-md-6">
                    <label class="form-label">Select Room</label>
                    <select class="form-select" id="roomSelect" name="room_id" required>
                        <option value="">Choose Room...</option>
                    </select>
                </div>
                <!-- Bed -->
                <div class="col-md-6">
                    <label class="form-label">Select Bed</label>
                    <select class="form-select" id="bedSelect" name="bed_id" required>
                        <option value="">Choose Bed...</option>
                    </select>
                </div>
                <div class="col-12 text-end">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-user-plus"></i> Assign Student</button>
                </div>
            </form>
        </div>
    </div>
    <?php else: ?>
        <div class="alert alert-warning">You have read-only access. Only Super Admin can assign students.</div>
    <?php endif; ?>

    <!-- Current Assignments -->
    <div class="card">
        <div class="card-header">Assignments History</div>
        <div class="card-body table-responsive">
            <table id="assignmentsTable" class="table table-striped table-hover align-middle">
                <thead>
                <tr>
                    <th>Student</th>
                    <th>Reg. No.</th>
                    <th>Hostel</th>
                    <th>Floor</th>
                    <th>Room</th>
                    <th>Bed</th>
                    <th>Assigned Date</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
                </thead>
                <tbody>
                <?php
                $sql = "SELECT sa.assignment_id, s.full_name, s.unique_reg_number, 
                               h.name AS hostel_name, f.floor_number, r.room_number, b.bed_number, 
                               sa.assigned_date, sa.status
                        FROM student_assignments sa
                        JOIN students s ON sa.unique_reg_number = s.unique_reg_number
                        JOIN beds b ON sa.bed_id = b.bed_id
                        JOIN rooms r ON b.room_id = r.room_id
                        JOIN floors f ON r.floor_id = f.floor_id
                        JOIN hostels h ON f.hostel_id = h.hostel_id
                        ORDER BY sa.assigned_date DESC";
                $res = $conn->query($sql);
                while ($row = $res->fetch_assoc()):
                    $badge = ($row['status'] == 'assigned') ? 'bg-success' : 'bg-secondary';
                ?>
                    <tr>
                        <td><?= htmlspecialchars($row['full_name']) ?></td>
                        <td><?= htmlspecialchars($row['unique_reg_number']) ?></td>
                        <td><?= htmlspecialchars($row['hostel_name']) ?></td>
                        <td><?= htmlspecialchars($row['floor_number']) ?></td>
                        <td><?= htmlspecialchars($row['room_number']) ?></td>
                        <td><?= htmlspecialchars($row['bed_number']) ?></td>
                        <td><?= htmlspecialchars($row['assigned_date']) ?></td>
                        <td>
                            <span class="badge <?= $badge ?> rounded-pill status-badge">
                                <?= ucfirst($row['status']) ?>
                            </span>
                        </td>
                        <td>
                            <a href="view_student_profile.php?reg=<?= urlencode($row['unique_reg_number']) ?>" class="btn btn-sm btn-info me-1">View</a>
                            <?php if ($_SESSION['is_super_admin'] == 1): ?>
                                <?php if ($row['status'] === 'assigned'): ?>
                                    <button 
                                        type="button"
                                        class="btn btn-sm btn-danger vacate-btn"
                                        data-id="<?= (int)$row['assignment_id'] ?>"
                                        data-student="<?= htmlspecialchars($row['full_name']) ?>">
                                        Vacate
                                    </button>
                                <?php else: ?>
                                    <button type="button" class="btn btn-sm btn-outline-secondary" disabled>Vacated</button>
                                <?php endif; ?>
                            <?php else: ?>
                                <button type="button" class="btn btn-sm btn-outline-dark" disabled>Read Only</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>

<script>
/* Dependent dropdowns */
$('#classSelect').on('change', function(){
    var selectedClass = $(this).val();
    $('#studentSelect').html('<option>Loading...</option>');
    if(selectedClass){
        $.get('get_students_by_class.php', {class_grade: selectedClass}, function(data){
            $('#studentSelect').html(data);
        }).fail(function(){
            $('#studentSelect').html('<option value="">Error loading students</option>');
        });
    } else {
        $('#studentSelect').html('<option value="">Choose Student...</option>');
    }
});
$('#hostelSelect').on('change', function(){
    var hostel_id = $(this).val();
    $('#floorSelect').html('<option>Loading...</option>');
    $.get('get_floors.php', {hostel_id: hostel_id}, function(data){
        $('#floorSelect').html(data);
        $('#roomSelect').html('<option value="">Choose Room...</option>');
        $('#bedSelect').html('<option value="">Choose Bed...</option>');
    });
});
$('#floorSelect').on('change', function(){
    var floor_id = $(this).val();
    $('#roomSelect').html('<option>Loading...</option>');
    $.get('get_rooms.php', {floor_id: floor_id}, function(data){
        $('#roomSelect').html(data);
        $('#bedSelect').html('<option value="">Choose Bed...</option>');
    });
});
$('#roomSelect').on('change', function(){
    var room_id = $(this).val();
    $('#bedSelect').html('<option>Loading...</option>');
    $.get('get_beds.php', {room_id: room_id}, function(data){
        $('#bedSelect').html(data);
    });
});

/* DataTable */
$(document).ready(function() {
    $('#assignmentsTable').DataTable({
        responsive: true,
        scrollX: true,
        dom: '<"d-flex justify-content-between align-items-center mb-3"lBf>rtip',
        buttons: [
            { extend: 'excelHtml5', title: 'Assignments_History', className: 'btn btn-success btn-sm me-2' },
            { extend: 'print', title: 'Assignments_History', className: 'btn btn-info btn-sm' }
        ],
        lengthMenu: [
            [10, 25, 50, 100, -1],
            [10, 25, 50, 100, "All"]
        ],
        pageLength: 10
    });
    $('.dt-buttons').addClass('d-flex gap-2');
});

/* Vacate Handler (only super admin has button) */
$(document).on('click', '.vacate-btn', function(){
    var $btn = $(this);
    var assignmentId = $btn.data('id');
    var studentName  = $btn.data('student');
    Swal.fire({
        title: 'Vacate Bed?',
        text: 'Do you want to vacate bed for ' + studentName + '?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Vacate'
    }).then(function(result){
        if (result.isConfirmed) {
            $.ajax({
                url: 'vacate_bed.php',
                method: 'POST',
                dataType: 'json',
                data: { id: assignmentId },
                success: function(resp){
                    if (resp && resp.success) {
                        var row = $btn.closest('tr');
                        row.find('.status-badge')
                           .removeClass('bg-success')
                           .addClass('bg-secondary')
                           .text('Vacated');
                        $btn.removeClass('btn-danger vacate-btn')
                            .addClass('btn-outline-secondary')
                            .prop('disabled', true)
                            .text('Vacated');
                        Swal.fire('Done', resp.message, 'success');
                    } else {
                        Swal.fire('Error', resp.message || 'Failed to vacate.', 'error');
                    }
                },
                error: function(xhr){
                    Swal.fire('Error', 'Server error: ' + xhr.responseText, 'error');
                }
            });
        }
    });
});
</script>
<?php include_once 'footer.php'; ?>
