<?php
require_once __DIR__ . '/db/config.php';

if (isset($_POST['edit'])) {
    $id = $_POST['id'];
    $name = $_POST['name'];
    $city = $_POST['city'] ?? null;
    $active = isset($_POST['active']) ? 1 : 0;
    $display_order = $_POST['display_order'] ?? 0;

    if (empty($name) || empty($id)) {
        $_SESSION['error_message'] = 'Name and ID are required.';
        header('Location: bni_groups.php');
        exit;
    }

    try {
        $pdo = db();
        $stmt = $pdo->prepare("UPDATE bni_groups SET name = :name, city = :city, active = :active, display_order = :display_order WHERE id = :id");
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':city', $city);
        $stmt->bindParam(':active', $active, PDO::PARAM_INT);
        $stmt->bindParam(':display_order', $display_order, PDO::PARAM_INT);
        $stmt->execute();

        $_SESSION['success_message'] = 'BNI Group updated successfully!';
    } catch (PDOException $e) {
        $_SESSION['error_message'] = 'Error updating BNI group: ' . $e->getMessage();
    }
}

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