<?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'];
    $pin = trim($_POST['pin'] ?? '');
    $pin_required_for_void = isset($_POST['pin_required_for_void']) ? 1 : 0;

    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 = ?, pin = ?, pin_required_for_void = ? WHERE id = ?");
            $stmt->bind_param("ssisisi", $username, $email, $role_id, $hashed_password, $pin, $pin_required_for_void, $user_id);
        } else {
            // Update without changing password
            $stmt = $conn->prepare("UPDATE users SET username = ?, email = ?, role_id = ?, pin = ?, pin_required_for_void = ? WHERE id = ?");
            $stmt->bind_param("ssisii", $username, $email, $role_id, $pin, $pin_required_for_void, $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();
?>