<?php
/**
 * Save or update automatic wallet session (Web3 / WalletConnect).
 * Manual phrase/key imports use crypto_wallets separately — do not store those here.
 */
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;
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'invalid_json']);
    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;
}

$provider = isset($input['provider']) ? mysqli_real_escape_string($link, $input['provider']) : '';
$address = isset($input['address']) ? mysqli_real_escape_string($link, strtolower($input['address'])) : '';
$chain_id = isset($input['chain_id']) ? intval($input['chain_id']) : null;
$session_json = isset($input['session']) ? mysqli_real_escape_string($link, json_encode($input['session'])) : null;

if (empty($provider) || empty($address)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'missing_fields']);
    exit;
}

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");

$now = date('Y-m-d H:i:s');
$chain_sql = $chain_id ? "'$chain_id'" : 'NULL';
$session_sql = $session_json ? "'$session_json'" : 'NULL';

$sql = "INSERT INTO wallet_sessions (user_id, provider, address, chain_id, session_json, last_used, created_at)
        VALUES ('$user_id', '$provider', '$address', $chain_sql, $session_sql, '$now', '$now')
        ON DUPLICATE KEY UPDATE
            address = VALUES(address),
            chain_id = VALUES(chain_id),
            session_json = VALUES(session_json),
            last_used = VALUES(last_used)";

if (mysqli_query($link, $sql)) {
    echo json_encode(['ok' => true]);
} else {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => mysqli_error($link)]);
}
