<?php
// Seed USDT token_contracts entries if they don't exist
$base = realpath(__DIR__ . '/../../');
if (file_exists($base . '/config/db.php')) include $base . '/config/db.php';
if (!isset($link)) { echo "DB not available\n"; exit(1); }

$tokens = [
    ['symbol'=>'USDT','network'=>'Ethereum','chain_id'=>1,'contract_address'=>'0xdAC17F958D2ee523a2206206994597C13D831ec7','decimals'=>6],
    ['symbol'=>'USDT','network'=>'BSC','chain_id'=>56,'contract_address'=>'0x55d398326f99059fF775485246999027B3197955','decimals'=>18],
    ['symbol'=>'USDT','network'=>'Polygon','chain_id'=>137,'contract_address'=>'0x3813e82e6f7098b9583fc0f33a962d02018b6803','decimals'=>6]
];

$created = 0;
foreach($tokens as $t) {
    $sym = mysqli_real_escape_string($link, $t['symbol']);
    $addr = mysqli_real_escape_string($link, $t['contract_address']);
    $chain = intval($t['chain_id']);
    $dec = intval($t['decimals']);

    // Ensure table exists (same schema as admin endpoints)
    $create_sql = "CREATE TABLE IF NOT EXISTS token_contracts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        symbol VARCHAR(32) NOT NULL,
        network VARCHAR(64) DEFAULT NULL,
        chain_id INT DEFAULT NULL,
        contract_address VARCHAR(255) NOT NULL,
        decimals INT DEFAULT NULL,
        enabled TINYINT DEFAULT 1,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
    mysqli_query($link, $create_sql);

    $check = mysqli_prepare($link, "SELECT id FROM token_contracts WHERE symbol=? AND chain_id=? LIMIT 1");
    mysqli_stmt_bind_param($check, 'si', $sym, $chain);
    mysqli_stmt_execute($check);
    $res = mysqli_stmt_get_result($check);
    if (mysqli_num_rows($res) > 0) { continue; }

    $stmt = mysqli_prepare($link, "INSERT INTO token_contracts (symbol,network,chain_id,contract_address,decimals,enabled) VALUES (?,?,?,?,?,1)");
    mysqli_stmt_bind_param($stmt, 'ssisi', $sym, $t['network'], $chain, $addr, $dec);
    $ok = mysqli_stmt_execute($stmt);
    if ($ok) { $created++; }
}

echo "Seed complete. Created: $created\n";
?>