<?php
require 'db.php';
header('Content-Type: application/json');

$data = json_decode(file_get_contents('php://input'), true);
$id = $data['id'] ?? null;
$reassign = $data['reassign_to'] ?? null;

if (!$id) exit;

$pdo->beginTransaction();

try {
    $deptName = $pdo->prepare("SELECT name FROM departments WHERE id = ?");
    $deptName->execute([$id]);
    $oldName = $deptName->fetchColumn();

    if ($reassign) {
        $update = $pdo->prepare(
            "UPDATE transactions SET department = ? WHERE department = ?"
        );
        $update->execute([$reassign, $oldName]);
    }

    $delete = $pdo->prepare("DELETE FROM departments WHERE id = ?");
    $delete->execute([$id]);

    $pdo->commit();
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
