<?php
include "config.php"; // Ensure this connects to your DB

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $s_name = mysqli_real_escape_string($con, $_POST['s_name']);

    // Check if subject name already exists
    $checkQuery = "SELECT * FROM subject WHERE s_name = '$s_name'";
    $result = mysqli_query($con, $checkQuery);

    if (mysqli_num_rows($result) > 0) {
        // Subject exists, update the existing record if needed (here we assume no new data, just refreshing)
        $updateQuery = "UPDATE subject SET s_name = '$s_name' WHERE s_name = '$s_name'";
        if (mysqli_query($con, $updateQuery)) {
            echo "Existing subject name updated successfully.";
            // Optionally redirect
            echo '<script>window.location.href = "subject.php";</script>';
            exit();
        } else {
            echo "Error while updating: " . mysqli_error($con);
        }
    } else {
        // Insert new subject (id should be auto-increment if not provided)
        $insertQuery = "INSERT INTO subject (s_name) VALUES ('$s_name')";
        if (mysqli_query($con, $insertQuery)) {
            echo "New subject inserted successfully.";
            // Optionally redirect
            echo '<script>window.location.href = "subject.php";</script>';
            exit();
        } else {
            echo "Error while inserting: " . mysqli_error($con);
        }
    }
}
?>