<?php
session_start();
include('includes/config.php');

header('Content-Type: application/json'); // ✅ Ensure JSON response

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $degreeId   = isset($_POST['degreeId']) ? intval($_POST['degreeId']) : 0;
        $degreeName = trim($_POST['degreeName']);

        if (empty($degreeName)) {
            echo json_encode(['status' => 'error', 'message' => 'Degree name is required']);
            exit;
        }

        if ($degreeId > 0) {
            // ✅ Update degree
            $sql = "UPDATE tbldegree SET degree_name = :degreeName WHERE degree_id = :degreeId";
            $stmt = $dbh->prepare($sql);
            $stmt->bindParam(':degreeName', $degreeName);
            $stmt->bindParam(':degreeId', $degreeId);
            $stmt->execute();

            echo json_encode(['status' => 'success', 'message' => 'Degree updated successfully']);
            exit;
        } else {
            // ✅ Insert degree
            $sql = "INSERT INTO tbldegree (degree_name) VALUES (:degreeName)";
            $stmt = $dbh->prepare($sql);
            $stmt->bindParam(':degreeName', $degreeName);
            $stmt->execute();

            echo json_encode(['status' => 'success', 'message' => 'Degree added successfully']);
            exit;
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
    }
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
