<?php ob_start();
// save_permissions.php
// PHP 5.6 compatible - Insert or Edit
include("config.php");
include("config2.php");

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Get POST data
$userid = isset($_POST['userid']) ? trim($_POST['userid']) : '';
$password = isset($_POST['password']) ? trim($_POST['password']) : '';

// Collect checked permissions
$permissions = array();
foreach ($_POST as $key => $value) {
    if ($key != 'userid' && $key != 'password') {
        $permissions[] = $key;
    }
}

// Validation
if ($userid == '' || $password == '') {
    die("UserID and Password are required.");
}

// Convert permissions array to comma-separated string
$permissions_str = implode(',', $permissions);

// Hash password (PHP 5.6 compatible)
$pass_hash = md5($password);

// Check if user exists
$sql_check = "SELECT id FROM user WHERE userid = '$userid'";
$result_check = mysqli_query($conn, $sql_check);

if (mysqli_num_rows($result_check) > 0) {
    // User exists - UPDATE
    $sql_update = "UPDATE user SET password='$pass_hash', permissions='$permissions_str' WHERE userid='$userid'";
    if (mysqli_query($conn, $sql_update)) {
        echo "User updated successfully!";
    } else {
        echo "Error updating user: " . mysqli_error($conn);
    }
} else {

$user_ip = getUserIP();

    // User does not exist - INSERT
    $sql_insert = "INSERT INTO user (userid, password, permissions,suser,user_ip) VALUES ('$userid', '$pass_hash', '$permissions_str','$_SESSION[uid]', '$user_ip')";
    if (mysqli_query($conn, $sql_insert)) {
        echo "User created successfully!";
    } else {
        echo "Error creating user: " . mysqli_error($conn);
    }
}

mysqli_close($conn);

header("location:admin_user.php");
?>
