<?php
session_start();
include '../../includes/db_connection.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: /school_management/public/index.php");
    exit();
}

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $class_name = $_POST['class_name'];
    
    // Check if class_name is not empty
    if (!empty($class_name)) {
        $sql = "INSERT INTO classes (class_name) VALUES (?)";
        $stmt = $conn->prepare($sql);
        
        if ($stmt === false) {
            $error = "Error preparing statement: " . $conn->error;
        } else {
            $stmt->bind_param("s", $class_name);
            if ($stmt->execute()) {
                $message = "Class added successfully!";
            } else {
                $error = "Error: " . $stmt->error;
            }
            $stmt->close();
        }
    } else {
        $error = "Class name cannot be empty.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Class</title>
    <link rel="stylesheet" href="/school_management/public/css/style.css">
</head>
<body>
<div class="header">
    <h1>School Management System</h1>
    <div class="nav">
        <a href="/school_management/public/dashboard.php">Dashboard</a>
        <a href="/school_management/public/students/students_list.php">Students</a>
        <a href="/school_management/public/teachers/teachers_list.php">Teachers</a>
        <a href="/school_management/public/fees/fee_collection.php">Fees</a>
        <a href="/school_management/public/subjects/subjects_list.php">Subjects</a>
        <a href="/school_management/public/classes/classes_list.php">Classes</a>
        <a href="/school_management/public/exam_results/add_exam_result.php">Exams</a>
        <a href="/school_management/public/attendance/record_attendance.php">Attendance</a>
        <a href="/school_management/public/change_password.php">Change Password</a>
        <a href="/school_management/public/logout.php">Logout</a>
    </div>
</div>

<div class="content">
    <div class="container">
        <h2>Add New Class</h2>
        <?php if ($message): ?>
            <p style='color:green;'><?php echo $message; ?></p>
        <?php endif; ?>
        <?php if ($error): ?>
            <p style='color:red;'><?php echo $error; ?></p>
        <?php endif; ?>
        
        <form action="" method="POST">
            <label for="class_name">Class Name:</label><br>
            <input type="text" id="class_name" name="class_name" required><br><br>
            
            <button type="submit">Add Class</button>
        </form>
    </div>
    <div class="footer">
        <p>&copy; <?php echo date("Y"); ?> School Management System. All Rights Reserved.</p>
    </div>
</div>
</body>
</html>