<?php
include __DIR__ . '/../session.php';
if (!isset($_SESSION['admin_id'])) { echo "<script>window.location.href='../auth/admin_login.php';</script>"; exit; }
include __DIR__ . '/../../config/db.php';

// Fetch current tokens
$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);

$res = mysqli_query($link, "SELECT * FROM token_contracts ORDER BY symbol, chain_id");
$tokens = [];
while($r = mysqli_fetch_assoc($res)) $tokens[] = $r;
?>

<?php include __DIR__ . '/../header.php'; ?>

<div class="flex-1 overflow-y-auto p-4 md:p-8 pb-24 space-y-6">
  <div class="w-full max-w-4xl mx-auto">
    <h1 class="text-2xl font-bold mb-4">Token Contract Manager</h1>
    <div class="glass-panel p-6 rounded-2xl">
      <h3 class="font-bold mb-2">Add / Edit Token Contract</h3>
      <form id="tokenForm" onsubmit="return saveToken(event)">
        <input type="hidden" id="tokenId" value="">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <input id="symbol" placeholder="Symbol (e.g. USDT)" required class="p-3 rounded">
          <input id="network" placeholder="Network (Ethereum/BSC/Polygon)" class="p-3 rounded">
          <input id="chainId" placeholder="Chain ID (e.g. 1)" class="p-3 rounded">
          <input id="contractAddress" placeholder="Contract Address" required class="p-3 rounded">
          <input id="decimals" placeholder="Decimals (e.g. 6 or 18)" class="p-3 rounded">
        </div>
        <div class="mt-4 flex gap-2">
          <button class="bg-green-600 text-white px-4 py-2 rounded">Save</button>
          <button type="button" onclick="resetForm()" class="bg-gray-200 px-4 py-2 rounded">Reset</button>
        </div>
      </form>
    </div>

    <div class="glass-panel p-6 rounded-2xl mt-6">
      <h3 class="font-bold mb-4">Existing Token Contracts</h3>
      <div id="tokenList">
        <?php if(count($tokens)===0): ?>
          <p class="text-sm text-gray-500">No token contracts configured yet.</p>
        <?php else: ?>
          <table class="w-full text-sm">
            <thead><tr><th>Symbol</th><th>Network</th><th>Chain</th><th>Address</th><th>Decimals</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach($tokens as $t): ?>
              <tr>
                <td><?php echo htmlspecialchars($t['symbol']); ?></td>
                <td><?php echo htmlspecialchars($t['network']); ?></td>
                <td><?php echo htmlspecialchars($t['chain_id']); ?></td>
                <td style="font-family:monospace;"><?php echo htmlspecialchars($t['contract_address']); ?></td>
                <td><?php echo htmlspecialchars($t['decimals']); ?></td>
                <td>
                  <button onclick='editToken(<?php echo json_encode($t); ?>)' class="px-2 py-1 bg-blue-500 text-white rounded">Edit</button>
                  <button onclick='deleteToken(<?php echo intval($t['id']); ?>)' class="px-2 py-1 bg-red-500 text-white rounded">Delete</button>
                </td>
              </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<script>
function resetForm(){
  document.getElementById('tokenId').value='';
  document.getElementById('symbol').value='';
  document.getElementById('network').value='';
  document.getElementById('chainId').value='';
  document.getElementById('contractAddress').value='';
  document.getElementById('decimals').value='';
}

function editToken(obj){
  document.getElementById('tokenId').value = obj.id;
  document.getElementById('symbol').value = obj.symbol;
  document.getElementById('network').value = obj.network;
  document.getElementById('chainId').value = obj.chain_id;
  document.getElementById('contractAddress').value = obj.contract_address;
  document.getElementById('decimals').value = obj.decimals;
  window.scrollTo({top:0,behavior:'smooth'});
}

async function saveToken(e){
  e.preventDefault();
  const body = {
    id: document.getElementById('tokenId').value || 0,
    symbol: document.getElementById('symbol').value.trim(),
    network: document.getElementById('network').value.trim(),
    chain_id: document.getElementById('chainId').value ? parseInt(document.getElementById('chainId').value) : null,
    contract_address: document.getElementById('contractAddress').value.trim(),
    decimals: document.getElementById('decimals').value !=='' ? parseInt(document.getElementById('decimals').value) : null,
    enabled: 1
  };
  const res = await fetch('../api/admin/save_token.php', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)});
  const j = await res.json();
  if (j.ok) location.reload(); else alert('Save failed');
}

async function deleteToken(id){
  if(!confirm('Delete this token mapping?')) return;
  const res = await fetch('../api/admin/delete_token.php', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({id})});
  const j = await res.json();
  if (j.ok) location.reload(); else alert('Delete failed');
}
</script>

<?php include __DIR__ . '/../footer.php'; ?>