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

header('Content-Type: application/json');

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

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

        if ($designationId > 0) {
            // ✅ Update designation
            $sql = "UPDATE tblstaffdesignation 
                    SET designation_name = :designationName 
                    WHERE designation_id = :designationId";
            $stmt = $dbh->prepare($sql);
            $stmt->bindParam(':designationName', $designationName);
            $stmt->bindParam(':designationId', $designationId);
            $stmt->execute();

            echo json_encode(['status' => 'success', 'message' => 'Designation updated successfully']);
            exit;
        } else {
            // ✅ Insert designation
            $sql = "INSERT INTO tblstaffdesignation (designation_name) 
                    VALUES (:designationName)";
            $stmt = $dbh->prepare($sql);
            $stmt->bindParam(':designationName', $designationName);
            $stmt->execute();

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