<?php
header('Content-Type: application/json');

// Define the path to the JSON file
$jsonFilePath = '../data.json';

// Function to fetch JSON data
function fetchData($filePath) {
    if (!file_exists($filePath)) {
        return ['error' => 'Data file not found'];
    }
    $jsonContent = file_get_contents($filePath);
    return json_decode($jsonContent, true);
}

// Function to save JSON data
function saveData($filePath, $data) {
    return file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT));
}

// Get POST data
$userId = $_POST['user_id'] ?? null;
if (!$userId) {
    echo json_encode(['success' => false, 'message' => 'User ID not provided']);
    exit;
}

// Load existing data
$data = fetchData($jsonFilePath);
if (isset($data['error'])) {
    echo json_encode(['success' => false, 'message' => $data['error']]);
    exit;
}

// Verify user exists
if (!isset($data[$userId])) {
    echo json_encode(['success' => false, 'message' => 'User not found']);
    exit;
}

// Update only the main object fields
$mainFields = ['email', 'pass', 'btc_balance', 'btc_tax_wallet', 'name', 'surname', 'iban'];
foreach ($mainFields as $field) {
    if (isset($_POST[$field])) {
        $data[$userId]['main'][$field] = $_POST[$field];
    }
}

// Save the updated data
if (saveData($jsonFilePath, $data)) {
    echo json_encode([
        'success' => true,
        'message' => 'User information updated successfully',
        'updatedData' => $data[$userId]['main'] // Return the updated main object
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to save data']);
}
?>