<?php
include "../../include/auth.php"; // Authentication
include "../../include/lskfjwfe.php"; // Database connection

header('Content-Type: application/json');

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Validate required fields
if (!isset($_POST['id'], $_POST['user_display_name'], $_POST['userrole'], $_POST['stationid'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit();
}

// Sanitize input
$user_id = intval($_POST['id']);
$new_username = trim($_POST['user_display_name']); // FIX: Using renamed field
$new_userrole = intval($_POST['userrole']);
$new_stationid = ($_POST['stationid'] === '' || $_POST['stationid'] === null) ? null : intval($_POST['stationid']);

// Ensure the user exists and fetch old data
$sql_check = "SELECT username, userrole FROM users WHERE id = ?";
$stmt_check = $db->prepare($sql_check);
$stmt_check->bind_param("i", $user_id);
$stmt_check->execute();
$result_check = $stmt_check->get_result();
if ($result_check->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'User not found']);
    exit();
}
$old_user_data = $result_check->fetch_assoc();
$old_username = $old_user_data['username'];
$old_userrole_id = $old_user_data['userrole'];
$stmt_check->close();

// Fetch role names for logging
$sql_role_old = "SELECT role_name FROM user_roles WHERE role_id = ?";
$stmt_role_old = $db2->prepare($sql_role_old);
$stmt_role_old->bind_param("i", $old_userrole_id);
$stmt_role_old->execute();
$result_role_old = $stmt_role_old->get_result();
$old_role_name = $result_role_old->fetch_assoc()['role_name'] ?? "Unknown";
$stmt_role_old->close();

$sql_role_new = "SELECT role_name FROM user_roles WHERE role_id = ?";
$stmt_role_new = $db2->prepare($sql_role_new);
$stmt_role_new->bind_param("i", $new_userrole);
$stmt_role_new->execute();
$result_role_new = $stmt_role_new->get_result();
$new_role_name = $result_role_new->fetch_assoc()['role_name'] ?? "Unknown";
$stmt_role_new->close();

// Update user in the database
$sql_update = "UPDATE users SET username = ?, userrole = ?, stationid = ? WHERE id = ?";
$stmt_update = $db->prepare($sql_update);
$stmt_update->bind_param("siii", $new_username, $new_userrole, $new_stationid, $user_id);
$update_success = $stmt_update->execute();

if ($update_success) {
    // Log the change
    $admin_username = $_SESSION['username'];
    $log_action = "Updated user details";
    $log_message = "User Update: $old_username ($old_role_name) → $new_username ($new_role_name)";

    // Ensure UTF-8 encoding only for this query
    $db2->query("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");

    $log_sql = "INSERT INTO settings_log (username, action, setting_name, old_value, new_value, timestamp)
                VALUES (?, ?, 'User Update', ?, ?, NOW())";
    
    $stmt_log = $db2->prepare($log_sql);

    if (!$stmt_log) {
        die(json_encode(['success' => false, 'message' => 'Log Statement Error: ' . $db2->error]));
    }

    $stmt_log->bind_param("ssss", $admin_username, $log_action, $log_message, $new_role_name);
    $execute_log = $stmt_log->execute();

    if (!$execute_log) {
        die(json_encode(['success' => false, 'message' => 'Log Execution Error: ' . $stmt_log->error]));
    }

    $stmt_log->close();

    echo json_encode(['success' => true, 'message' => 'User updated successfully']);
}

?>
