<?php

require_once __DIR__ . '/admin_tool_helper.php';

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

function api_col_exists($column)
{
    try {
        $stmt = db()->prepare("SHOW COLUMNS FROM api_settings LIKE ?");
        $stmt->execute([$column]);
        return (bool)$stmt->fetchColumn();
    } catch (Throwable $e) {
        return false;
    }
}


function api_ensure_rotation_columns(): void
{
    try {
        if (!api_col_exists('last_used_at')) {
            db()->exec("ALTER TABLE api_settings ADD COLUMN last_used_at DATETIME NULL AFTER cooldown_until");
        }
    } catch (Throwable $e) {}

    try {
        if (!api_col_exists('reset_date')) {
            db()->exec("ALTER TABLE api_settings ADD COLUMN reset_date DATE NULL AFTER used_today");
        }
    } catch (Throwable $e) {}

    try {
        if (!api_col_exists('last_error')) {
            db()->exec("ALTER TABLE api_settings ADD COLUMN last_error TEXT NULL AFTER cooldown_until");
        }
    } catch (Throwable $e) {}
}

api_ensure_rotation_columns();


function api_table_exists(string $table): bool
{
    try {
        $stmt = db()->prepare("SHOW TABLES LIKE ?");
        $stmt->execute([$table]);
        return (bool)$stmt->fetchColumn();
    } catch (Throwable $e) {
        return false;
    }
}

function api_upsert_system_setting(string $key, string $value): void
{
    if (!api_table_exists('system_settings')) {
        return;
    }

    try {
        $stmt = db()->prepare("SELECT id FROM system_settings WHERE setting_key = ? ORDER BY id DESC LIMIT 1");
        $stmt->execute([$key]);
        $id = (int)$stmt->fetchColumn();

        if ($id > 0) {
            db()->prepare("UPDATE system_settings SET setting_value = ? WHERE id = ?")->execute([$value, $id]);
        } else {
            db()->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES (?, ?)")->execute([$key, $value]);
        }
    } catch (Throwable $e) {
        // Settings are optional; do not break API Settings if the table schema differs.
    }
}

function api_clear_fmp_metal_errors(): void
{
    if (!api_col_exists('last_error')) {
        return;
    }

    $sets = ['last_error = NULL'];
    if (api_col_exists('cooldown_until')) $sets[] = 'cooldown_until = NULL';
    if (api_col_exists('fail_count')) $sets[] = 'fail_count = 0';

    db()->exec("UPDATE api_settings SET " . implode(', ', $sets) . "
        WHERE LOWER(provider) IN ('fmp','financialmodelingprep','financial_modeling_prep')
          AND (
            last_error LIKE '%GCUSD%' OR last_error LIKE '%ZGUSD%' OR last_error LIKE '%XAUUSD%' OR
            last_error LIKE '%SIUSD%' OR last_error LIKE '%ZIUSD%' OR last_error LIKE '%XAGUSD%' OR
            last_error LIKE '%commodity%' OR last_error LIKE '%Restricted Endpoint%' OR
            last_error LIKE '%not available under your current subscription%'
          )");
}

function api_normalize_provider_name(string $provider): string
{
    $provider = strtolower(trim($provider));
    $map = [
        'financialmodelingprep' => 'fmp',
        'financial_modeling_prep' => 'fmp',
        'twelve_data' => 'twelvedata',
        'twelve-data' => 'twelvedata',
        'alpha-vantage' => 'alphavantage',
        'alpha_vantage' => 'alphavantage',
        'goldapi.io' => 'goldapiio',
        'goldapi' => 'goldapiio',
        'gold-api.com' => 'gold-api',
        'metals-api' => 'metalsapi',
        'metalprice-api' => 'metalpriceapi',
    ];
    return $map[$provider] ?? $provider;
}

function api_recommended_providers(): array
{
    return [
        'binance' => [
            'provider' => 'binance',
            'provider_type' => 'crypto_public',
            'base_url' => 'https://api.binance.com',
            'daily_limit' => 0,
            'priority_order' => 5,
            'supports_candles' => 1,
            'supports_quote' => 1,
            'supports_usage' => 0,
            'is_active' => 1,
        ],
        'goldapiio' => [
            'provider' => 'goldapiio',
            'provider_type' => 'metals_quote',
            'base_url' => 'https://www.goldapi.io/api',
            'daily_limit' => 0,
            'priority_order' => 10,
            'supports_candles' => 0,
            'supports_quote' => 1,
            'supports_usage' => 0,
            'is_active' => 0,
        ],
        'gold-api' => [
            'provider' => 'gold-api',
            'provider_type' => 'metals_public_quote',
            'base_url' => 'https://api.gold-api.com',
            'daily_limit' => 0,
            'priority_order' => 20,
            'supports_candles' => 0,
            'supports_quote' => 1,
            'supports_usage' => 0,
            'is_active' => 1,
        ],
        'fmp' => [
            'provider' => 'fmp',
            'provider_type' => 'market_data',
            'base_url' => 'https://financialmodelingprep.com',
            'daily_limit' => 250,
            'priority_order' => 30,
            'supports_candles' => 1,
            'supports_quote' => 1,
            'supports_usage' => 0,
            'is_active' => 1,
        ],
        'twelvedata' => [
            'provider' => 'twelvedata',
            'provider_type' => 'market_data',
            'base_url' => 'https://api.twelvedata.com',
            'daily_limit' => 800,
            'priority_order' => 40,
            'supports_candles' => 1,
            'supports_quote' => 1,
            'supports_usage' => 0,
            'is_active' => 1,
        ],
        'finnhub' => [
            'provider' => 'finnhub',
            'provider_type' => 'market_quote',
            'base_url' => 'https://finnhub.io/api/v1',
            'daily_limit' => 60,
            'priority_order' => 50,
            'supports_candles' => 0,
            'supports_quote' => 1,
            'supports_usage' => 0,
            'is_active' => 0,
        ],
        'alphavantage' => [
            'provider' => 'alphavantage',
            'provider_type' => 'market_quote',
            'base_url' => 'https://www.alphavantage.co',
            'daily_limit' => 25,
            'priority_order' => 60,
            'supports_candles' => 0,
            'supports_quote' => 1,
            'supports_usage' => 0,
            'is_active' => 0,
        ],
        'metalsapi' => [
            'provider' => 'metalsapi',
            'provider_type' => 'metals_quote',
            'base_url' => 'https://api.metals-api.com',
            'daily_limit' => 0,
            'priority_order' => 70,
            'supports_candles' => 0,
            'supports_quote' => 1,
            'supports_usage' => 0,
            'is_active' => 0,
        ],
        'metalpriceapi' => [
            'provider' => 'metalpriceapi',
            'provider_type' => 'metals_quote',
            'base_url' => 'https://api.metalpriceapi.com',
            'daily_limit' => 0,
            'priority_order' => 80,
            'supports_candles' => 0,
            'supports_quote' => 1,
            'supports_usage' => 0,
            'is_active' => 0,
        ],
    ];
}

function api_insert_or_update_provider(array $defaults, array $existingColumns): string
{
    $provider = api_normalize_provider_name((string)($defaults['provider'] ?? ''));
    if ($provider === '') {
        return 'skipped';
    }

    $stmt = db()->prepare("SELECT * FROM api_settings WHERE LOWER(provider) = LOWER(?) ORDER BY is_active DESC, priority_order ASC, id ASC LIMIT 1");
    $stmt->execute([$provider]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

    if ($row) {
        $sets = [];
        $params = [];
        foreach ($defaults as $column => $value) {
            if (!in_array($column, $existingColumns, true)) {
                continue;
            }
            if ($column === 'api_key' || $column === 'used_today' || $column === 'fail_count' || $column === 'cooldown_until' || $column === 'last_error') {
                continue;
            }
            if ($column === 'daily_limit' && (int)($row[$column] ?? 0) > 0) {
                continue;
            }
            if (in_array($column, ['base_url', 'provider_type'], true) && trim((string)($row[$column] ?? '')) !== '') {
                continue;
            }
            $sets[] = "`$column` = ?";
            $params[] = $value;
        }
        if ($sets) {
            $params[] = (int)$row['id'];
            db()->prepare("UPDATE api_settings SET " . implode(', ', $sets) . " WHERE id = ?")->execute($params);
            return 'updated';
        }
        return 'exists';
    }

    $insertColumns = [];
    $placeholders = [];
    $params = [];
    foreach ($existingColumns as $column) {
        if ($column === 'api_key') {
            $value = '';
        } elseif ($column === 'used_today' || $column === 'fail_count') {
            $value = 0;
        } elseif (in_array($column, ['cooldown_until','last_used_at','reset_date','last_error'], true)) {
            $value = null;
        } else {
            $value = $defaults[$column] ?? '';
        }
        $insertColumns[] = "`$column`";
        $placeholders[] = '?';
        $params[] = $value;
    }

    db()->prepare("INSERT INTO api_settings (" . implode(', ', $insertColumns) . ") VALUES (" . implode(', ', $placeholders) . ")")->execute($params);
    return 'inserted';
}

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

$columns = [
    'provider',
    'provider_type',
    'api_key',
    'base_url',
    'daily_limit',
    'used_today',
    'priority_order',
    'fail_count',
    'cooldown_until',
    'last_used_at',
    'reset_date',
    'last_error',
    'supports_candles',
    'supports_quote',
    'supports_usage',
    'is_active'
];

$existing = [];

foreach ($columns as $column) {
    if (api_col_exists($column)) {
        $existing[] = $column;
    }
}

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

        if ($action === 'save') {
            foreach ($_POST['apis'] ?? [] as $id => $row) {
                $sets = [];
                $params = [];

                foreach ($existing as $column) {
                    if ($column === 'used_today' || $column === 'fail_count' || $column === 'daily_limit' || $column === 'priority_order') {
                        $value = (int)($row[$column] ?? 0);
                    } elseif (in_array($column, ['is_active', 'supports_candles', 'supports_quote', 'supports_usage'], true)) {
                        $value = !empty($row[$column]) ? 1 : 0;
                    } else {
                        $value = trim((string)($row[$column] ?? ''));
                    }

                    if ($column === 'provider') {
                        $value = api_normalize_provider_name($value);
                    }
                    if (in_array($column, ['cooldown_until','last_used_at','reset_date','last_error'], true) && trim((string)$value) === '') {
                        $value = null;
                    }

                    $sets[] = "`$column` = ?";
                    $params[] = $value;
                }

                if ($sets) {
                    $params[] = (int)$id;
                    db()->prepare("UPDATE api_settings SET " . implode(', ', $sets) . " WHERE id = ?")->execute($params);
                }
            }

            $message = 'API providers updated successfully.';
        }

        if ($action === 'add') {
            $insertColumns = [];
            $placeholders = [];
            $params = [];

            foreach ($existing as $column) {
                if ($column === 'used_today' || $column === 'fail_count') {
                    $value = 0;
                } elseif ($column === 'daily_limit' || $column === 'priority_order') {
                    $value = (int)($_POST['new_' . $column] ?? 0);
                } elseif (in_array($column, ['is_active', 'supports_candles', 'supports_quote', 'supports_usage'], true)) {
                    $value = !empty($_POST['new_' . $column]) ? 1 : 0;
                } elseif ($column === 'provider') {
                    $value = api_normalize_provider_name((string)($_POST['new_' . $column] ?? ''));
                } elseif (in_array($column, ['cooldown_until','last_used_at','reset_date','last_error'], true)) {
                    $value = null;
                } else {
                    $value = trim((string)($_POST['new_' . $column] ?? ''));
                }

                $insertColumns[] = "`$column`";
                $placeholders[] = '?';
                $params[] = $value;
            }

            db()->prepare("INSERT INTO api_settings (" . implode(', ', $insertColumns) . ") VALUES (" . implode(', ', $placeholders) . ")")->execute($params);

            $message = 'New API provider added successfully.';
        }

        if ($action === 'seed_recommended') {
            $counts = ['inserted' => 0, 'updated' => 0, 'exists' => 0, 'skipped' => 0];
            foreach (api_recommended_providers() as $defaults) {
                $result = api_insert_or_update_provider($defaults, $existing);
                $counts[$result] = ($counts[$result] ?? 0) + 1;
            }
            $message = 'Recommended provider rows checked: ' . $counts['inserted'] . ' added, ' . $counts['updated'] . ' updated, ' . $counts['exists'] . ' already OK.';
        }

        if ($action === 'reset_usage') {
            $apiId = (int)($_POST['api_id'] ?? 0);
            $selectedProvider = '';
            try {
                $st = db()->prepare("SELECT provider FROM api_settings WHERE id = ? LIMIT 1");
                $st->execute([$apiId]);
                $selectedProvider = strtolower(trim((string)$st->fetchColumn()));
            } catch (Throwable $e) {
                $selectedProvider = '';
            }

            $sets = [];
            if (api_col_exists('used_today')) $sets[] = 'used_today = 0';
            if (api_col_exists('fail_count')) $sets[] = 'fail_count = 0';
            if (api_col_exists('cooldown_until')) $sets[] = 'cooldown_until = NULL';
            if (api_col_exists('last_error')) $sets[] = 'last_error = NULL';
            if (api_col_exists('reset_date')) $sets[] = 'reset_date = CURDATE()';
            if ($sets) {
                db()->prepare("UPDATE api_settings SET " . implode(', ', $sets) . " WHERE id = ?")->execute([$apiId]);
            }

            /*
             * If one FMP/TwelveData key row is reset, clear only old saved legacy-endpoint
             * errors for the same provider group. This avoids duplicate key rows continuing
             * to display an obsolete error after the endpoint code has been corrected.
             */
            if ($selectedProvider !== '' && api_col_exists('last_error')) {
                $clearSets = [];
                if (api_col_exists('last_error')) $clearSets[] = 'last_error = NULL';
                if (api_col_exists('cooldown_until')) $clearSets[] = 'cooldown_until = NULL';
                if (api_col_exists('fail_count')) $clearSets[] = 'fail_count = 0';
                if ($clearSets) {
                    db()->prepare("UPDATE api_settings SET " . implode(', ', $clearSets) . " WHERE LOWER(provider) = LOWER(?) AND (last_error LIKE '%Legacy Endpoint%' OR last_error LIKE '%legacy endpoint%' OR last_error LIKE '%api/v3%' OR last_error LIKE '%quote-short%' OR last_error LIKE '%GCUSD%' OR last_error LIKE '%ZGUSD%' OR last_error LIKE '%XAUUSD%' OR last_error LIKE '%XAGUSD%' OR last_error LIKE '%Restricted Endpoint%' OR last_error LIKE '%not available under your current subscription%')")
                        ->execute([$selectedProvider]);
                }
            }

            $message = 'Usage, cooldown and saved legacy endpoint errors reset.';
        }

        if ($action === 'clear_legacy_errors') {
            if (api_col_exists('last_error')) {
                $sets = ['last_error = NULL'];
                if (api_col_exists('cooldown_until')) $sets[] = 'cooldown_until = NULL';
                if (api_col_exists('fail_count')) $sets[] = 'fail_count = 0';
                db()->exec("UPDATE api_settings SET " . implode(', ', $sets) . " WHERE last_error LIKE '%Legacy Endpoint%' OR last_error LIKE '%legacy endpoint%' OR last_error LIKE '%api/v3%' OR last_error LIKE '%quote-short%'");
            }
            $message = 'Saved legacy endpoint errors cleared.';
        }

        if ($action === 'clear_fmp_metal_errors') {
            api_clear_fmp_metal_errors();
            $message = 'Saved FMP metal/commodity endpoint errors cleared.';
        }

        if ($action === 'apply_metal_routing_fix') {
            api_upsert_system_setting('live_quote_fmp_metals_enabled', '0');
            api_upsert_system_setting('candle_sync_fmp_metals_enabled', '0');
            api_upsert_system_setting('market_data_fmp_metals_enabled', '0');
            api_upsert_system_setting('candle_sync_alert_aware_metal_provider', 'twelvedata');
            api_upsert_system_setting('candle_sync_alert_aware_forex_provider', 'fmp');
            api_clear_fmp_metal_errors();
            $message = 'Metal routing fix applied: XAUUSD/XAGUSD avoid FMP by default, metals use TwelveData/metals providers, forex can still use FMP rotation.';
        }


        if ($action === 'apply_api_credit_safe_mode') {
            // Prevent the 1-minute alert worker from acting like a bulk scanner.
            // The separate 5-minute sync_candles cron remains responsible for candles.
            api_upsert_system_setting('alert_worker_pre_sync_enabled', '0');
            api_upsert_system_setting('alert_worker_pre_sync_min_seconds', '300');
            api_upsert_system_setting('alert_worker_pre_sync_limit', '10');
            api_upsert_system_setting('alert_worker_pre_sync_max_pairs', '8');

            // Disable bulk live-quote prefetch by default; quote calls remain on-demand and cached.
            api_upsert_system_setting('alert_worker_prefetch_live_quotes', '0');
            api_upsert_system_setting('alert_worker_live_quote_prefetch_min_seconds', '180');
            api_upsert_system_setting('alert_worker_live_quote_max_alerts', '10');
            api_upsert_system_setting('live_quote_prefetch_min_seconds', '180');
            api_upsert_system_setting('live_quote_prefetch_max_symbols', '10');

            // Safer default cache TTLs for paid quote providers.
            api_upsert_system_setting('live_quote_cache_ttl_forex', '120');
            api_upsert_system_setting('live_quote_cache_ttl_metal', '120');
            api_upsert_system_setting('live_quote_cache_ttl_index', '180');
            api_upsert_system_setting('live_quote_cache_ttl_indices', '180');
            api_upsert_system_setting('live_quote_cache_ttl_stock', '180');

            // Candle sync should remain alert-aware, but not scan too many active setups per run.
            api_upsert_system_setting('candle_sync_alert_aware_default', '1');
            api_upsert_system_setting('candle_sync_alert_aware_max_alerts', '30');
            api_upsert_system_setting('candle_sync_alert_aware_stage_filter', 'LIQUIDITY_SWEPT,STRUCTURE_CONFIRMED');
            api_upsert_system_setting('candle_sync_live_limit', '10');
            api_upsert_system_setting('candle_sync_min_seconds_1m', '60');
            api_upsert_system_setting('candle_sync_min_seconds_5m', '240');
            api_upsert_system_setting('candle_sync_min_seconds_15m', '600');
            api_upsert_system_setting('candle_sync_min_seconds_30m', '900');
            api_upsert_system_setting('candle_sync_min_seconds_1h', '1800');
            api_upsert_system_setting('candle_sync_min_seconds_4h', '3600');

            // Apply conservative per-key app-side caps where a provider row still has limit 0.
            if (api_col_exists('daily_limit')) {
                db()->exec("UPDATE api_settings SET daily_limit = 220 WHERE LOWER(provider) IN ('fmp','financialmodelingprep','financial_modeling_prep') AND COALESCE(daily_limit,0) <= 0");
                db()->exec("UPDATE api_settings SET daily_limit = 700 WHERE LOWER(provider) IN ('twelvedata','twelve_data','twelve-data') AND COALESCE(daily_limit,0) <= 0");
                db()->exec("UPDATE api_settings SET daily_limit = 50 WHERE LOWER(provider) IN ('finnhub') AND COALESCE(daily_limit,0) <= 0");
                db()->exec("UPDATE api_settings SET daily_limit = 20 WHERE LOWER(provider) IN ('alphavantage','alpha_vantage','alpha-vantage') AND COALESCE(daily_limit,0) <= 0");
            }

            // Keep the previous metal protection too.
            api_upsert_system_setting('live_quote_fmp_metals_enabled', '0');
            api_upsert_system_setting('candle_sync_fmp_metals_enabled', '0');
            api_upsert_system_setting('market_data_fmp_metals_enabled', '0');
            api_upsert_system_setting('candle_sync_alert_aware_metal_provider', 'twelvedata');
            api_upsert_system_setting('candle_sync_alert_aware_forex_provider', 'fmp');
            api_clear_fmp_metal_errors();

            $message = 'API Credit Safe Mode applied: 1-minute bulk pre-sync/prefetch disabled, quotes cached longer, candle sync throttled to Stage 2/3 tracked setups only, and conservative per-key app limits added where limits were 0.';
        }

        if ($action === 'delete') {
            db()->prepare("DELETE FROM api_settings WHERE id = ?")->execute([(int)($_POST['api_id'] ?? 0)]);
            $message = 'API provider deleted successfully.';
        }

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

$providers = [];
$providerStats = ['total' => 0, 'active' => 0, 'multi_key_groups' => 0];

try {
    $providers = db()->query("
        SELECT *
        FROM api_settings
        ORDER BY is_active DESC, priority_order ASC, provider ASC, id ASC
    ")->fetchAll(PDO::FETCH_ASSOC) ?: [];

    $seen = [];
    foreach ($providers as $provider) {
        $providerStats['total']++;
        if (!empty($provider['is_active'])) $providerStats['active']++;
        $key = api_normalize_provider_name((string)($provider['provider'] ?? ''));
        if ($key !== '') {
            $seen[$key] = ($seen[$key] ?? 0) + 1;
            if ($seen[$key] === 2) $providerStats['multi_key_groups']++;
        }
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

admin_layout_header('API Settings');

?>

<style>
.api-page{max-width:1450px;margin:0 auto}
.api-title{font-size:42px;font-weight:900;letter-spacing:-.05em;color:#020617;line-height:1}
.api-subtitle{margin-top:9px;color:#64748b;font-size:15px;margin-bottom:24px}.api-note{background:#eff6ff;border:1px solid #bfdbfe;color:#1e3a8a;border-radius:18px;padding:14px 16px;font-weight:800;margin-bottom:18px;line-height:1.45}
.api-alert{padding:14px 18px;border-radius:16px;font-weight:800;margin-bottom:18px}.api-success{background:#ecfdf5;border:1px solid #a7f3d0;color:#047857}.api-error{background:#fef2f2;border:1px solid #fecaca;color:#b91c1c}
.api-toolbar{display:flex;gap:12px;flex-wrap:wrap;align-items:center;justify-content:space-between;margin-bottom:18px}.api-toolbar-actions{display:flex;gap:10px;flex-wrap:wrap}.api-pill{display:inline-flex;height:36px;align-items:center;border:1px solid #bfdbfe;background:#eff6ff;color:#1d4ed8;border-radius:999px;padding:0 14px;font-weight:900;font-size:13px}
.api-card{background:#fff;border:1px solid #e2e8f0;border-radius:30px;box-shadow:0 10px 28px rgba(15,23,42,.05);overflow:hidden;margin-bottom:24px}.api-head{padding:24px 28px;border-bottom:1px solid #e2e8f0;background:linear-gradient(135deg,rgba(37,99,235,.06),rgba(15,23,42,.02))}.api-head h2{margin:0;font-size:26px;font-weight:900;color:#020617}.api-head p{margin-top:8px;color:#64748b;font-size:14px}.api-grid{padding:24px;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px}.api-field label{display:block;margin-bottom:7px;color:#64748b;font-size:11px;font-weight:900;text-transform:uppercase;letter-spacing:.08em}.api-field input,.api-field select{width:100%;height:46px;border:1px solid #cbd5e1;border-radius:14px;padding:0 14px;font-size:14px;font-weight:700;color:#0f172a;background:#fff}.api-check-row{display:flex;align-items:center;gap:16px;flex-wrap:wrap;padding:0 24px 24px}.api-check-row label{font-weight:800;color:#334155}.api-actions{display:flex;gap:12px;padding:18px 24px;background:#f8fafc;border-top:1px solid #e2e8f0;justify-content:flex-end}.api-btn{height:44px;border:0;border-radius:14px;padding:0 20px;font-weight:900;cursor:pointer}.api-primary{background:#2563eb;color:#fff}.api-dark{background:#020617;color:#fff}.api-danger{background:#fee2e2;color:#991b1b;border:1px solid #fecaca}.api-soft{background:#e0f2fe;color:#075985;border:1px solid #bae6fd}
.provider-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.provider-card{background:#fff;border:1px solid #e2e8f0;border-radius:28px;overflow:hidden;box-shadow:0 10px 28px rgba(15,23,42,.05)}.provider-top{padding:22px;border-bottom:1px solid #e2e8f0}.provider-title{font-size:24px;font-weight:900;color:#020617;letter-spacing:-.035em}.provider-sub{margin-top:5px;color:#64748b;font-size:13px;font-weight:700}.provider-body{padding:22px}.provider-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.badge{display:inline-flex;height:28px;align-items:center;padding:0 10px;border-radius:999px;font-size:11px;font-weight:900;text-transform:uppercase}.green{background:#dcfce7;color:#166534}.red{background:#fee2e2;color:#991b1b}.blue{background:#dbeafe;color:#1d4ed8}.orange{background:#ffedd5;color:#9a3412}.slate{background:#f1f5f9;color:#334155}
@media(max-width:1100px){.api-grid,.provider-list{grid-template-columns:1fr}.provider-grid{grid-template-columns:1fr}.api-toolbar{align-items:flex-start;flex-direction:column}}
</style>

<div class="api-page">

    <div class="api-title">API Settings</div>
    <div class="api-subtitle">Manage multiple market-data providers, multiple API keys, rotation priority, failover rules and usage limits.</div>

    <div class="api-toolbar">
        <div style="display:flex;gap:8px;flex-wrap:wrap">
            <span class="api-pill"><?= e($providerStats['total']) ?> total</span>
            <span class="api-pill"><?= e($providerStats['active']) ?> active</span>
            <?php if ($providerStats['multi_key_groups'] > 0): ?><span class="api-pill"><?= e($providerStats['multi_key_groups']) ?> multi-key provider group(s)</span><?php endif; ?>
        </div>
        <div class="api-toolbar-actions">
            <form method="post"><button class="api-btn api-soft" name="action" value="seed_recommended">Seed / Repair Recommended Providers</button></form>
        </div>
    </div>

    <div class="api-note">
        Production routing: Binance is used for crypto; GoldAPI.io/Gold-API/TwelveData/metals providers are used for metals by default; FMP is intentionally blocked for metals unless you enable it in system_settings because many FMP plans reject GCUSD/XAU commodity endpoints. FMP/TwelveData/Finnhub/Alpha Vantage remain available for normal forex pairs; Finnhub/FMP/TwelveData/Alpha Vantage are available for stocks and indices. Multiple rows with the same provider are allowed when they contain different API keys. The rotation service treats each row as a separate account and updates usage/cooldown by row ID. API Credit Safe Mode prevents the 1-minute alert worker from bulk-prefetching quotes or candles; the separate 5-minute alert-aware candle cron remains the main candle-refresh worker and, by default, only syncs closed candles after liquidity has been swept / structure confirmation is needed.
    </div>

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

    <form method="post" style="margin-bottom:18px;display:flex;gap:10px;flex-wrap:wrap">
        <button class="api-btn api-primary" type="submit" name="action" value="apply_api_credit_safe_mode">Apply API Credit Safe Mode</button>
        <button class="api-btn api-primary" type="submit" name="action" value="apply_metal_routing_fix">Apply Metal Routing Fix</button>
        <button class="api-btn api-dark" type="submit" name="action" value="clear_fmp_metal_errors">Clear Saved FMP Metal Errors</button>
        <button class="api-btn api-dark" type="submit" name="action" value="clear_legacy_errors">Clear Saved Legacy FMP Errors</button>
    </form>

    <form method="post" class="api-card">
        <input type="hidden" name="action" value="add">

        <div class="api-head">
            <h2>Add API Provider</h2>
            <p>Add providers such as fmp, twelvedata, finnhub, alphavantage, goldapiio, metalsapi or metalpriceapi. Use the repair button above to create the recommended rows automatically.</p>
        </div>

        <div class="api-grid">
            <div class="api-field"><label>Provider</label><input name="new_provider" placeholder="fmp"></div>
            <div class="api-field"><label>Provider Type</label><input name="new_provider_type" value="market_data"></div>
            <div class="api-field"><label>Base URL</label><input name="new_base_url" placeholder="https://financialmodelingprep.com"></div>
            <div class="api-field"><label>API Key</label><input name="new_api_key" placeholder="API key"></div>
            <div class="api-field"><label>Daily Limit</label><input type="number" name="new_daily_limit" value="250"></div>
            <div class="api-field"><label>Priority</label><input type="number" name="new_priority_order" value="100"></div>
        </div>

        <div class="api-check-row">
            <label><input type="checkbox" name="new_supports_candles" value="1" checked> Candles</label>
            <label><input type="checkbox" name="new_supports_quote" value="1" checked> Quotes</label>
            <label><input type="checkbox" name="new_supports_usage" value="1"> Usage API</label>
            <label><input type="checkbox" name="new_is_active" value="1" checked> Active</label>
        </div>

        <div class="api-actions">
            <button class="api-btn api-dark">Add Provider</button>
        </div>
    </form>

    <form method="post">
        <input type="hidden" name="action" value="save">

        <div class="provider-list">
            <?php foreach ($providers as $provider): ?>
                <?php $id = (int)($provider['id'] ?? 0); ?>
                <section class="provider-card">
                    <div class="provider-top">
                        <div class="provider-title"><?= e($provider['provider'] ?? 'Provider') ?></div>
                        <div class="provider-sub"><?= e($provider['base_url'] ?? '') ?></div>
                        <div style="margin-top:12px;display:flex;gap:8px;flex-wrap:wrap">
                            <span class="badge <?= !empty($provider['is_active']) ? 'green' : 'red' ?>"><?= !empty($provider['is_active']) ? 'Active' : 'Inactive' ?></span>
                            <span class="badge blue"><?= e($provider['used_today'] ?? 0) ?> used</span>
                            <span class="badge slate">Limit <?= e($provider['daily_limit'] ?? 0) ?></span>
                            <?php if (!empty($provider['cooldown_until'])): ?><span class="badge orange">Cooldown</span><?php endif; ?>
                        </div>
                    </div>

                    <div class="provider-body">
                        <div class="provider-grid">
                            <?php foreach ($existing as $column): ?>
                                <?php if (in_array($column, ['is_active','supports_candles','supports_quote','supports_usage'], true)) continue; ?>
                                <div class="api-field">
                                    <label><?= e(str_replace('_',' ', $column)) ?></label>
                                    <input name="apis[<?= e($id) ?>][<?= e($column) ?>]" value="<?= e($provider[$column] ?? '') ?>">
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="api-check-row" style="padding:18px 0 0">
                            <?php foreach (['supports_candles'=>'Candles','supports_quote'=>'Quotes','supports_usage'=>'Usage API','is_active'=>'Active'] as $column=>$label): ?>
                                <?php if (!in_array($column, $existing, true)) continue; ?>
                                <label><input type="checkbox" name="apis[<?= e($id) ?>][<?= e($column) ?>]" value="1" <?= !empty($provider[$column]) ? 'checked' : '' ?>> <?= e($label) ?></label>
                            <?php endforeach; ?>
                        </div>

                        <?php if (!empty($provider['last_error'])): ?>
                            <div style="margin-top:14px;color:#b91c1c;font-size:13px;font-weight:700">
                                <?= e($provider['last_error']) ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="api-actions">
                        <button class="api-btn api-primary" type="submit">Save</button>
                        <button class="api-btn api-dark" type="submit" name="action" value="reset_usage" onclick="this.form.api_id.value='<?= e($id) ?>'">Reset Usage</button>
                        <button class="api-btn api-danger" type="submit" name="action" value="delete" onclick="this.form.api_id.value='<?= e($id) ?>'; return confirm('Delete this API provider?')">Delete</button>
                    </div>
                </section>
            <?php endforeach; ?>
        </div>

        <input type="hidden" name="api_id" value="">
    </form>
</div>

<?php admin_layout_footer(); ?>
