<?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['name'], $_POST['bni_group_id'])) {
    $name = trim($_POST['name']);
    $bni_group_id = trim($_POST['bni_group_id']);

    if (!empty($name) && !empty($bni_group_id)) {
        try {
            $pdo = db();
            // Get the current max display order
            $stmt = $pdo->query("SELECT MAX(display_order) FROM functions");
            $max_order = $stmt->fetchColumn();
            $new_order = $max_order + 1;

            $stmt = $pdo->prepare("INSERT INTO functions (name, bni_group_id, display_order) VALUES (:name, :bni_group_id, :display_order)");
            $stmt->execute(['name' => $name, 'bni_group_id' => $bni_group_id, 'display_order' => $new_order]);
            $_SESSION['success_message'] = "Function added successfully.";
        } catch (PDOException $e) {
            // Handle potential errors, e.g., duplicate name
            $_SESSION['error_message'] = "Error adding function: " . $e->getMessage();
        }
    }
} else {
    $_SESSION['error_message'] = "Name and group are required.";
}

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