<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: login.php');
    exit();
}

require_once 'db/config.php';

if (isset($_POST['id'], $_POST['name'], $_POST['bni_group_id'])) {
    $id = $_POST['id'];
    $name = trim($_POST['name']);
    $bni_group_id = trim($_POST['bni_group_id']);

    if (!empty($name) && !empty($bni_group_id)) {
        try {
            $pdo = db();
            $stmt = $pdo->prepare("UPDATE functions SET name = :name, bni_group_id = :bni_group_id WHERE id = :id");
            $stmt->execute(['name' => $name, 'bni_group_id' => $bni_group_id, 'id' => $id]);
            $_SESSION['success_message'] = "Function updated successfully.";
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error updating function: " . $e->getMessage();
        }
    }
} else {
     $_SESSION['error_message'] = "Name and group are required.";
}

header('Location: functions.php');
exit();
