<?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") {
    $subject_name = $_POST['subject_name'];
    
    // Check if subject_name is not empty
    if (!empty($subject_name)) {
        $sql = "INSERT INTO subjects (subject_name) VALUES (?)";
        $stmt = $conn->prepare($sql);
        
        if ($stmt === false) {
            $error = "Error preparing statement: " . $conn->error;
        } else {
            $stmt->bind_param("s", $subject_name);
            if ($stmt->execute()) {
                $message = "Subject added successfully!";
            } else {
                $error = "Error: " . $stmt->error;
            }
            $stmt->close();
        }
    } else {
        $error = "Subject 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 Subject</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>
    </div>
</div>

<div class="content">
    <div class="container">
        <h2>Add New Subject</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="subject_name">Subject Name:</label><br>
            <input type="text" id="subject_name" name="subject_name" required><br><br>
            
            <button type="submit">Add Subject</button>
        </form>
    </div>
    <div class="footer">
        <p>&copy; <?php echo date("Y"); ?> School Management System. All Rights Reserved.</p>
    </div>
</div>
</body>
</html>