<?php
header("Content-Type: application/json");
require_once '../config/db.php';

$id = intval($_POST['id']);
$user_name = $_POST['user_name'];
$role = $_POST['role'];
$mobile = $_POST['mobile_number'];
$user_id = !empty($_POST['user_id']) ? intval($_POST['user_id']) : null;

// Handle optional password update
$password_update = "";
if (!empty($_POST['password'])) {
    $hashed = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $password_update = ", password = '$hashed'";
}

// Check for duplicate username (excluding current user)
$check = $conn->prepare("SELECT id FROM team_grovia WHERE user_name = ? AND id != ?");
$check->bind_param("si", $user_name, $id);
$check->execute();
if ($check->get_result()->num_rows > 0) {
    echo json_encode(["success" => false, "message" => "Username '$user_name' is taken by another member."]);
    exit();
}

$sql = "UPDATE team_grovia SET 
        user_name = ?, 
        role = ?, 
        mobile_number = ?, 
        user_id = ? 
        $password_update 
        WHERE id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sssii", $user_name, $role, $mobile, $user_id, $id);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Team member '$user_name' updated successfully."]);
} else {
    echo json_encode(["success" => false, "message" => "Database Error: " . $conn->error]);
}