<?php
require_once __DIR__ . '/../config/database.php';

function e($v)
{
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

function getApiKey($provider)
{
    $stmt = db()->prepare("SELECT api_key FROM api_settings WHERE provider = ? AND is_active = 1 LIMIT 1");
    $stmt->execute([$provider]);

    return $stmt->fetchColumn();
}

function fetchJson($url)
{
    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER => [
            'Accept: application/json'
        ]
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);

    curl_close($ch);

    return [
        'success' => $response !== false && $httpCode >= 200 && $httpCode < 300,
        'http_code' => $httpCode,
        'error' => $error,
        'raw' => $response,
        'json' => json_decode($response, true)
    ];
}

$fmpKey = getApiKey('fmp');
$twelveDataKey = getApiKey('twelvedata');

$calendar = [
    'status' => false,
    'message' => 'Not tested'
];

$forexNews = [
    'status' => false,
    'message' => 'Not tested'
];

$geoNews = [
    'status' => false,
    'message' => 'Not tested'
];

if ($fmpKey) {

    $calendarUrl = "https://financialmodelingprep.com/stable/economic-calendar?apikey={$fmpKey}";
    $calendarResponse = fetchJson($calendarUrl);

    if ($calendarResponse['success']) {

        $calendar['status'] = true;
        $calendar['message'] = 'Economic calendar API responding';
        $calendar['sample'] = array_slice($calendarResponse['json'] ?? [], 0, 3);

    } else {

        $calendar['message'] = $calendarResponse['error'] ?: ('HTTP ' . $calendarResponse['http_code']);
    }

    $newsUrl = "https://financialmodelingprep.com/stable/news/forex?apikey={$fmpKey}";
    $newsResponse = fetchJson($newsUrl);

    if ($newsResponse['success']) {

        $forexNews['status'] = true;
        $forexNews['message'] = 'Forex news API responding';
        $forexNews['sample'] = array_slice($newsResponse['json'] ?? [], 0, 3);

    } else {

        $forexNews['message'] = $newsResponse['error'] ?: ('HTTP ' . $newsResponse['http_code']);
    }

    $geoUrl = "https://financialmodelingprep.com/stable/news/general?apikey={$fmpKey}";
    $geoResponse = fetchJson($geoUrl);

    if ($geoResponse['success']) {

        $geoNews['status'] = true;
        $geoNews['message'] = 'Geopolitical/general news API responding';
        $geoNews['sample'] = array_slice($geoResponse['json'] ?? [], 0, 5);

    } else {

        $geoNews['message'] = $geoResponse['error'] ?: ('HTTP ' . $geoResponse['http_code']);
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Risk Diagnostics</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 text-slate-900 min-h-screen">

<div class="max-w-7xl mx-auto px-6 py-10">

    <div class="mb-8">
        <h1 class="text-4xl font-black">Phase 1 Risk Diagnostics</h1>
        <p class="text-slate-600 mt-2">
            Economic Calendar + News + Geopolitical Intelligence Verification
        </p>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">

        <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
            <h2 class="text-xl font-bold mb-4">API Configuration</h2>

            <div class="space-y-4">

                <div class="rounded-xl p-4 border border-slate-200">
                    <div class="font-semibold">Financial Modeling Prep (FMP)</div>
                    <div class="mt-2">
                        Status:
                        <span class="<?= $fmpKey ? 'text-green-600 font-bold' : 'text-red-600 font-bold' ?>">
                            <?= $fmpKey ? 'CONNECTED' : 'MISSING API KEY' ?>
                        </span>
                    </div>
                </div>

                <div class="rounded-xl p-4 border border-slate-200">
                    <div class="font-semibold">TwelveData</div>
                    <div class="mt-2">
                        Status:
                        <span class="<?= $twelveDataKey ? 'text-green-600 font-bold' : 'text-red-600 font-bold' ?>">
                            <?= $twelveDataKey ? 'CONNECTED' : 'MISSING API KEY' ?>
                        </span>
                    </div>
                </div>

            </div>
        </div>

        <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
            <h2 class="text-xl font-bold mb-4">Economic Calendar Engine</h2>

            <div class="<?= $calendar['status'] ? 'text-green-600' : 'text-red-600' ?> font-bold">
                <?= $calendar['status'] ? 'WORKING' : 'FAILED' ?>
            </div>

            <p class="mt-2 text-slate-700">
                <?= e($calendar['message']) ?>
            </p>

            <?php if (!empty($calendar['sample'])): ?>
                <div class="mt-4 text-sm">
                    <div class="font-bold mb-2">Sample Events</div>

                    <?php foreach ($calendar['sample'] as $item): ?>
                        <div class="border rounded-lg p-3 mb-2 bg-slate-50">
                            <?= e($item['event'] ?? 'Unknown Event') ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
            <h2 class="text-xl font-bold mb-4">Forex News Engine</h2>

            <div class="<?= $forexNews['status'] ? 'text-green-600' : 'text-red-600' ?> font-bold">
                <?= $forexNews['status'] ? 'WORKING' : 'FAILED' ?>
            </div>

            <p class="mt-2 text-slate-700">
                <?= e($forexNews['message']) ?>
            </p>

            <?php if (!empty($forexNews['sample'])): ?>
                <div class="mt-4 text-sm">
                    <div class="font-bold mb-2">Sample Headlines</div>

                    <?php foreach ($forexNews['sample'] as $item): ?>
                        <div class="border rounded-lg p-3 mb-2 bg-slate-50">
                            <?= e($item['title'] ?? 'No title') ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
            <h2 class="text-xl font-bold mb-4">Geopolitical Risk Engine</h2>

            <div class="<?= $geoNews['status'] ? 'text-green-600' : 'text-red-600' ?> font-bold">
                <?= $geoNews['status'] ? 'WORKING' : 'FAILED' ?>
            </div>

            <p class="mt-2 text-slate-700">
                <?= e($geoNews['message']) ?>
            </p>

            <?php if (!empty($geoNews['sample'])): ?>
                <div class="mt-4 text-sm">
                    <div class="font-bold mb-2">Sample Headlines</div>

                    <?php foreach ($geoNews['sample'] as $item): ?>
                        <div class="border rounded-lg p-3 mb-2 bg-slate-50">
                            <?= e($item['title'] ?? 'No title') ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

    </div>

</div>

</body>
</html>
