<?php
include '../db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = (int)$_POST['user_id'];
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $role_id = (int)$_POST['role_id'];
    $password = $_POST['password'];

    if (!empty($username) && !empty($email) && !empty($role_id)) {
        // Check if username or email already exists for other users
        $check_stmt = $conn->prepare("SELECT id FROM users WHERE (username = ? OR email = ?) AND id != ?");
        $check_stmt->bind_param("ssi", $username, $email, $user_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows > 0) {
            header("Location: ../users.php?error=duplicate_user");
            exit();
        }

        // Update user
        if (!empty($password)) {
            // Update with new password
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET username = ?, email = ?, role_id = ?, password = ? WHERE id = ?");
            $stmt->bind_param("ssisi", $username, $email, $role_id, $hashed_password, $user_id);
        } else {
            // Update without changing password
            $stmt = $conn->prepare("UPDATE users SET username = ?, email = ?, role_id = ? WHERE id = ?");
            $stmt->bind_param("ssii", $username, $email, $role_id, $user_id);
        }
        
        $stmt->execute();
        $stmt->close();
        
        header("Location: ../users.php?success=user_updated");
        exit();
    } else {
        header("Location: ../users.php?error=missing_fields");
        exit();
    }
}

header("Location: ../users.php");
exit();
?>