<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/database.php';

$response = ['success' => false, 'message' => ''];

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['id'])) {
        throw new Exception('Invalid input data');
    }
    
    $pdo = Database::getInstance()->getConnection();
    
    // Build update query based on provided fields
    $fields = [];
    $params = [];
    
    $updatable = ['full_name', 'email', 'username', 'role', 'status', 'department'];
    foreach ($updatable as $field) {
        if (isset($input[$field])) {
            $fields[] = "$field = ?";
            $params[] = $input[$field];
        }
    }
    
    // Handle password update separately
    if (!empty($input['password'])) {
        $fields[] = "password = ?";
        $params[] = password_hash($input['password'], PASSWORD_DEFAULT);
    }
    
    if (empty($fields)) {
        throw new Exception('No fields to update');
    }
    
    $params[] = $input['id']; // WHERE condition
    
    $sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $success = $stmt->execute($params);
    
    if ($success) {
        $response['success'] = true;
        $response['message'] = 'User updated successfully';
    } else {
        throw new Exception('Failed to update user');
    }
    
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
?>