<?php
require_once __DIR__ . '/config/database.php';

try {
    // 1. Create transactions table
    $pdo->exec("CREATE TABLE IF NOT EXISTS transactions (
        id TEXT PRIMARY KEY,
        sender_id INTEGER NOT NULL,
        receiver_id INTEGER NOT NULL,
        amount REAL NOT NULL,
        symbol TEXT NOT NULL,
        status TEXT DEFAULT 'completed',
        tx_hash TEXT NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (sender_id) REFERENCES users(id),
        FOREIGN KEY (receiver_id) REFERENCES users(id)
    )");
    echo "Created transactions table." . PHP_EOL;

    // 2. Add wallet_address column to users if not exists
    $stmt = $pdo->query("PRAGMA table_info(users)");
    $cols = $stmt->fetchAll(PDO::FETCH_COLUMN, 1);
    
    if (!in_array('wallet_address', $cols)) {
        $pdo->exec("ALTER TABLE users ADD COLUMN wallet_address TEXT UNIQUE");
        echo "Added wallet_address column to users." . PHP_EOL;
        
        // Generate wallet addresses for existing users
        $users = $pdo->query("SELECT id FROM users WHERE wallet_address IS NULL")->fetchAll(PDO::FETCH_ASSOC);
        $stmt = $pdo->prepare("UPDATE users SET wallet_address = ? WHERE id = ?");
        
        foreach ($users as $user) {
            $walletAddr = '0x' . bin2hex(random_bytes(20));
            $stmt->execute([$walletAddr, $user['id']]);
        }
        echo "Generated wallet addresses for existing users." . PHP_EOL;
    } else {
        echo "wallet_address column already exists." . PHP_EOL;
    }

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage() . PHP_EOL;
}
