<?php

require_once __DIR__ . '/admin_tool_helper.php';

date_default_timezone_set('Africa/Lagos');

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

function mon_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 mon_column_exists(string $table, string $column): bool
{
    try { $stmt = db()->prepare("SHOW COLUMNS FROM `$table` LIKE ?"); $stmt->execute([$column]); return (bool)$stmt->fetchColumn(); }
    catch (Throwable $e) { return false; }
}

function mon_time_lagos($utcValue): string
{
    $value = trim((string)$utcValue);
    if ($value === '' || $value === '0000-00-00 00:00:00') return '';
    try { return (new DateTimeImmutable($value, new DateTimeZone('UTC')))->setTimezone(new DateTimeZone('Africa/Lagos'))->format('Y-m-d H:i:s'); }
    catch (Throwable $e) { return $value; }
}

function mon_fetch_all(string $sql, array $params = []): array
{
    try { $stmt = db()->prepare($sql); $stmt->execute($params); return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: []; }
    catch (Throwable $e) { return []; }
}

function mon_count(string $sql, array $params = []): int
{
    try { $stmt = db()->prepare($sql); $stmt->execute($params); return (int)$stmt->fetchColumn(); }
    catch (Throwable $e) { return 0; }
}

function mon_delete_rows(string $table, array $ids): int
{
    if (!mon_table_exists($table) || !mon_column_exists($table, 'id')) return 0;
    $ids = array_values(array_unique(array_filter(array_map('intval', $ids), static fn($id) => $id > 0)));
    if (!$ids) return 0;
    $ph = implode(',', array_fill(0, count($ids), '?'));
    try { $stmt = db()->prepare("DELETE FROM `$table` WHERE id IN ($ph)"); $stmt->execute($ids); return $stmt->rowCount(); }
    catch (Throwable $e) { return 0; }
}

function mon_url(array $overrides = []): string
{
    $params = $_GET;
    foreach ($overrides as $key => $value) { if ($value === null) unset($params[$key]); else $params[$key] = $value; }
    return '?' . http_build_query($params);
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $action = (string)($_POST['action'] ?? '');
        if ($action === 'delete_logs') {
            $deleted = mon_delete_rows('api_request_logs', $_POST['selected_logs'] ?? []);
            if ($deleted === 0 && mon_table_exists('api_rotation_logs')) {
                $deleted = mon_delete_rows('api_rotation_logs', $_POST['selected_logs'] ?? []);
            }
            $message = $deleted . ' API monitor log row(s) deleted.';
        }
        if ($action === 'clear_old_monitor_logs') {
            $days = max(1, min(365, (int)($_POST['older_than_days'] ?? 30)));
            $deleted = 0;
            foreach (['api_request_logs','api_rotation_logs'] as $table) {
                if (!mon_table_exists($table) || !mon_column_exists($table, 'created_at')) continue;
                $stmt = db()->prepare("DELETE FROM `$table` WHERE created_at < DATE_SUB(UTC_TIMESTAMP(), INTERVAL ? DAY)");
                $stmt->execute([$days]);
                $deleted += $stmt->rowCount();
            }
            $message = $deleted . ' old monitor log row(s) deleted.';
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

$perPage = max(25, min(200, (int)($_GET['per_page'] ?? 50)));
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $perPage;

$providers = [];
$summary = [];
$logs = [];
$totalLogs = 0;
$logTable = mon_table_exists('api_request_logs') ? 'api_request_logs' : (mon_table_exists('api_rotation_logs') ? 'api_rotation_logs' : '');

try {
    if (mon_table_exists('api_settings')) {
        $providers = mon_fetch_all("SELECT * FROM api_settings ORDER BY COALESCE(is_active,1) DESC, COALESCE(priority_order,999999), provider ASC, id ASC");
    }

    if ($logTable !== '') {
        $idSelect = mon_column_exists($logTable, 'id') ? 'id' : '0 AS id';
        $apiRowSelect = mon_column_exists($logTable, 'api_setting_id') ? 'api_setting_id' : 'NULL AS api_setting_id';
        $providerSelect = mon_column_exists($logTable, 'provider') ? 'provider' : "'' AS provider";
        $endpointSelect = mon_column_exists($logTable, 'endpoint') ? 'endpoint' : "'' AS endpoint";
        $symbolSelect = mon_column_exists($logTable, 'symbol') ? 'symbol' : "'' AS symbol";
        $tfSelect = mon_column_exists($logTable, 'timeframe') ? 'timeframe' : "'' AS timeframe";
        $statusSelect = mon_column_exists($logTable, 'status') ? 'status' : "'' AS status";
        $msSelect = mon_column_exists($logTable, 'response_ms') ? 'response_ms' : '0 AS response_ms';
        $creditsSelect = mon_column_exists($logTable, 'credits_used') ? 'credits_used' : '0 AS credits_used';
        $errorSelect = mon_column_exists($logTable, 'error_message') ? 'error_message' : "'' AS error_message";
        $createdSelect = mon_column_exists($logTable, 'created_at') ? 'created_at' : 'NULL AS created_at';

        $totalLogs = mon_count("SELECT COUNT(*) FROM `$logTable`");
        $logs = mon_fetch_all("SELECT $idSelect, $apiRowSelect, $providerSelect, $endpointSelect, $symbolSelect, $tfSelect, $statusSelect, $msSelect, $creditsSelect, $errorSelect, $createdSelect FROM `$logTable` ORDER BY created_at DESC LIMIT $perPage OFFSET $offset");

        $summary = mon_fetch_all("SELECT provider, api_setting_id, status, COUNT(*) AS total, SUM(COALESCE(credits_used,0)) AS credits, MAX(created_at) AS last_seen FROM `$logTable` WHERE created_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 24 HOUR) GROUP BY provider, api_setting_id, status ORDER BY provider ASC, api_setting_id ASC, total DESC LIMIT 80");
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$totalPages = max(1, (int)ceil($totalLogs / max(1, $perPage)));

admin_layout_header('API Monitor');
?>
<style>
.mon-page{max-width:1500px;margin:0 auto}.hero{background:linear-gradient(135deg,#020617,#0f172a,#1e293b);border-radius:34px;padding:34px;color:#fff;margin-bottom:22px}.hero h1{font-size:42px;font-weight:900;letter-spacing:-.055em;margin:0}.hero p{margin:10px 0 0;color:#cbd5e1;line-height:1.7;max-width:920px}.card{background:#fff;border:1px solid #e2e8f0;border-radius:28px;box-shadow:0 10px 28px rgba(15,23,42,.05);padding:24px;margin-bottom:22px}.card h2{margin:0 0 6px;font-size:25px;font-weight:900;color:#020617;letter-spacing:-.035em}.muted{color:#64748b;font-size:13px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:14px}.provider{border:1px solid #e2e8f0;border-radius:22px;padding:18px;background:#f8fafc}.provider-name{font-size:22px;font-weight:900;color:#020617}.provider-sub{margin-top:6px;color:#64748b;font-size:12px}.badges{margin-top:12px;display:flex;gap:8px;flex-wrap:wrap}.badge{display:inline-flex;border-radius:999px;padding:5px 9px;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}.table-wrap{overflow:auto;border:1px solid #e2e8f0;border-radius:20px;margin-top:16px}table{width:100%;border-collapse:collapse;min-width:1000px}th{background:#f8fafc;text-align:left;font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:#64748b;padding:13px;border-bottom:1px solid #e2e8f0}td{padding:13px;border-bottom:1px solid #f1f5f9;font-size:13px;color:#0f172a;vertical-align:top}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono",monospace}.btn{height:42px;border:0;border-radius:14px;padding:0 18px;font-weight:900;cursor:pointer;background:#020617;color:#fff}.btn-danger{background:#991b1b}.pager{display:flex;gap:8px;align-items:center;justify-content:flex-end;margin-top:14px;flex-wrap:wrap}.pager a,.pager span{padding:8px 12px;border-radius:12px;border:1px solid #cbd5e1;font-weight:900;font-size:12px;text-decoration:none;color:#0f172a}.pager .current{background:#020617;color:#fff;border-color:#020617}.action-row{display:flex;gap:10px;align-items:center;justify-content:space-between;margin-top:14px;flex-wrap:wrap}.field label{display:block;font-size:11px;font-weight:900;color:#64748b;text-transform:uppercase;letter-spacing:.08em;margin-bottom:7px}.field input{height:42px;border:1px solid #cbd5e1;border-radius:14px;padding:0 12px;font-weight:800}.notice{padding:13px 16px;border-radius:16px;font-weight:800;margin-bottom:14px}.ok{background:#ecfdf5;border:1px solid #a7f3d0;color:#047857}.bad{background:#fef2f2;border:1px solid #fecaca;color:#b91c1c}
</style>
<div class="mon-page">
    <section class="hero"><h1>API Monitor</h1><p>Monitor API provider health, app-side usage counters, recent API calls, and request logs. Times are displayed in Lagos, Nigeria time.</p></section>
    <?php if ($message): ?><div class="notice ok"><?= e($message) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="notice bad"><?= e($error) ?></div><?php endif; ?>

    <section class="card"><h2>Provider Status</h2><div class="muted">Duplicate provider rows are treated as separate API keys/accounts.</div><div class="grid" style="margin-top:16px">
    <?php if (!$providers): ?><div class="muted">No providers found in api_settings.</div><?php endif; ?>
    <?php foreach ($providers as $p): $active = (int)($p['is_active'] ?? 1) === 1; $limit=(int)($p['daily_limit'] ?? 0); $used=(int)($p['used_today'] ?? 0); ?>
        <div class="provider"><div class="provider-name"><?= e(strtoupper($p['provider'] ?? 'Provider')) ?> <span class="mono" style="font-size:13px">#<?= e($p['id'] ?? '') ?></span></div><div class="provider-sub"><?= e($p['base_url'] ?? '') ?></div><div class="badges"><span class="badge <?= $active ? 'green' : 'red' ?>"><?= $active ? 'Active' : 'Inactive' ?></span><span class="badge blue"><?= e($used) ?> used<?= $limit > 0 ? ' / ' . e($limit) : '' ?></span><?php if (!empty($p['cooldown_until'])): ?><span class="badge orange">Cooldown until <?= e(mon_time_lagos($p['cooldown_until'])) ?></span><?php endif; ?></div><?php if (!empty($p['last_error'])): ?><div style="margin-top:12px;color:#991b1b;font-size:12px;font-weight:800"><?= e($p['last_error']) ?></div><?php endif; ?></div>
    <?php endforeach; ?></div></section>

    <section class="card"><h2>24-Hour Request Summary</h2><div class="table-wrap"><table><thead><tr><th>Provider</th><th>API Row</th><th>Status</th><th>Rows</th><th>Credits</th><th>Last Seen Lagos</th></tr></thead><tbody><?php if (!$summary): ?><tr><td colspan="6" class="muted">No recent logs found.</td></tr><?php endif; ?><?php foreach ($summary as $s): ?><tr><td><strong><?= e(strtoupper($s['provider'] ?? '')) ?></strong></td><td class="mono"><?= e($s['api_setting_id'] ?: 'public') ?></td><td><?= e($s['status'] ?? '') ?></td><td><?= e($s['total'] ?? 0) ?></td><td><?= e($s['credits'] ?? 0) ?></td><td class="mono"><?= e(mon_time_lagos($s['last_seen'] ?? '')) ?></td></tr><?php endforeach; ?></tbody></table></div></section>

    <form method="post" class="card" onsubmit="return confirm('Delete selected API monitor log rows?')"><input type="hidden" name="action" value="delete_logs"><h2>Recent Request Logs</h2><div class="muted">Showing <?= e(number_format(count($logs))) ?> of <?= e(number_format($totalLogs)) ?> rows from <?= e($logTable ?: 'no log table') ?>.</div><div class="table-wrap"><table><thead><tr><th>Select</th><th>Time Lagos</th><th>Status</th><th>Provider</th><th>API Row</th><th>Endpoint</th><th>Symbol</th><th>TF</th><th>Credits</th><th>ms</th><th>Error</th></tr></thead><tbody><?php if (!$logs): ?><tr><td colspan="11" class="muted">No request logs found.</td></tr><?php endif; ?><?php foreach ($logs as $row): ?><tr><td><?php if (!empty($row['id'])): ?><input type="checkbox" name="selected_logs[]" value="<?= e($row['id']) ?>"><?php endif; ?></td><td class="mono"><?= e(mon_time_lagos($row['created_at'] ?? '')) ?></td><td><?= e($row['status'] ?? '') ?></td><td><strong><?= e(strtoupper($row['provider'] ?? '')) ?></strong></td><td class="mono"><?= e($row['api_setting_id'] ?: 'public') ?></td><td><?= e($row['endpoint'] ?? '') ?></td><td><strong><?= e($row['symbol'] ?? '') ?></strong></td><td><?= e($row['timeframe'] ?? '') ?></td><td><?= e($row['credits_used'] ?? 0) ?></td><td><?= e($row['response_ms'] ?? 0) ?></td><td style="max-width:420px"><?= e($row['error_message'] ?? '') ?></td></tr><?php endforeach; ?></tbody></table></div><div class="action-row"><button class="btn btn-danger">Delete Selected Logs</button><div class="pager"><?php if ($page > 1): ?><a href="<?= e(mon_url(['page'=>$page-1])) ?>">Prev</a><?php endif; ?><span class="current">Page <?= e($page) ?> / <?= e($totalPages) ?></span><?php if ($page < $totalPages): ?><a href="<?= e(mon_url(['page'=>$page+1])) ?>">Next</a><?php endif; ?></div></div></form>

    <section class="card"><form method="post" class="action-row" onsubmit="return confirm('Delete old API monitor logs?')"><input type="hidden" name="action" value="clear_old_monitor_logs"><div class="field"><label>Delete logs older than days</label><input type="number" name="older_than_days" value="30" min="1" max="365"></div><button class="btn btn-danger">Delete Old Monitor Logs</button></form></section>
</div>
<?php admin_layout_footer(); ?>
