<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_admin.php');

if(isset($_POST['post_class'])) {
    try {
        $class = strip_tags($_POST['class']);
        $subclass = strip_tags($_POST['subclass']);
        
        // Check if class already exists
        $STH = $DBH->prepare("SELECT id FROM tbl_class WHERE class = ? AND subclass = ?");
        $STH->execute(array($class, $subclass));
        $existing_class = $STH->fetch(PDO::FETCH_ASSOC);
        
        if($existing_class) {
            // Update existing class
            sql($DBH, "UPDATE tbl_class SET class = ?, subclass = ? WHERE id = ?", 
                array($class, $subclass, $existing_class['id']));
            $_SESSION['msg'] = "post";
        } else {
            // Create new class - let database handle auto-increment
            sql($DBH, "INSERT INTO tbl_class (class, subclass) VALUES (?, ?)", 
                array($class, $subclass));
            $_SESSION['msg'] = "post";
        }
        
        header("Location: post_classes.php");
        exit;
    } catch(PDOException $e) { 
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
        $_SESSION['msg'] = "failed";
        $_SESSION['error_message'] = $e->getMessage();
        header("Location: post_classes.php");
        exit;
    }
} else {
    $_SESSION['msg'] = "failed";
    $_SESSION['error_message'] = "Invalid request";
    header("Location: post_classes.php");
    exit;
}
?>