<?php
// school_admission/public/admin_manage_courses.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth_check.php';

requireRole(['super_admin']); // Only Super Admin can access this page

$message = '';
if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    unset($_SESSION['message']);
}

// Fetch all courses
$courses = [];
$sql = "SELECT course_id, course_name, course_code, description FROM courses ORDER BY course_name ASC";
$result = $conn->query($sql);

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $courses[] = $row;
    }
    $result->free();
} else {
    $message = "<div class='message error'>Error fetching courses: " . $conn->error . "</div>";
}

include __DIR__ . '/../includes/header.php';
?>

<h2 class="mt-30">Manage Courses</h2>

<?php if (!empty($message)): ?>
    <?php echo $message; ?>
<?php endif; ?>

<div class="mb-20">
    <a href="admin_add_course.php" class="btn btn-success"><i class="fas fa-plus"></i> Add New Course</a>
</div>

<?php if (empty($courses)): ?>
    <div class="message info">No courses found. Please add a new course.</div>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Course Name</th>
                <th>Course Code</th>
                <th>Description</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($courses as $course): ?>
                <tr>
                    <td data-label="ID"><?php echo htmlspecialchars($course['course_id']); ?></td>
                    <td data-label="Course Name"><?php echo htmlspecialchars($course['course_name']); ?></td>
                    <td data-label="Course Code"><?php echo htmlspecialchars($course['course_code']); ?></td>
                    <td data-label="Description"><?php echo htmlspecialchars(substr($course['description'], 0, 100)) . (strlen($course['description']) > 100 ? '...' : ''); ?></td>
                    <td data-label="Actions" class="action-links">
                        <a href="admin_edit_course.php?id=<?php echo $course['course_id']; ?>" class="btn btn-info btn-sm"><i class="fas fa-edit"></i> Edit</a>
                        <a href="admin_delete_course_action.php?id=<?php echo $course['course_id']; ?>" class="btn btn-danger btn-sm confirm-delete"><i class="fas fa-trash-alt"></i> Delete</a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>

<?php
include __DIR__ . '/../includes/footer.php';
$conn->close();
?>