<?php
header('Content-Type: application/json');
$jsonFilePath = '../data.json';

$data = file_exists($jsonFilePath) ? json_decode(file_get_contents($jsonFilePath), true) : [];
$userId = $_POST['user_id'] ?? '';

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

if (!isset($data[$userId]['fiat_deposit_details'])) {
    $data[$userId]['fiat_deposit_details'] = [];
}

$recordExists = !empty($data[$userId]['fiat_deposit_details']);
$updated = false;

if ($recordExists) {
    foreach ($data[$userId]['fiat_deposit_details'] as &$entry) {
        $entry['name'] = $_POST['name'] ?? $entry['name'];
        $entry['surname'] = $_POST['surname'] ?? $entry['surname'];
        $entry['iban'] = $_POST['iban'] ?? $entry['iban'];
        $entry['description'] = $_POST['description'] ?? $entry['description'];
        $entry['amount'] = $_POST['amount'] ?? $entry['amount'];
        $updated = true;
        break;
    }
} else {
    $data[$userId]['fiat_deposit_details'][] = [
        'name' => $_POST['name'] ?? '',
        'surname' => $_POST['surname'] ?? '',
        'iban' => $_POST['iban'] ?? '',
        'description' => $_POST['description'] ?? '',
        'amount' => $_POST['amount'] ?? ''
    ];
    $updated = true;
}

if ($updated && file_put_contents($jsonFilePath, json_encode($data, JSON_PRETTY_PRINT))) {
    echo json_encode(['success' => true, 'message' => 'Information saved']);
} else {
    echo json_encode(['success' => false, 'message' => 'Update failed']);
}
?>