<?php
include("../config.php"); 
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
header("Content-Type: application/json"); 

$postData = json_decode(file_get_contents('php://input'), true);

if (!$db) {
    echo json_encode(["status" => "error", "message" => "Database connection failed"]);
    exit;
}

// Validate required fields
$requiredFields = ['firstName', 'lastName', 'email', 'phoneNumber', 'roles', 'userId'];
foreach ($requiredFields as $field) {
    if (!isset($postData[$field]) || empty($postData[$field])) {
        echo json_encode(["status" => "error", "message" => "$field is required"]);
        exit;
    }
}

// Sanitize inputs
$firstName = mysqli_real_escape_string($db, $postData['firstName']); 
$lastName = mysqli_real_escape_string($db, $postData['lastName']); 
$email = mysqli_real_escape_string($db, $postData['email']); 
$phoneNumber = mysqli_real_escape_string($db, $postData['phoneNumber']);
$rolesString = mysqli_real_escape_string($db, implode(',', array_map('trim', $postData['roles'])));
$userId = mysqli_real_escape_string($db, $postData['userId']);
$fullName = trim($firstName . ' ' . $lastName); 

// Update Query
$sql = "UPDATE users 
        SET name = '$fullName', 
            email = '$email', 
            phone = '$phoneNumber', 
            role = '$rolesString' 
        WHERE id = '$userId'";

$result = mysqli_query($db, $sql);

// Response
if ($result) {
    echo json_encode(["status" => "success", "message" => "User updated successfully"]);
} else {
    echo json_encode(["status" => "error", "message" => "Failed to update user", "error" => mysqli_error($db)]);
}

mysqli_close($db);
?>
