<?php
$pageTitle = 'Assets';
/**
 * Admin Assets Management - Fixed
 */
require_once 'includes/header.php';

$message = '';
$messageType = '';

// Handle actions BEFORE any output
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    try {
        if ($action === 'add') {
            $data = [
                'name' => trim($_POST['name'] ?? ''),
                'symbol' => strtoupper(trim($_POST['symbol'] ?? '')),
                'base_currency' => strtoupper(trim($_POST['base_currency'] ?? '')),
                'quote_currency' => strtoupper(trim($_POST['quote_currency'] ?? 'USDT')),
                'asset_type' => $_POST['asset_type'] ?? 'crypto',
                'category' => $_POST['asset_type'] ?? 'crypto',
                'payout_percent' => (float)($_POST['payout_percent'] ?? 85),
                'min_trade' => (float)($_POST['min_trade'] ?? 100),
                'max_trade' => (float)($_POST['max_trade'] ?? 50000),
                'icon_color' => $_POST['icon_color'] ?? '#f7931a',
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
                'is_24h' => 1
            ];
            
            if (empty($data['name']) || empty($data['symbol'])) {
                $message = 'Name and Symbol are required';
                $messageType = 'error';
            } else {
                dbInsert('assets', $data);
                $message = 'Asset added successfully!';
                $messageType = 'success';
            }
        } elseif ($action === 'edit') {
            $data = [
                'name' => trim($_POST['name'] ?? ''),
                'symbol' => strtoupper(trim($_POST['symbol'] ?? '')),
                'base_currency' => strtoupper(trim($_POST['base_currency'] ?? '')),
                'quote_currency' => strtoupper(trim($_POST['quote_currency'] ?? 'USDT')),
                'asset_type' => $_POST['asset_type'] ?? 'crypto',
                'category' => $_POST['asset_type'] ?? 'crypto',
                'payout_percent' => (float)($_POST['payout_percent'] ?? 85),
                'min_trade' => (float)($_POST['min_trade'] ?? 100),
                'max_trade' => (float)($_POST['max_trade'] ?? 50000),
                'icon_color' => $_POST['icon_color'] ?? '#f7931a',
                'is_active' => isset($_POST['is_active']) ? 1 : 0
            ];
            dbUpdate('assets', $data, 'id = :id', ['id' => $_POST['asset_id']]);
            $message = 'Asset updated successfully!';
            $messageType = 'success';
        } elseif ($action === 'delete') {
            $assetId = (int)$_POST['asset_id'];
            $stmt = db()->prepare("DELETE FROM assets WHERE id = ?");
            $stmt->execute([$assetId]);
            $message = 'Asset deleted!';
            $messageType = 'success';
        } elseif ($action === 'toggle') {
            $asset = dbFetch("SELECT is_active FROM assets WHERE id = :id", ['id' => $_POST['asset_id']]);
            $newStatus = $asset['is_active'] ? 0 : 1;
            dbUpdate('assets', ['is_active' => $newStatus], 'id = :id', ['id' => $_POST['asset_id']]);
            $message = 'Asset status updated!';
            $messageType = 'success';
        }
    } catch (Exception $e) {
        $message = 'Error: ' . $e->getMessage();
        $messageType = 'error';
    }
}

$catFilter = $_GET['cat'] ?? 'all';
if ($catFilter !== 'all') {
    $assets = dbFetchAll("SELECT *, COALESCE(is_active, 1) as is_active FROM assets WHERE asset_type = :cat ORDER BY is_active DESC, name ASC", ['cat' => $catFilter]);
} else {
    $assets = dbFetchAll("SELECT *, COALESCE(is_active, 1) as is_active FROM assets ORDER BY is_active DESC, name ASC");
}
?>

<style>
.assets-container { max-height: calc(100vh - 250px); overflow-y: auto; }
.asset-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; padding: 1rem; margin-bottom: 1rem; }
.asset-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem; }
.asset-info { display: flex; align-items: center; gap: 1rem; }
.asset-icon { width: 48px; height: 48px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700; color: #fff; background: var(--bg-tertiary); }
.asset-icon.crypto { background: linear-gradient(135deg, #f7931a, #ff6b00); }
.asset-icon.forex { background: linear-gradient(135deg, #3b82f6, #1d4ed8); }
.asset-icon.stocks { background: linear-gradient(135deg, #10b981, #059669); }
.asset-icon.commodities { background: linear-gradient(135deg, #fbbf24, #d97706); }
.asset-name { font-weight: 600; font-size: 1.1rem; }
.asset-symbol { color: var(--text-muted); font-size: 0.9rem; font-family: monospace; }
.asset-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1rem; }
.asset-stat { text-align: center; padding: 0.75rem; background: var(--bg-tertiary); border-radius: 8px; }
.asset-stat-value { font-weight: 600; font-size: 1.1rem; }
.asset-stat-label { font-size: 0.75rem; color: var(--text-muted); }
.asset-actions { display: flex; gap: 0.5rem; }
.badge-active { background: rgba(0, 208, 156, 0.2); color: #00d09c; }
.badge-inactive { background: rgba(255, 82, 82, 0.2); color: #ff5252; }
.modal-lg { max-width: 600px; }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
@media (max-width: 768px) { .asset-stats { grid-template-columns: repeat(2, 1fr); } .form-row { grid-template-columns: 1fr; } }
</style>

<div class="page-header">
    <h1 class="page-title">Trading Assets</h1>
    <button class="btn btn-primary" onclick="openAddModal()">
        <i class="fas fa-plus"></i> Add Asset
    </button>
</div>

<?php if ($message): ?>
<div class="alert alert-<?= $messageType === 'success' ? 'success' : 'danger' ?>">
    <i class="fas fa-<?= $messageType === 'success' ? 'check-circle' : 'exclamation-circle' ?>"></i>
    <?= htmlspecialchars($message) ?>
</div>
<?php endif; ?>

<div class="card mb-4">
    <div class="card-header">
        <div class="d-flex gap-2">
            <a href="?cat=all" class="btn btn-sm <?= $catFilter === 'all' ? 'btn-primary' : 'btn-secondary' ?>">All</a>
            <a href="?cat=crypto" class="btn btn-sm <?= $catFilter === 'crypto' ? 'btn-primary' : 'btn-secondary' ?>">Crypto</a>
            <a href="?cat=forex" class="btn btn-sm <?= $catFilter === 'forex' ? 'btn-primary' : 'btn-secondary' ?>">Forex</a>
            <a href="?cat=stock" class="btn btn-sm <?= $catFilter === 'stock' ? 'btn-primary' : 'btn-secondary' ?>">Stocks</a>
            <a href="?cat=commodity" class="btn btn-sm <?= $catFilter === 'commodity' ? 'btn-primary' : 'btn-secondary' ?>">Commodities</a>
            <a href="?cat=index" class="btn btn-sm <?= $catFilter === 'index' ? 'btn-primary' : 'btn-secondary' ?>">Indices</a>
        </div>
    </div>
</div>

<div class="assets-container">
    <?php if (empty($assets)): ?>
    <div class="card">
        <div class="card-body text-center py-5">
            <i class="fas fa-coins fa-3x text-muted mb-3"></i>
            <h3>No Assets Found</h3>
            <p class="text-muted">Add trading assets to get started</p>
            <button class="btn btn-primary" onclick="openAddModal()">
                <i class="fas fa-plus"></i> Add First Asset
            </button>
        </div>
    </div>
    <?php else: ?>
    <?php foreach ($assets as $asset): ?>
    <div class="asset-card">
        <div class="asset-header">
            <div class="asset-info">
                <div class="asset-icon" style="background: <?= $asset['icon_color'] ?? '#f7931a' ?>">
                    <?= substr($asset['base_currency'] ?? 'XX', 0, 2) ?>
                </div>
                <div>
                    <div class="asset-name"><?= htmlspecialchars($asset['name']) ?></div>
                    <div class="asset-symbol"><?= htmlspecialchars($asset['symbol']) ?></div>
                </div>
                <span class="badge <?= $asset['is_active'] ? 'badge-active' : 'badge-inactive' ?>">
                    <?= $asset['is_active'] ? 'Active' : 'Inactive' ?>
                </span>
            </div>
            <div class="asset-actions">
                <button class="btn btn-sm btn-secondary" onclick='editAsset(<?= json_encode($asset, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'>
                    <i class="fas fa-edit"></i>
                </button>
                <form method="POST" style="display:inline">
                    <input type="hidden" name="action" value="toggle">
                    <input type="hidden" name="asset_id" value="<?= $asset['id'] ?>">
                    <button type="submit" class="btn btn-sm <?= $asset['is_active'] ? 'btn-warning' : 'btn-success' ?>">
                        <i class="fas fa-<?= $asset['is_active'] ? 'pause' : 'play' ?>"></i>
                    </button>
                </form>
                <form method="POST" style="display:inline" onsubmit="return confirm('Delete this asset?')">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="asset_id" value="<?= $asset['id'] ?>">
                    <button type="submit" class="btn btn-sm btn-danger">
                        <i class="fas fa-trash"></i>
                    </button>
                </form>
            </div>
        </div>
        <div class="asset-stats">
            <div class="asset-stat">
                <div class="asset-stat-value text-green"><?= $asset['payout_percent'] ?>%</div>
                <div class="asset-stat-label">Payout</div>
            </div>
            <div class="asset-stat">
                <div class="asset-stat-value"><?= CURRENCY_SYMBOL ?><?= number_format($asset['min_trade'] ?? 100) ?></div>
                <div class="asset-stat-label">Min Trade</div>
            </div>
            <div class="asset-stat">
                <div class="asset-stat-value"><?= CURRENCY_SYMBOL ?><?= number_format($asset['max_trade'] ?? 50000) ?></div>
                <div class="asset-stat-label">Max Trade</div>
            </div>
            <div class="asset-stat">
                <div class="asset-stat-value"><?= ucfirst($asset['asset_type'] ?? 'crypto') ?></div>
                <div class="asset-stat-label">Type</div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- Add/Edit Modal -->
<div class="modal" id="assetModal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modalTitle">Add Asset</h4>
                <button class="modal-close" onclick="closeModal()">&times;</button>
            </div>
            <form method="POST" id="assetForm">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="asset_id" id="assetId">
                <div class="modal-body">
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Asset Name *</label>
                            <input type="text" name="name" id="assetName" class="form-control" required placeholder="Bitcoin">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Symbol (Binance) *</label>
                            <input type="text" name="symbol" id="assetSymbol" class="form-control" required placeholder="BTCUSDT">
                            <small class="text-muted">Must match Binance symbol exactly</small>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Base Currency *</label>
                            <input type="text" name="base_currency" id="baseCurrency" class="form-control" required placeholder="BTC">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Quote Currency</label>
                            <input type="text" name="quote_currency" id="quoteCurrency" class="form-control" value="USDT" placeholder="USDT">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Asset Type</label>
                            <select name="asset_type" id="assetType" class="form-control">
                                <option value="crypto">Cryptocurrency</option>
                                <option value="forex">Forex</option>
                                <option value="stock">Stocks</option>
                                <option value="commodity">Commodities</option>
                                <option value="index">Indices</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Payout Percent</label>
                            <input type="number" name="payout_percent" id="payoutPercent" class="form-control" value="85" min="50" max="95">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Icon Color</label>
                            <input type="color" name="icon_color" id="iconColor" class="form-control" value="#f7931a" style="height: 48px; padding: 4px;">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Min Trade Amount</label>
                            <input type="number" name="min_trade" id="minTrade" class="form-control" value="100">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Max Trade Amount</label>
                            <input type="number" name="max_trade" id="maxTrade" class="form-control" value="50000">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-check">
                            <input type="checkbox" name="is_active" id="isActive" checked>
                            <span>Active (available for trading)</span>
                        </label>
                    </div>
                    
                    <!-- Popular Assets Quick Add -->
                    <div class="form-group">
                        <label class="form-label">Quick Add Popular Assets</label>
                        <div style="display: flex; flex-wrap: wrap; gap: 0.5rem;">
                            <button type="button" class="btn btn-sm btn-secondary" onclick="quickAdd('Bitcoin','BTCUSDT','BTC')">BTC</button>
                            <button type="button" class="btn btn-sm btn-secondary" onclick="quickAdd('Ethereum','ETHUSDT','ETH')">ETH</button>
                            <button type="button" class="btn btn-sm btn-secondary" onclick="quickAdd('BNB','BNBUSDT','BNB')">BNB</button>
                            <button type="button" class="btn btn-sm btn-secondary" onclick="quickAdd('Solana','SOLUSDT','SOL')">SOL</button>
                            <button type="button" class="btn btn-sm btn-secondary" onclick="quickAdd('XRP','XRPUSDT','XRP')">XRP</button>
                            <button type="button" class="btn btn-sm btn-secondary" onclick="quickAdd('Dogecoin','DOGEUSDT','DOGE')">DOGE</button>
                            <button type="button" class="btn btn-sm btn-secondary" onclick="quickAdd('Cardano','ADAUSDT','ADA')">ADA</button>
                            <button type="button" class="btn btn-sm btn-secondary" onclick="quickAdd('Polygon','MATICUSDT','MATIC')">MATIC</button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Save Asset
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function openAddModal() {
    document.getElementById('modalTitle').textContent = 'Add Asset';
    document.getElementById('formAction').value = 'add';
    document.getElementById('assetId').value = '';
    document.getElementById('assetForm').reset();
    document.getElementById('isActive').checked = true;
    document.getElementById('assetModal').classList.add('active');
}

function editAsset(asset) {
    document.getElementById('modalTitle').textContent = 'Edit Asset';
    document.getElementById('formAction').value = 'edit';
    document.getElementById('assetId').value = asset.id;
    document.getElementById('assetName').value = asset.name;
    document.getElementById('assetSymbol').value = asset.symbol;
    document.getElementById('baseCurrency').value = asset.base_currency;
    document.getElementById('quoteCurrency').value = asset.quote_currency || 'USDT';
    document.getElementById('assetType').value = asset.asset_type;
    document.getElementById('payoutPercent').value = asset.payout_percent;
    document.getElementById('minTrade').value = asset.min_trade;
    document.getElementById('maxTrade').value = asset.max_trade;
    document.getElementById('iconColor').value = asset.icon_color || '#f7931a';
    document.getElementById('isActive').checked = asset.is_active == 1;
    document.getElementById('assetModal').classList.add('active');
}

function closeModal() {
    document.getElementById('assetModal').classList.remove('active');
}

function quickAdd(name, symbol, base) {
    document.getElementById('assetName').value = name;
    document.getElementById('assetSymbol').value = symbol;
    document.getElementById('baseCurrency').value = base;
    document.getElementById('quoteCurrency').value = 'USDT';
}

// Close modal on outside click
document.getElementById('assetModal').addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});
</script>

<?php require_once 'includes/footer.php'; ?>
