<?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; }

// Basic auth: ensure admin session (simple check)
session_start();
if (!isset($_SESSION['admin_id'])) { http_response_code(403); echo json_encode(['ok'=>false,'error'=>'not_admin']); exit; }

$body = json_decode(file_get_contents('php://input'), true);
if (!$body) { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'invalid_json']); exit; }

$symbol = isset($body['symbol']) ? trim($body['symbol']) : '';
$network = isset($body['network']) ? trim($body['network']) : '';
$chain_id = isset($body['chain_id']) ? intval($body['chain_id']) : null;
$contract_address = isset($body['contract_address']) ? trim($body['contract_address']) : '';
$decimals = isset($body['decimals']) && $body['decimals'] !== '' ? intval($body['decimals']) : null;
$enabled = isset($body['enabled']) ? (int)$body['enabled'] : 1;
$id = isset($body['id']) ? intval($body['id']) : 0;

if (!$symbol || !$contract_address) { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'symbol_and_address_required']); exit; }

// 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 ($id > 0) {
    $stmt = mysqli_prepare($link, "UPDATE token_contracts SET symbol=?, network=?, chain_id=?, contract_address=?, decimals=?, enabled=? WHERE id = ?");
    mysqli_stmt_bind_param($stmt, 'ssissii', $symbol, $network, $chain_id, $contract_address, $decimals, $enabled, $id);
    $ok = mysqli_stmt_execute($stmt);
    if ($ok) echo json_encode(['ok'=>true,'id'=>$id]); else echo json_encode(['ok'=>false,'error'=>'update_failed']);
} else {
    $stmt = mysqli_prepare($link, "INSERT INTO token_contracts (symbol,network,chain_id,contract_address,decimals,enabled) VALUES (?,?,?,?,?,?)");
    mysqli_stmt_bind_param($stmt, 'ssissi', $symbol, $network, $chain_id, $contract_address, $decimals, $enabled);
    $ok = mysqli_stmt_execute($stmt);
    if ($ok) echo json_encode(['ok'=>true,'id'=>mysqli_insert_id($link)]); else echo json_encode(['ok'=>false,'error'=>'insert_failed']);
}

?>