<?php
include 'db.php'; // PDO connection
header('Content-Type: text/plain');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);

    if($name === '') {
        echo 'Department name cannot be empty.';
        exit;
    }

    // Check if the name already exists
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM departments WHERE name = :name");
    $stmt->execute(['name' => $name]);
    $count = $stmt->fetchColumn();

    if($count > 0) {
        echo 'duplicate'; // special keyword for JS
        exit;
    }

    // Insert into database
    $stmt = $pdo->prepare("INSERT INTO departments (name) VALUES (:name)");
    try {
        $stmt->execute(['name' => $name]);
        echo 'Department added successfully!';
    } catch (Exception $e) {
        echo 'Error adding department: ' . htmlspecialchars($e->getMessage());
    }
}
?>
