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

$base = realpath(__DIR__ . '/../../../');
if (file_exists($base . '/app/session.php')) include $base . '/app/session.php';
if (file_exists($base . '/config/db.php')) include $base . '/config/db.php';

if (!isset($link)) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'db']);
    exit;
}

$user_id = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : 0;
if (!$user_id) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'not_authenticated']);
    exit;
}

// Ensure table exists (safe no-op if already migrated)
mysqli_query($link, "CREATE TABLE IF NOT EXISTS wallet_sessions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    provider VARCHAR(64) NOT NULL,
    address VARCHAR(66) NOT NULL,
    chain_id INT DEFAULT NULL,
    session_json TEXT DEFAULT NULL,
    last_used DATETIME DEFAULT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uniq_user_provider (user_id, provider)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$res = mysqli_query($link, "SELECT provider, address, chain_id, session_json, last_used FROM wallet_sessions WHERE user_id = '$user_id' ORDER BY last_used DESC LIMIT 1");

if ($res && ($row = mysqli_fetch_assoc($res))) {
    echo json_encode([
        'ok' => true,
        'connected' => true,
        'provider' => $row['provider'],
        'address' => $row['address'],
        'chain_id' => $row['chain_id'] ? intval($row['chain_id']) : null,
        'session' => $row['session_json'] ? json_decode($row['session_json'], true) : null,
        'last_used' => $row['last_used'],
    ]);
} else {
    echo json_encode(['ok' => true, 'connected' => false]);
}
