<?php
session_start();
require '../includes/config.php';

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: index.php');
    exit;
}

$error = '';
$success = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $class_name = trim($_POST['class_name']);
    $class_id = $_POST['class_id'] ?? null;

    if (empty($class_name)) {
        $error = "Class name is required.";
    } else {
        if ($class_id) {
            // Update class
            $query = "UPDATE classes SET class_name = ? WHERE class_id = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'si', $class_name, $class_id);
            if (mysqli_stmt_execute($stmt)) {
                $success = "Class updated successfully!";
            } else {
                $error = "Failed to update class: " . mysqli_error($conn);
            }
        } else {
            // Create class
            $query = "INSERT INTO classes (class_name) VALUES (?)";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 's', $class_name);
            if (mysqli_stmt_execute($stmt)) {
                $success = "Class created successfully!";
            } else {
                $error = "Failed to create class: " . mysqli_error($conn);
            }
        }
    }
}

// Handle delete
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $class_id = $_GET['delete'];
    $query = "DELETE FROM classes WHERE class_id = ?";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, 'i', $class_id);
    if (mysqli_stmt_execute($stmt)) {
        $success = "Class deleted successfully!";
    } else {
        $error = "Failed to delete class: " . mysqli_error($conn);
    }
}

// Get all classes
$classes = mysqli_fetch_all(mysqli_query($conn, "SELECT * FROM classes"), MYSQLI_ASSOC);

// Get class for editing
$edit_class = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $query = "SELECT * FROM classes WHERE class_id = ?";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, 'i', $_GET['edit']);
    mysqli_stmt_execute($stmt);
    $edit_class = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manage Classes</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/manage.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Manage Classes</h2>
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <!-- Create/Edit Form -->
        <form method="POST">
            <div class="form-group">
                <label>Class Name</label>
                <input type="text" name="class_name" class="form-control" value="<?php echo $edit_class ? htmlspecialchars($edit_class['class_name']) : ''; ?>" required>
                <?php if ($edit_class): ?>
                    <input type="hidden" name="class_id" value="<?php echo $edit_class['class_id']; ?>">
                <?php endif; ?>
            </div>
            <button type="submit" class="btn btn-primary"><?php echo $edit_class ? 'Update Class' : 'Create Class'; ?></button>
            <?php if ($edit_class): ?>
                <a href="class_manage.php" class="btn btn-secondary">Cancel</a>
            <?php endif; ?>
        </form>

        <!-- Class List -->
        <h3>Class List</h3>
        <?php if (empty($classes)): ?>
            <p>No classes found.</p>
        <?php else: ?>
            <table class="table">
                <thead>
                    <tr>
                        <th>Class Name</th>
                        <th>Created At</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($classes as $class): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($class['class_name']); ?></td>
                            <td><?php echo $class['created_at']; ?></td>
                            <td>
                                <a href="?edit=<?php echo $class['class_id']; ?>" class="btn btn-primary btn-sm">Edit</a>
                                <a href="?delete=<?php echo $class['class_id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?');">Delete</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
        <a href="dashboard.php" class="btn btn-secondary mt-3">Back to Dashboard</a>
    </div>
</body>
</html>