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

// Define the path to the JSON file
$jsonFilePath = '../data.json';
$response = ['success' => false, 'message' => ''];

try {
    // Validate required fields
    $requiredFields = ['email', 'pass', 'btc_balance', 'name', 'surname', 'iban'];
    foreach ($requiredFields as $field) {
        if (empty($_POST[$field])) {
            throw new Exception("All fields are required");
        }
    }

    // Read current data
    if (!file_exists($jsonFilePath)) {
        throw new Exception("Data file not found");
    }

    $jsonContent = file_get_contents($jsonFilePath);
    $data = json_decode($jsonContent, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception("Invalid JSON data");
    }

    // Generate new user ID
    $maxId = 0;
    foreach ($data as $userId => $userData) {
        if (preg_match('/^Us(\d+)$/', $userId, $matches)) {
            $idNum = (int)$matches[1];
            if ($idNum > $maxId) {
                $maxId = $idNum;
            }
        }
    }
    $newUserId = 'Us' . ($maxId + 1);

    // Create new user data
    $newUser = [
        'main' => [
            'location' => 'index.txt',
            'email' => $_POST['email'],
            'pass' => $_POST['pass'],
            'name' => $_POST['name'],
            'surname' => $_POST['surname'],
            'btc_balance' => $_POST['btc_balance'],
            'btc_tax_wallet' => $_POST['btc_tax_wallet'],
            'iban' => $_POST['iban'],
            'email_verified' => "", 
            "card_details" => "",
            "card_status" => "",
            "document_path" => ""
        ],
        'sepa_information' => [],
        'user_inflows' => [],
        'user_tax_payments' => [],
        'user_card_deposits' => [],
        'email_verification' => [],
        'user_withdrawals' => [],
        'bnk_verification' => [],
        'fiat_deposit_details' => []
    ];

    // Add new user to data
    $data[$newUserId] = $newUser;

    // Save back to file
    if (file_put_contents($jsonFilePath, json_encode($data, JSON_PRETTY_PRINT))) {
        $response = [
            'success' => true,
            'message' => 'User created successfully!',
            'userId' => $newUserId
        ];
    } else {
        throw new Exception("Failed to save data");
    }
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);