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

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

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

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

// Get updated values
$id = (int)$data['id'];
$class_name = trim($data['class_name']);


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

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

    // ✅ Update class details in the database
    $stmt = $pdo->prepare("UPDATE classes SET class_name = ?  WHERE id = ?");
    $stmt->execute([$class_name, $id]);

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