<?php
header("Content-Type: application/json");

require("../includes/config.php");

$data = json_decode(file_get_contents("php://input"), true);

// Validate class name
if (!isset($data['class_name']) || trim($data['class_name']) === "") {
    echo json_encode(["status" => "error", "message" => "Class name is required"]);
    exit;
}



// Get class name, session year, and class section (with default "A")
$class = trim($data['class_name']);

try {
    // 🔒 Check for duplicate class with the same name, session year, and section
    $check = $pdo->prepare("SELECT id FROM classes WHERE class_name = ? ");
    $check->execute([$class]);

    if ($check->rowCount() > 0) {
        echo json_encode([
            "status" => "error",
            "message" => "Class already exists for the given session year and section"
        ]);
        exit;
    }

    // ✅ Insert new class into the database
    $stmt = $pdo->prepare("INSERT INTO classes (class_name) VALUES ( ?)");
    $stmt->execute([$class]);

    echo json_encode([
        "status" => "success",
        "message" => "Class added successfully"
    ]);

} catch (Exception $e) {
    echo json_encode([
        "status" => "error",
        "message" => "Server error: " . $e->getMessage()
    ]);
}
?>