<?php 
include 'includes/header.php';
include 'includes/db.php';
?>

<section class="departments-list-section">
    <h2 class="section-title">All Departments</h2>
    <div class="departments-list-container">
        <?php
        $result = $conn->query("SELECT * FROM departments ORDER BY id DESC");
        if ($result->num_rows > 0):
            while($dept = $result->fetch_assoc()):
                $deptId = $dept['id'];

                // Get first image
                $imgResult = $conn->query("SELECT image_path FROM department_images WHERE department_id=$deptId ORDER BY id ASC LIMIT 1");
                $thumb = ($imgResult->num_rows > 0) ? $imgResult->fetch_assoc()['image_path'] : 'assets/images/no-image.jpg';

                // Short description
                $shortDesc = substr(strip_tags($dept['description']), 0, 120) . '...';
        ?>
        <div class="department-card">
            <div class="department-thumb">
                <img src="<?= htmlspecialchars($thumb) ?>" alt="<?= htmlspecialchars($dept['name']) ?>">
            </div>
            <div class="department-content">
                <h3><?= htmlspecialchars($dept['name']) ?></h3>
                <p><?= $shortDesc ?></p>
                <a href="department-details.php?id=<?= $deptId ?>" class="read-more">Read More →</a>
            </div>
        </div>
        <?php
            endwhile;
        else:
            echo "<p class='no-departments'>No departments available.</p>";
        endif;
        ?>
    </div>
</section>

<style>
.departments-list-section {
    background: #f8f9fa;
    padding: 60px 0;
}

.section-title {
    text-align: center;
    font-size: 2rem;
    margin-bottom: 40px;
    color: #1a237e;
}

.departments-list-container {
    display: flex;
    flex-wrap: wrap;
    gap: 30px;
    justify-content: center;
}

.department-card {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    width: 280px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    transition: transform 0.3s;
}

.department-card:hover {
    transform: scale(1.03);
}

.department-thumb img {
    width: 100%;
    height: 180px;
    object-fit: cover;
}

.department-content {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.department-content h3 {
    margin: 0;
    color: #1a237e;
    font-size: 1.2rem;
}

.department-content p {
    font-size: 0.95rem;
    color: #555;
    line-height: 1.4;
}

.read-more {
    align-self: flex-start;
    color: #007bff;
    font-weight: bold;
    text-decoration: none;
    transition: 0.3s;
}

.read-more:hover {
    text-decoration: underline;
}

.no-departments {
    text-align: center;
    color: #777;
    font-size: 1rem;
}
</style>

<?php include 'includes/footer.php'; ?>
