<?php

require_once __DIR__ . '/admin_tool_helper.php';

$message = '';
$error = '';

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function sym($row, $key, $default = '')
{
    return $row[$key] ?? $default;
}

function normalize_symbol_code($symbol)
{
    $symbol = strtoupper(trim((string)$symbol));
    $symbol = str_replace([' ', '-', '/'], '', $symbol);

    if ($symbol === 'BTCUSDT') {
        return 'BTCUSD';
    }

    if ($symbol === 'ETHUSDT') {
        return 'ETHUSD';
    }

    return $symbol;
}

function canonical_asset_type($assetType)
{
    $assetType = strtoupper(trim((string)$assetType));

    $map = [
        'FX' => 'FOREX',
        'FOREX' => 'FOREX',
        'METAL' => 'METAL',
        'METALS' => 'METAL',
        'INDEX' => 'INDICES',
        'INDEXES' => 'INDICES',
        'INDICES' => 'INDICES',
        'CRYPTO' => 'CRYPTO',
        'CRYPTOCURRENCY' => 'CRYPTO',
        'CRYPTOCURRENCIES' => 'CRYPTO',
        'STOCK' => 'STOCKS',
        'STOCKS' => 'STOCKS',
        'COMMODITY' => 'COMMODITY',
        'COMMODITIES' => 'COMMODITY',
        'OTHER' => 'OTHER',
        'OTHERS' => 'OTHER',
    ];

    return $map[$assetType] ?? 'OTHER';
}

function detect_asset_type($symbol, $selectedAssetType = '')
{
    $clean = normalize_symbol_code($symbol);
    $selected = canonical_asset_type($selectedAssetType);

    if (
        strpos($clean, 'BTC') !== false ||
        strpos($clean, 'ETH') !== false ||
        strpos($clean, 'BNB') !== false ||
        strpos($clean, 'SOL') !== false ||
        strpos($clean, 'XRP') !== false ||
        strpos($clean, 'DOGE') !== false ||
        strpos($clean, 'ADA') !== false ||
        strpos($clean, 'AVAX') !== false ||
        strpos($clean, 'DOT') !== false
    ) {
        return 'CRYPTO';
    }

    if (
        strpos($clean, 'XAU') !== false ||
        strpos($clean, 'XAG') !== false ||
        strpos($clean, 'GOLD') !== false ||
        strpos($clean, 'SILVER') !== false
    ) {
        return 'METAL';
    }

    if (
        strpos($clean, 'US30') !== false ||
        strpos($clean, 'NAS') !== false ||
        strpos($clean, 'US100') !== false ||
        strpos($clean, 'US500') !== false ||
        strpos($clean, 'SPX') !== false ||
        strpos($clean, 'GER40') !== false ||
        strpos($clean, 'UK100') !== false
    ) {
        return 'INDICES';
    }

    if (preg_match('/^[A-Z]{6}$/', $clean)) {
        return 'FOREX';
    }

    return $selected !== 'OTHER' ? $selected : 'OTHER';
}

function default_provider_symbol($symbol, $assetType)
{
    $symbol = normalize_symbol_code($symbol);
    $assetType = canonical_asset_type($assetType);

    if ($symbol === '') {
        return '';
    }

    if ($assetType === 'FOREX' && preg_match('/^[A-Z]{6}$/', $symbol)) {
        return substr($symbol, 0, 3) . '/' . substr($symbol, 3, 3);
    }

    if ($assetType === 'METAL' && preg_match('/^[A-Z]{6}$/', $symbol)) {
        return substr($symbol, 0, 3) . '/' . substr($symbol, 3, 3);
    }

    if ($assetType === 'CRYPTO' && substr($symbol, -3) === 'USD') {
        return substr($symbol, 0, -3) . '/USD';
    }

    return $symbol;
}

function default_base_quote($symbol)
{
    $symbol = normalize_symbol_code($symbol);

    if (preg_match('/^[A-Z]{6}$/', $symbol)) {
        return [substr($symbol, 0, 3), substr($symbol, 3, 3)];
    }

    if (substr($symbol, -3) === 'USD') {
        return [substr($symbol, 0, -3), 'USD'];
    }

    return [$symbol, 'USD'];
}

function symbol_defaults_for($symbol, $assetType)
{
    $symbol = normalize_symbol_code($symbol);
    $assetType = canonical_asset_type($assetType);
    [$base, $quote] = default_base_quote($symbol);

    $defaults = [
        'provider' => 'twelvedata',
        'provider_symbol' => default_provider_symbol($symbol, $assetType),
        'base_currency' => $base,
        'quote_currency' => $quote,
        'news_currency' => implode(',', array_filter(array_unique([$base, $quote]))),
        'decimals' => 5,
        'pip_size' => 0.0001,
        'point_size' => 0.00001,
        'tick_size' => 0.00001,
        'tick_value' => 1,
        'contract_size' => 100000,
        'spread_limit' => 0,
        'min_lot' => 0.01,
        'lot_step' => 0.01,
        'news_sensitivity' => 'MEDIUM',
        'session_preference' => 'London/New York',
        'min_rr' => 1.50,
    ];

    if ($assetType === 'FOREX') {
        if ($quote === 'JPY') {
            $defaults['decimals'] = 3;
            $defaults['pip_size'] = 0.01;
            $defaults['point_size'] = 0.001;
            $defaults['tick_size'] = 0.001;
        }
    }

    if ($assetType === 'METAL') {
        $defaults['news_currency'] = 'USD';
        $defaults['session_preference'] = 'London/New York';
        $defaults['news_sensitivity'] = 'HIGH';
        $defaults['min_rr'] = 2.00;

        if ($symbol === 'XAGUSD') {
            $defaults['decimals'] = 3;
            $defaults['pip_size'] = 0.01;
            $defaults['point_size'] = 0.001;
            $defaults['tick_size'] = 0.001;
            $defaults['contract_size'] = 5000;
            $defaults['spread_limit'] = 50;
        } else {
            $defaults['decimals'] = 2;
            $defaults['pip_size'] = 0.1;
            $defaults['point_size'] = 0.01;
            $defaults['tick_size'] = 0.01;
            $defaults['contract_size'] = 100;
            $defaults['spread_limit'] = 50;
        }
    }

    if ($assetType === 'INDICES') {
        $defaults['provider_symbol'] = $symbol;
        $defaults['base_currency'] = $symbol;
        $defaults['quote_currency'] = 'USD';
        $defaults['news_currency'] = 'USD';
        $defaults['decimals'] = 2;
        $defaults['pip_size'] = 1;
        $defaults['point_size'] = 1;
        $defaults['tick_size'] = 1;
        $defaults['contract_size'] = 1;
        $defaults['spread_limit'] = 30;
        $defaults['news_sensitivity'] = 'HIGH';
        $defaults['session_preference'] = 'London/New York';
        $defaults['min_rr'] = 2.00;
    }

    if ($assetType === 'CRYPTO') {
        $defaults['news_currency'] = 'USD';
        $defaults['decimals'] = 2;
        $defaults['pip_size'] = 1;
        $defaults['point_size'] = 0.01;
        $defaults['tick_size'] = 0.01;
        $defaults['contract_size'] = 1;
        $defaults['spread_limit'] = 100;
        $defaults['news_sensitivity'] = 'LOW';
        $defaults['session_preference'] = '24/7';
        $defaults['min_rr'] = 2.00;

        /*
         * Crypto lot sizes need more precision than forex/metals.
         * BTC can be very small; ETH is commonly smaller than 0.01.
         */
        if (strpos($symbol, 'BTC') === 0) {
            $defaults['min_lot'] = 0.0001;
            $defaults['lot_step'] = 0.0001;
        } elseif (strpos($symbol, 'ETH') === 0) {
            $defaults['min_lot'] = 0.001;
            $defaults['lot_step'] = 0.001;
        } else {
            $defaults['min_lot'] = 0.001;
            $defaults['lot_step'] = 0.001;
        }
    }

    return $defaults;
}

function post_value($key, $default = '')
{
    return $_POST[$key] ?? $default;
}

function post_or_default($key, array $defaults, $defaultKey)
{
    $value = post_value($key, '');

    if ($value === '' || $value === null) {
        return $defaults[$defaultKey] ?? '';
    }

    return $value;
}

function repair_symbol_asset_types()
{
    try {
        db()->query("
            UPDATE symbols
            SET asset_type = 'CRYPTO'
            WHERE UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), ' ', '')) LIKE '%BTC%'
               OR UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), ' ', '')) LIKE '%ETH%'
               OR UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), ' ', '')) LIKE '%BNB%'
               OR UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), ' ', '')) LIKE '%SOL%'
               OR UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), ' ', '')) LIKE '%XRP%'
               OR UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), ' ', '')) LIKE '%DOGE%'
               OR UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), ' ', '')) LIKE '%ADA%'
        ");

        db()->query("
            UPDATE symbols
            SET symbol = 'BTCUSD', base_currency = COALESCE(NULLIF(base_currency,''),'BTC'), quote_currency = COALESCE(NULLIF(quote_currency,''),'USD'), asset_type = 'CRYPTO'
            WHERE UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), ' ', '')) IN ('BTCUSD', 'BTCUSDT')
        ");

        db()->query("
            UPDATE symbols
            SET symbol = 'ETHUSD', base_currency = COALESCE(NULLIF(base_currency,''),'ETH'), quote_currency = COALESCE(NULLIF(quote_currency,''),'USD'), asset_type = 'CRYPTO'
            WHERE UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), ' ', '')) IN ('ETHUSD', 'ETHUSDT')
        ");

        db()->query("
            UPDATE symbols
            SET asset_type = 'METAL'
            WHERE UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), ' ', '')) LIKE '%XAU%'
               OR UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), ' ', '')) LIKE '%XAG%'
               OR UPPER(symbol) LIKE '%GOLD%'
               OR UPPER(symbol) LIKE '%SILVER%'
        ");
    } catch (Throwable $e) {
    }
}

$assetTypes = ['FOREX', 'METAL', 'INDICES', 'CRYPTO', 'STOCKS', 'COMMODITY', 'OTHER'];
$newsLevels = ['LOW', 'MEDIUM', 'HIGH'];

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';

        if ($action === 'add_symbol') {
            $symbol = normalize_symbol_code($_POST['new_symbol'] ?? '');

            if ($symbol === '') {
                throw new RuntimeException('Symbol is required.');
            }

            $assetType = detect_asset_type($symbol, $_POST['new_asset_type'] ?? 'OTHER');
            $defaults = symbol_defaults_for($symbol, $assetType);

            $displayName = trim($_POST['new_display_name'] ?? '');
            $base = strtoupper(trim((string)post_or_default('new_base_currency', $defaults, 'base_currency')));
            $quote = strtoupper(trim((string)post_or_default('new_quote_currency', $defaults, 'quote_currency')));

            $stmt = db()->prepare("
                INSERT INTO symbols (
                    symbol,
                    display_name,
                    asset_type,
                    provider,
                    provider_symbol,
                    base_currency,
                    quote_currency,
                    news_currency,
                    decimals,
                    pip_size,
                    point_size,
                    tick_size,
                    tick_value,
                    contract_size,
                    spread_limit,
                    min_lot,
                    lot_step,
                    news_sensitivity,
                    session_preference,
                    min_rr,
                    sort_order,
                    is_core,
                    is_active
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            $stmt->execute([
                $symbol,
                $displayName ?: $symbol,
                $assetType,
                trim((string)post_or_default('new_provider', $defaults, 'provider')),
                trim((string)post_or_default('new_provider_symbol', $defaults, 'provider_symbol')),
                $base,
                $quote,
                strtoupper(trim((string)post_or_default('new_news_currency', $defaults, 'news_currency'))),
                (int)post_or_default('new_decimals', $defaults, 'decimals'),
                (float)post_or_default('new_pip_size', $defaults, 'pip_size'),
                (float)post_or_default('new_point_size', $defaults, 'point_size'),
                (float)post_or_default('new_tick_size', $defaults, 'tick_size'),
                (float)post_or_default('new_tick_value', $defaults, 'tick_value'),
                (float)post_or_default('new_contract_size', $defaults, 'contract_size'),
                (float)post_or_default('new_spread_limit', $defaults, 'spread_limit'),
                (float)post_or_default('new_min_lot', $defaults, 'min_lot'),
                (float)post_or_default('new_lot_step', $defaults, 'lot_step'),
                strtoupper(trim((string)post_or_default('new_news_sensitivity', $defaults, 'news_sensitivity'))),
                trim((string)post_or_default('new_session_preference', $defaults, 'session_preference')),
                (float)post_or_default('new_min_rr', $defaults, 'min_rr'),
                (int)($_POST['new_sort_order'] ?? 999),
                !empty($_POST['new_is_core']) ? 1 : 0,
                !empty($_POST['new_is_active']) ? 1 : 0
            ]);

            repair_symbol_asset_types();

            $message = 'Symbol added successfully.';
        }

        if ($action === 'save_symbol') {
            $id = (int)($_POST['symbol_id'] ?? 0);
            $symbol = normalize_symbol_code($_POST['symbol'] ?? '');

            if ($id <= 0) {
                throw new RuntimeException('Invalid symbol selected.');
            }

            if ($symbol === '') {
                throw new RuntimeException('Symbol is required.');
            }

            $assetType = detect_asset_type($symbol, $_POST['asset_type'] ?? 'OTHER');
            $defaults = symbol_defaults_for($symbol, $assetType);

            $stmt = db()->prepare("
                UPDATE symbols SET
                    symbol = ?,
                    display_name = ?,
                    asset_type = ?,
                    provider = ?,
                    provider_symbol = ?,
                    base_currency = ?,
                    quote_currency = ?,
                    news_currency = ?,
                    decimals = ?,
                    pip_size = ?,
                    point_size = ?,
                    tick_size = ?,
                    tick_value = ?,
                    contract_size = ?,
                    spread_limit = ?,
                    min_lot = ?,
                    lot_step = ?,
                    news_sensitivity = ?,
                    session_preference = ?,
                    min_rr = ?,
                    sort_order = ?,
                    is_core = ?,
                    is_active = ?
                WHERE id = ?
            ");

            $stmt->execute([
                $symbol,
                trim($_POST['display_name'] ?? ''),
                $assetType,
                trim((string)post_or_default('provider', $defaults, 'provider')),
                trim((string)post_or_default('provider_symbol', $defaults, 'provider_symbol')),
                strtoupper(trim((string)post_or_default('base_currency', $defaults, 'base_currency'))),
                strtoupper(trim((string)post_or_default('quote_currency', $defaults, 'quote_currency'))),
                strtoupper(trim((string)post_or_default('news_currency', $defaults, 'news_currency'))),
                (int)post_or_default('decimals', $defaults, 'decimals'),
                (float)post_or_default('pip_size', $defaults, 'pip_size'),
                (float)post_or_default('point_size', $defaults, 'point_size'),
                (float)post_or_default('tick_size', $defaults, 'tick_size'),
                (float)post_or_default('tick_value', $defaults, 'tick_value'),
                (float)post_or_default('contract_size', $defaults, 'contract_size'),
                (float)post_or_default('spread_limit', $defaults, 'spread_limit'),
                (float)post_or_default('min_lot', $defaults, 'min_lot'),
                (float)post_or_default('lot_step', $defaults, 'lot_step'),
                strtoupper(trim((string)post_or_default('news_sensitivity', $defaults, 'news_sensitivity'))),
                trim((string)post_or_default('session_preference', $defaults, 'session_preference')),
                (float)post_or_default('min_rr', $defaults, 'min_rr'),
                (int)($_POST['sort_order'] ?? 999),
                !empty($_POST['is_core']) ? 1 : 0,
                !empty($_POST['is_active']) ? 1 : 0,
                $id
            ]);

            repair_symbol_asset_types();

            $message = 'Symbol updated successfully.';
        }

        if ($action === 'delete_symbol') {
            $id = (int)($_POST['delete_id'] ?? 0);

            if ($id <= 0) {
                throw new RuntimeException('Invalid symbol selected for deletion.');
            }

            db()->prepare("DELETE FROM symbols WHERE id = ?")->execute([$id]);

            $message = 'Symbol deleted successfully.';
        }
    }

    repair_symbol_asset_types();

} catch (Throwable $e) {
    $error = $e->getMessage();
}

$symbols = [];

try {
    $symbols = db()->query("
        SELECT *
        FROM symbols
        ORDER BY
            CASE UPPER(asset_type)
                WHEN 'FOREX' THEN 1
                WHEN 'METAL' THEN 2
                WHEN 'INDICES' THEN 3
                WHEN 'CRYPTO' THEN 4
                WHEN 'STOCKS' THEN 5
                WHEN 'COMMODITY' THEN 6
                ELSE 99
            END ASC,
            sort_order ASC,
            symbol ASC
    ")->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$grouped = [];

foreach ($symbols as $symbol) {
    $group = canonical_asset_type($symbol['asset_type'] ?? 'OTHER');
    $grouped[$group][] = $symbol;
}

$stats = [
    'total' => count($symbols),
    'active' => 0,
    'core' => 0,
    'forex' => 0,
    'metal' => 0,
    'indices' => 0,
    'crypto' => 0,
];

foreach ($symbols as $symbol) {
    if (!empty($symbol['is_active'])) {
        $stats['active']++;
    }

    if (!empty($symbol['is_core'])) {
        $stats['core']++;
    }

    $type = strtolower(canonical_asset_type($symbol['asset_type'] ?? 'OTHER'));

    if (isset($stats[$type])) {
        $stats[$type]++;
    }
}

admin_layout_header('Symbol Management');

?>

<style>
.symbol-page{max-width:1450px;margin:0 auto}.symbol-hero{display:flex;justify-content:space-between;align-items:flex-end;gap:24px;margin-bottom:24px}.symbol-title{font-size:42px;font-weight:900;letter-spacing:-.05em;color:#020617;line-height:1}.symbol-sub{margin-top:8px;color:#64748b;font-size:15px}.symbol-stats{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:12px;margin-bottom:20px}.symbol-stat{background:#fff;border:1px solid #e2e8f0;border-radius:22px;padding:16px;box-shadow:0 8px 22px rgba(15,23,42,.04)}.symbol-stat span{display:block;font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:#64748b;font-weight:900}.symbol-stat strong{display:block;margin-top:6px;font-size:26px;font-weight:900;color:#020617}.symbol-alert{padding:14px 18px;border-radius:16px;margin-bottom:16px;font-weight:800}.symbol-success{background:#ecfdf5;border:1px solid #a7f3d0;color:#047857}.symbol-error{background:#fef2f2;border:1px solid #fecaca;color:#b91c1c}.symbol-panel{background:#fff;border:1px solid #e2e8f0;border-radius:28px;box-shadow:0 10px 28px rgba(15,23,42,.045);overflow:hidden;margin-bottom:24px}.symbol-panel-head{padding:22px 24px;border-bottom:1px solid #e2e8f0;background:#f8fafc;display:flex;justify-content:space-between;align-items:center;gap:18px}.symbol-panel-title{font-size:24px;font-weight:900;color:#020617}.symbol-panel-sub{margin-top:4px;color:#64748b;font-size:13px}.symbol-add-grid{padding:22px 24px;display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:12px}.symbol-field label{display:block;margin-bottom:6px;font-size:10px;font-weight:900;text-transform:uppercase;letter-spacing:.07em;color:#64748b}.symbol-input,.symbol-select{width:100%;height:42px;border:1px solid #cbd5e1;border-radius:13px;padding:0 12px;font-size:13px;font-weight:750;color:#0f172a;background:#fff}.symbol-input:focus,.symbol-select:focus{outline:none;border-color:#2563eb;box-shadow:0 0 0 3px rgba(37,99,235,.10)}.symbol-add-actions{padding:16px 24px;border-top:1px solid #e2e8f0;background:#f8fafc;display:flex;justify-content:space-between;align-items:center;gap:12px}.symbol-checks{display:flex;gap:16px;flex-wrap:wrap;color:#334155;font-size:13px;font-weight:800}.symbol-btn{height:42px;border:0;border-radius:14px;padding:0 18px;font-weight:900;font-size:13px;cursor:pointer}.symbol-btn-dark{background:#020617;color:#fff}.symbol-btn-blue{background:#2563eb;color:#fff}.symbol-btn-soft{background:#eff6ff;color:#1d4ed8}.symbol-btn-red{background:#fef2f2;color:#b91c1c;border:1px solid #fecaca}.symbol-toolbar{padding:18px 24px;display:grid;grid-template-columns:1.7fr 1fr 1fr 1fr;gap:12px;border-bottom:1px solid #e2e8f0;background:#fff}.symbol-table-wrap{overflow-x:auto}.symbol-table{width:100%;border-collapse:separate;border-spacing:0}.symbol-table th{background:#f8fafc;color:#64748b;font-size:11px;text-transform:uppercase;letter-spacing:.07em;text-align:left;padding:13px 16px;border-bottom:1px solid #e2e8f0}.symbol-table td{padding:14px 16px;border-bottom:1px solid #edf2f7;font-size:13px;color:#0f172a;vertical-align:middle}.symbol-code{font-size:15px;font-weight:900;color:#020617}.symbol-name{margin-top:3px;color:#64748b;font-size:12px;font-weight:700}.symbol-muted{color:#64748b;font-size:12px;font-weight:700}.symbol-badge{display:inline-flex;align-items:center;height:26px;padding:0 10px;border-radius:999px;font-size:10px;font-weight:900;background:#ecfeff;color:#0f766e}.symbol-status{display:inline-flex;align-items:center;height:26px;padding:0 10px;border-radius:999px;font-size:10px;font-weight:900}.status-active{background:#dcfce7;color:#166534}.status-off{background:#fee2e2;color:#991b1b}.symbol-actions{display:flex;gap:8px;justify-content:flex-end}.modal-backdrop{display:none;position:fixed;inset:0;background:rgba(15,23,42,.60);z-index:9998;align-items:center;justify-content:center;padding:20px}.modal-backdrop.is-open{display:flex}.symbol-modal{width:min(980px,100%);max-height:92vh;overflow:auto;background:#fff;border-radius:28px;box-shadow:0 24px 80px rgba(2,6,23,.30);border:1px solid #e2e8f0}.symbol-modal-head{padding:22px 24px;border-bottom:1px solid #e2e8f0;display:flex;justify-content:space-between;align-items:flex-start;gap:16px;background:linear-gradient(135deg,#f8fafc,#fff)}.symbol-modal-title{font-size:28px;font-weight:900;color:#020617;letter-spacing:-.04em}.symbol-modal-sub{margin-top:4px;color:#64748b;font-size:13px}.symbol-modal-body{padding:24px;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px}.symbol-modal-footer{padding:18px 24px;background:#f8fafc;border-top:1px solid #e2e8f0;display:flex;justify-content:space-between;align-items:center;gap:12px}.symbol-close{border:0;background:#f1f5f9;color:#0f172a;border-radius:14px;height:38px;width:38px;font-weight:900;cursor:pointer}.symbol-hidden{display:none!important}.symbol-section-label{grid-column:1/-1;font-size:11px;font-weight:900;color:#2563eb;text-transform:uppercase;letter-spacing:.08em;margin-top:6px}@media(max-width:1100px){.symbol-stats{grid-template-columns:repeat(3,minmax(0,1fr))}.symbol-add-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.symbol-toolbar{grid-template-columns:1fr 1fr}.symbol-modal-body{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:700px){.symbol-hero{display:block}.symbol-stats,.symbol-add-grid,.symbol-toolbar,.symbol-modal-body{grid-template-columns:1fr}.symbol-panel-head{display:block}.symbol-add-actions,.symbol-modal-footer{align-items:stretch;flex-direction:column}.symbol-btn{width:100%}}
</style>

<div class="symbol-page">

    <div class="symbol-hero">
        <div>
            <h1 class="symbol-title">Symbol Management</h1>
            <p class="symbol-sub">Compact institutional symbol manager with asset-aware metadata for forex, metals, indices and crypto.</p>
        </div>
    </div>

    <div class="symbol-stats">
        <div class="symbol-stat"><span>Total</span><strong><?= e($stats['total']) ?></strong></div>
        <div class="symbol-stat"><span>Active</span><strong><?= e($stats['active']) ?></strong></div>
        <div class="symbol-stat"><span>Core</span><strong><?= e($stats['core']) ?></strong></div>
        <div class="symbol-stat"><span>Forex</span><strong><?= e($stats['forex']) ?></strong></div>
        <div class="symbol-stat"><span>Metals</span><strong><?= e($stats['metal']) ?></strong></div>
        <div class="symbol-stat"><span>Crypto</span><strong><?= e($stats['crypto']) ?></strong></div>
    </div>

    <?php if ($message): ?><div class="symbol-alert symbol-success"><?= e($message) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="symbol-alert symbol-error"><?= e($error) ?></div><?php endif; ?>

    <form method="post" class="symbol-panel">
        <input type="hidden" name="action" value="add_symbol">

        <div class="symbol-panel-head">
            <div>
                <div class="symbol-panel-title">Add Symbol</div>
                <div class="symbol-panel-sub">For Silver use XAGUSD with provider symbol XAG/USD. Provider symbol must match the data provider. Crypto accepts small lot values such as 0.001 or 0.0001.</div>
            </div>
        </div>

        <div class="symbol-add-grid">
            <div class="symbol-field"><label>Symbol</label><input class="symbol-input" name="new_symbol" placeholder="XAGUSD"></div>
            <div class="symbol-field"><label>Display Name</label><input class="symbol-input" name="new_display_name" placeholder="Silver / US Dollar"></div>
            <div class="symbol-field"><label>Asset Type</label><select class="symbol-select" name="new_asset_type"><?php foreach ($assetTypes as $type): ?><option value="<?= e($type) ?>"><?= e($type) ?></option><?php endforeach; ?></select></div>
            <div class="symbol-field"><label>Provider</label><input class="symbol-input" name="new_provider" value="twelvedata"></div>
            <div class="symbol-field"><label>Provider Symbol</label><input class="symbol-input" name="new_provider_symbol" placeholder="XAG/USD"></div>
            <div class="symbol-field"><label>News Currency</label><input class="symbol-input" name="new_news_currency" placeholder="USD"></div>

            <div class="symbol-field"><label>Base</label><input class="symbol-input" name="new_base_currency" placeholder="XAG"></div>
            <div class="symbol-field"><label>Quote</label><input class="symbol-input" name="new_quote_currency" placeholder="USD"></div>
            <div class="symbol-field"><label>Decimals</label><input class="symbol-input" type="number" name="new_decimals" placeholder="3"></div>
            <div class="symbol-field"><label>Pip Size</label><input class="symbol-input" type="number" step="0.00000001" name="new_pip_size" placeholder="0.01"></div>
            <div class="symbol-field"><label>Point Size</label><input class="symbol-input" type="number" step="0.00000001" name="new_point_size" placeholder="0.001"></div>
            <div class="symbol-field"><label>Tick Size</label><input class="symbol-input" type="number" step="0.00000001" name="new_tick_size" placeholder="0.001"></div>

            <div class="symbol-field"><label>Tick Value</label><input class="symbol-input" type="number" step="0.00000001" name="new_tick_value" placeholder="1"></div>
            <div class="symbol-field"><label>Contract</label><input class="symbol-input" type="number" step="0.01" name="new_contract_size" placeholder="5000"></div>
            <div class="symbol-field"><label>Spread</label><input class="symbol-input" type="number" step="0.00001" name="new_spread_limit" placeholder="50"></div>
            <div class="symbol-field"><label>Min Lot</label><input class="symbol-input" type="number" step="0.000001" min="0.000001" name="new_min_lot" placeholder="0.001"></div>
            <div class="symbol-field"><label>Lot Step</label><input class="symbol-input" type="number" step="0.000001" min="0.000001" name="new_lot_step" placeholder="0.001"></div>
            <div class="symbol-field"><label>News Level</label><select class="symbol-select" name="new_news_sensitivity"><?php foreach ($newsLevels as $level): ?><option value="<?= e($level) ?>"><?= e($level) ?></option><?php endforeach; ?></select></div>

            <div class="symbol-field"><label>Session</label><input class="symbol-input" name="new_session_preference" placeholder="London/New York"></div>
            <div class="symbol-field"><label>Min RR</label><input class="symbol-input" type="number" step="0.01" name="new_min_rr" placeholder="2.00"></div>
            <div class="symbol-field"><label>Sort</label><input class="symbol-input" type="number" name="new_sort_order" value="999"></div>
        </div>

        <div class="symbol-add-actions">
            <div class="symbol-checks">
                <label><input type="checkbox" name="new_is_core" value="1"> Core Symbol</label>
                <label><input type="checkbox" name="new_is_active" value="1" checked> Active</label>
            </div>
            <button class="symbol-btn symbol-btn-dark">Add Symbol</button>
        </div>
    </form>

    <section class="symbol-panel">
        <div class="symbol-panel-head">
            <div>
                <div class="symbol-panel-title">Tradable Symbols</div>
                <div class="symbol-panel-sub">Search and manage routing, price precision, pip size and risk metadata.</div>
            </div>
        </div>

        <div class="symbol-toolbar">
            <input class="symbol-input" id="symbolSearch" placeholder="Search symbol, name, provider, base, quote...">
            <select class="symbol-select" id="typeFilter">
                <option value="">All Asset Types</option>
                <?php foreach ($assetTypes as $type): ?>
                    <option value="<?= e($type) ?>"><?= e($type) ?></option>
                <?php endforeach; ?>
            </select>
            <select class="symbol-select" id="activeFilter">
                <option value="">All Status</option>
                <option value="active">Active Only</option>
                <option value="inactive">Inactive Only</option>
            </select>
            <select class="symbol-select" id="coreFilter">
                <option value="">All Symbols</option>
                <option value="core">Core Only</option>
                <option value="noncore">Non-Core Only</option>
            </select>
        </div>

        <div class="symbol-table-wrap">
            <table class="symbol-table" id="symbolsTable">
                <thead>
                    <tr>
                        <th>Symbol</th>
                        <th>Asset</th>
                        <th>Provider</th>
                        <th>Base / Quote</th>
                        <th>Precision</th>
                        <th>Risk Metadata</th>
                        <th>Status</th>
                        <th style="text-align:right;">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($symbols as $row): ?>
                        <?php
                            $assetType = canonical_asset_type(sym($row, 'asset_type'));
                            $isActive = !empty($row['is_active']);
                            $isCore = !empty($row['is_core']);
                            $searchBlob = strtolower(
                                sym($row, 'symbol') . ' ' .
                                sym($row, 'display_name') . ' ' .
                                $assetType . ' ' .
                                sym($row, 'provider') . ' ' .
                                sym($row, 'provider_symbol') . ' ' .
                                sym($row, 'base_currency') . ' ' .
                                sym($row, 'quote_currency') . ' ' .
                                sym($row, 'news_currency')
                            );
                        ?>
                        <tr
                            data-search="<?= e($searchBlob) ?>"
                            data-type="<?= e($assetType) ?>"
                            data-active="<?= $isActive ? 'active' : 'inactive' ?>"
                            data-core="<?= $isCore ? 'core' : 'noncore' ?>"
                        >
                            <td>
                                <div class="symbol-code"><?= e(sym($row, 'symbol')) ?></div>
                                <div class="symbol-name"><?= e(sym($row, 'display_name')) ?></div>
                            </td>
                            <td><span class="symbol-badge"><?= e($assetType) ?></span></td>
                            <td>
                                <strong><?= e(sym($row, 'provider', 'twelvedata')) ?></strong>
                                <div class="symbol-muted"><?= e(sym($row, 'provider_symbol')) ?></div>
                            </td>
                            <td>
                                <?= e(sym($row, 'base_currency')) ?> / <?= e(sym($row, 'quote_currency')) ?>
                                <div class="symbol-muted">News: <?= e(sym($row, 'news_currency')) ?></div>
                            </td>
                            <td>
                                Dec: <?= e(sym($row, 'decimals', 2)) ?>
                                <div class="symbol-muted">Pip: <?= e(sym($row, 'pip_size')) ?> | Point: <?= e(sym($row, 'point_size')) ?></div>
                            </td>
                            <td>
                                Contract: <?= e(sym($row, 'contract_size')) ?>
                                <div class="symbol-muted">Min: <?= e(sym($row, 'min_lot')) ?> | Step: <?= e(sym($row, 'lot_step')) ?></div>
                            </td>
                            <td>
                                <span class="symbol-status <?= $isActive ? 'status-active' : 'status-off' ?>">
                                    <?= $isActive ? 'ACTIVE' : 'DISABLED' ?>
                                </span>
                            </td>
                            <td>
                                <div class="symbol-actions">
                                    <button
                                        type="button"
                                        class="symbol-btn symbol-btn-soft js-open-symbol"
                                        data-id="<?= e(sym($row, 'id')) ?>"
                                        data-symbol="<?= e(sym($row, 'symbol')) ?>"
                                        data-display_name="<?= e(sym($row, 'display_name')) ?>"
                                        data-asset_type="<?= e($assetType) ?>"
                                        data-provider="<?= e(sym($row, 'provider', 'twelvedata')) ?>"
                                        data-provider_symbol="<?= e(sym($row, 'provider_symbol')) ?>"
                                        data-news_currency="<?= e(sym($row, 'news_currency')) ?>"
                                        data-news_sensitivity="<?= e(strtoupper(sym($row, 'news_sensitivity', 'MEDIUM'))) ?>"
                                        data-base_currency="<?= e(sym($row, 'base_currency')) ?>"
                                        data-quote_currency="<?= e(sym($row, 'quote_currency')) ?>"
                                        data-decimals="<?= e(sym($row, 'decimals', 2)) ?>"
                                        data-pip_size="<?= e(sym($row, 'pip_size')) ?>"
                                        data-point_size="<?= e(sym($row, 'point_size')) ?>"
                                        data-tick_size="<?= e(sym($row, 'tick_size')) ?>"
                                        data-tick_value="<?= e(sym($row, 'tick_value')) ?>"
                                        data-contract_size="<?= e(sym($row, 'contract_size', 1)) ?>"
                                        data-spread_limit="<?= e(sym($row, 'spread_limit', 0)) ?>"
                                        data-min_lot="<?= e(sym($row, 'min_lot', 0.01)) ?>"
                                        data-lot_step="<?= e(sym($row, 'lot_step', 0.01)) ?>"
                                        data-session_preference="<?= e(sym($row, 'session_preference')) ?>"
                                        data-min_rr="<?= e(sym($row, 'min_rr', 1.5)) ?>"
                                        data-sort_order="<?= e(sym($row, 'sort_order', 999)) ?>"
                                        data-is_core="<?= $isCore ? '1' : '0' ?>"
                                        data-is_active="<?= $isActive ? '1' : '0' ?>"
                                    >
                                        View / Edit
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>

                    <?php if (!$symbols): ?>
                        <tr><td colspan="8" style="text-align:center;color:#64748b;padding:28px;font-weight:800;">No symbols found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>

</div>

<div class="modal-backdrop" id="symbolModal">
    <form method="post" class="symbol-modal">
        <input type="hidden" name="action" value="save_symbol">
        <input type="hidden" name="symbol_id" id="modal_symbol_id">

        <div class="symbol-modal-head">
            <div>
                <div class="symbol-modal-title" id="modalTitle">Edit Symbol</div>
                <div class="symbol-modal-sub">Update routing, risk, precision and execution settings.</div>
            </div>
            <button type="button" class="symbol-close" id="closeModal">×</button>
        </div>

        <div class="symbol-modal-body">
            <div class="symbol-section-label">Identity</div>
            <div class="symbol-field"><label>Symbol</label><input class="symbol-input" name="symbol" id="modal_symbol"></div>
            <div class="symbol-field"><label>Display Name</label><input class="symbol-input" name="display_name" id="modal_display_name"></div>
            <div class="symbol-field"><label>Asset Type</label><select class="symbol-select" name="asset_type" id="modal_asset_type"><?php foreach ($assetTypes as $type): ?><option value="<?= e($type) ?>"><?= e($type) ?></option><?php endforeach; ?></select></div>
            <div class="symbol-field"><label>News Level</label><select class="symbol-select" name="news_sensitivity" id="modal_news_sensitivity"><?php foreach ($newsLevels as $level): ?><option value="<?= e($level) ?>"><?= e($level) ?></option><?php endforeach; ?></select></div>

            <div class="symbol-section-label">Data Provider</div>
            <div class="symbol-field"><label>Provider</label><input class="symbol-input" name="provider" id="modal_provider"></div>
            <div class="symbol-field"><label>Provider Symbol</label><input class="symbol-input" name="provider_symbol" id="modal_provider_symbol"></div>
            <div class="symbol-field"><label>News Currency</label><input class="symbol-input" name="news_currency" id="modal_news_currency"></div>

            <div class="symbol-section-label">Price & Contract Metadata</div>
            <div class="symbol-field"><label>Base</label><input class="symbol-input" name="base_currency" id="modal_base_currency"></div>
            <div class="symbol-field"><label>Quote</label><input class="symbol-input" name="quote_currency" id="modal_quote_currency"></div>
            <div class="symbol-field"><label>Decimals</label><input class="symbol-input" type="number" name="decimals" id="modal_decimals"></div>
            <div class="symbol-field"><label>Pip Size</label><input class="symbol-input" type="number" step="0.00000001" name="pip_size" id="modal_pip_size"></div>
            <div class="symbol-field"><label>Point Size</label><input class="symbol-input" type="number" step="0.00000001" name="point_size" id="modal_point_size"></div>
            <div class="symbol-field"><label>Tick Size</label><input class="symbol-input" type="number" step="0.00000001" name="tick_size" id="modal_tick_size"></div>
            <div class="symbol-field"><label>Tick Value</label><input class="symbol-input" type="number" step="0.00000001" name="tick_value" id="modal_tick_value"></div>
            <div class="symbol-field"><label>Contract Size</label><input class="symbol-input" type="number" step="0.01" name="contract_size" id="modal_contract_size"></div>
            <div class="symbol-field"><label>Min Lot</label><input class="symbol-input" type="number" step="0.000001" min="0.000001" name="min_lot" id="modal_min_lot"></div>
            <div class="symbol-field"><label>Lot Step</label><input class="symbol-input" type="number" step="0.000001" min="0.000001" name="lot_step" id="modal_lot_step"></div>

            <div class="symbol-section-label">Trading Rules</div>
            <div class="symbol-field"><label>Spread Limit</label><input class="symbol-input" type="number" step="0.00001" name="spread_limit" id="modal_spread_limit"></div>
            <div class="symbol-field"><label>Session</label><input class="symbol-input" name="session_preference" id="modal_session_preference"></div>
            <div class="symbol-field"><label>Minimum RR</label><input class="symbol-input" type="number" step="0.01" name="min_rr" id="modal_min_rr"></div>
            <div class="symbol-field"><label>Sort Order</label><input class="symbol-input" type="number" name="sort_order" id="modal_sort_order"></div>
        </div>

        <div class="symbol-modal-footer">
            <div class="symbol-checks">
                <label><input type="checkbox" name="is_core" value="1" id="modal_is_core"> Core Symbol</label>
                <label><input type="checkbox" name="is_active" value="1" id="modal_is_active"> Active</label>
            </div>
            <div class="symbol-actions">
                <button type="button" class="symbol-btn symbol-btn-red" id="deleteFromModal">Delete</button>
                <button class="symbol-btn symbol-btn-blue">Save Changes</button>
            </div>
        </div>
    </form>
</div>

<form method="post" id="deleteSymbolForm" class="symbol-hidden" onsubmit="return confirm('Delete this symbol?');">
    <input type="hidden" name="action" value="delete_symbol">
    <input type="hidden" name="delete_id" id="delete_symbol_id">
</form>

<script>
(function(){
    const modal = document.getElementById('symbolModal');
    const closeModal = document.getElementById('closeModal');
    const deleteBtn = document.getElementById('deleteFromModal');
    const deleteForm = document.getElementById('deleteSymbolForm');
    const deleteId = document.getElementById('delete_symbol_id');

    function setValue(id, value) {
        const el = document.getElementById(id);
        if (el) el.value = value || '';
    }

    document.querySelectorAll('.js-open-symbol').forEach(function(button){
        button.addEventListener('click', function(){
            const d = button.dataset;

            setValue('modal_symbol_id', d.id);
            setValue('modal_symbol', d.symbol);
            setValue('modal_display_name', d.display_name);
            setValue('modal_asset_type', d.asset_type);
            setValue('modal_news_sensitivity', d.news_sensitivity || 'MEDIUM');
            setValue('modal_provider', d.provider || 'twelvedata');
            setValue('modal_provider_symbol', d.provider_symbol);
            setValue('modal_news_currency', d.news_currency);
            setValue('modal_base_currency', d.base_currency);
            setValue('modal_quote_currency', d.quote_currency);
            setValue('modal_decimals', d.decimals);
            setValue('modal_pip_size', d.pip_size);
            setValue('modal_point_size', d.point_size);
            setValue('modal_tick_size', d.tick_size);
            setValue('modal_tick_value', d.tick_value);
            setValue('modal_contract_size', d.contract_size);
            setValue('modal_spread_limit', d.spread_limit);
            setValue('modal_min_lot', d.min_lot);
            setValue('modal_lot_step', d.lot_step);
            setValue('modal_session_preference', d.session_preference);
            setValue('modal_min_rr', d.min_rr);
            setValue('modal_sort_order', d.sort_order);

            document.getElementById('modal_is_core').checked = d.is_core === '1';
            document.getElementById('modal_is_active').checked = d.is_active === '1';
            document.getElementById('modalTitle').textContent = d.symbol + ' Settings';

            modal.classList.add('is-open');
        });
    });

    closeModal.addEventListener('click', function(){
        modal.classList.remove('is-open');
    });

    modal.addEventListener('click', function(e){
        if (e.target === modal) {
            modal.classList.remove('is-open');
        }
    });

    deleteBtn.addEventListener('click', function(){
        deleteId.value = document.getElementById('modal_symbol_id').value;
        deleteForm.submit();
    });

    const search = document.getElementById('symbolSearch');
    const typeFilter = document.getElementById('typeFilter');
    const activeFilter = document.getElementById('activeFilter');
    const coreFilter = document.getElementById('coreFilter');
    const rows = Array.from(document.querySelectorAll('#symbolsTable tbody tr[data-search]'));

    function applyFilters() {
        const q = (search.value || '').toLowerCase().trim();
        const type = typeFilter.value || '';
        const active = activeFilter.value || '';
        const core = coreFilter.value || '';

        rows.forEach(function(row){
            const matchSearch = !q || row.dataset.search.includes(q);
            const matchType = !type || row.dataset.type === type;
            const matchActive = !active || row.dataset.active === active;
            const matchCore = !core || row.dataset.core === core;

            row.style.display = (matchSearch && matchType && matchActive && matchCore) ? '' : 'none';
        });
    }

    [search, typeFilter, activeFilter, coreFilter].forEach(function(el){
        el.addEventListener('input', applyFilters);
        el.addEventListener('change', applyFilters);
    });
})();
</script>

<?php admin_layout_footer(); ?>
