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

$response = ["status" => "error", "message" => "Unknown error"];
$degreeId = $_POST['id'] ?? $_GET['id'] ?? '';
$name = $_POST['name'] ?? '';

//Insert Values
$newname = $_POST['newname'] ?? '';
try {
    if ($degreeId && $name) {
        // Update Degree
        $sql = "UPDATE tbldegree 
                SET degree_name = :name
                WHERE degree_id = :id";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':id', $degreeId);

        if ($stmt->execute()) {
            $response = ["status" => "success", "message" => "Degree updated successfully"];
        } else {
            $response = ["status" => "error", "message" => "Failed to update degree"];
        }
    } else if ($newname) {
        // 🔹 Insert Department
        $sql = "INSERT INTO tbldegree (degree_name) 
            VALUES (:newname)";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':newname', $newname);

        if ($stmt->execute()) {
            $response = ["status" => "success", "message" => "Department inserted successfully"];
        } else {
            $response = ["status" => "error", "message" => "Failed to insert department"];
        }
    } else {
        // Fetch degrees
        $sql = "SELECT degree_id, degree_name FROM tbldegree ORDER BY degree_name ASC";
        $stmt = $dbh->prepare($sql);
        $stmt->execute();

        $degrees = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($degrees && count($degrees) > 0) {
            $response = [
                "status" => "success",
                "data" => $degrees
            ];
        } else {
            $response = [
                "status" => "error",
                "message" => "No degrees found"
            ];
        }
    }
} catch (Exception $e) {
    $response = [
        "status" => "error",
        "message" => $e->getMessage()
    ];
}

// 🔹 Echo only once at the end
echo json_encode($response);
exit;
