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

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

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

        if (empty($deptName) || empty($deptCode)) {
            echo json_encode(['status' => 'error', 'message' => 'All fields are required']);
            exit;
        }

        if ($deptId > 0) {
            // ✅ Update department
            $sql = "UPDATE tbldepartment 
                    SET department_name = :deptName, department_code = :deptCode 
                    WHERE department_id = :deptId";
            $stmt = $dbh->prepare($sql);
            $stmt->bindParam(':deptName', $deptName);
            $stmt->bindParam(':deptCode', $deptCode);
            $stmt->bindParam(':deptId', $deptId);
            $stmt->execute();

            echo json_encode(['status' => 'success', 'message' => 'Department updated successfully']);
            exit;
        } else {
            // ✅ Insert department
            $sql = "INSERT INTO tbldepartment (department_name, department_code) 
                    VALUES (:deptName, :deptCode)";
            $stmt = $dbh->prepare($sql);
            $stmt->bindParam(':deptName', $deptName);
            $stmt->bindParam(':deptCode', $deptCode);
            $stmt->execute();

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