<?php
require_once '../includes/init.php';

$user = new User($pdo);
if (!$user->isLoggedIn() || !$user->isTeacher()) {
    header("Location: ../index.php");
    exit;
}

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_class'])) {
        $name = trim($_POST['class_name']);
        if (!empty($name)) {
            $stmt = $pdo->prepare("INSERT INTO classes (class_name) VALUES (?)");
            try {
                $stmt->execute([$name]);
                $message = "Class added successfully.";
            } catch (PDOException $e) {
                $error = "Error adding class: " . $e->getMessage();
            }
        }
    } elseif (isset($_POST['delete_class'])) {
        $class_id = $_POST['class_id'];
        $stmt = $pdo->prepare("DELETE FROM classes WHERE class_id = ?");
        if ($stmt->execute([$class_id])) {
            $message = "Class deleted successfully.";
        } else {
            $error = "Failed to delete class.";
        }
    }
}

$classes = $pdo->query("SELECT * FROM classes")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Classes</title>
    <link rel="stylesheet" href="../assets/css/admin.css">
</head>
<body>
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="content">
        <?php include '../includes/page_header.php'; ?>
        <h1>Manage Classes</h1>
        <?php if ($message): ?> <div style="color: green;"><?php echo $message; ?></div> <?php endif; ?>
        <?php if ($error): ?> <div style="color: red;"><?php echo $error; ?></div> <?php endif; ?>

        <form method="POST">
            <input type="text" name="class_name" placeholder="Class Name (e.g., JSS1)" required>
            <button type="submit" name="add_class" class="btn btn-primary">Add Class</button>
        </form>

        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Class Name</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($classes as $c): ?>
                <tr>
                    <td><?php echo $c['class_id']; ?></td>
                    <td><?php echo htmlspecialchars($c['class_name']); ?></td>
                    <td>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('Delete class?');">
                            <input type="hidden" name="class_id" value="<?php echo $c['class_id']; ?>">
                            <button type="submit" name="delete_class" class="btn btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="footer">
            Designed by ferakeys
        </div>
    </div>
</body>
</html>
