<?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([]); exit; }

$symbol = isset($_GET['symbol']) ? trim($_GET['symbol']) : '';

// Ensure table exists
$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);

if ($symbol) {
    $stmt = mysqli_prepare($link, "SELECT id,symbol,network,chain_id,contract_address,decimals,enabled,updated_at FROM token_contracts WHERE symbol = ? ORDER BY chain_id ASC");
    mysqli_stmt_bind_param($stmt, 's', $symbol);
} else {
    $stmt = mysqli_prepare($link, "SELECT id,symbol,network,chain_id,contract_address,decimals,enabled,updated_at FROM token_contracts ORDER BY symbol,chain_id");
}

mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);
$rows = [];
while($r = mysqli_fetch_assoc($res)) $rows[] = $r;
echo json_encode($rows);

?>