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

$response = ["status" => "error", "message" => "Unknown error"];
$designationId = $_POST['id'] ?? $_GET['id'] ?? '';
$name = $_POST['name'] ?? '';
//Insert Values
$newname = $_POST['newname'] ?? '';
try {
    if ($designationId && $name) {
        // Update Designation
        $sql = "UPDATE tblstaffdesignation 
                SET designation_name = :name
                WHERE designation_id = :id";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':id', $designationId);

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

        if ($stmt->execute()) {
            $response = ["status" => "success", "message" => "Designation inserted successfully"];
        } else {
            $response = ["status" => "error", "message" => "Failed to insert Designation"];
        }
    } else {
        // Fetch Designations
        $sql = "SELECT designation_id, designation_name FROM tblstaffdesignation ORDER BY designation_name ASC";
        $stmt = $dbh->prepare($sql);
        $stmt->execute();

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

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

echo json_encode($response);
exit;
