<?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 api_log_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_log_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 api_log_select_expr(string $table, string $column, string $alias, string $fallback = 'NULL'): string
{
    return api_log_column_exists($table, $column) ? "`$column` AS `$alias`" : $fallback . " AS `$alias`";
}

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

function api_log_lagos_date_to_utc(string $date, string $end = 'start'): string
{
    $date = trim($date);
    if ($date === '') {
        return '';
    }
    $time = $end === 'end' ? '23:59:59' : '00:00:00';
    try {
        $dt = new DateTimeImmutable($date . ' ' . $time, new DateTimeZone('Africa/Lagos'));
        return $dt->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
    } catch (Throwable $e) {
        return $date . ' ' . $time;
    }
}

function api_log_event_tables(): array
{
    // Prefer api_request_logs because the logging layer mirrors provider activity there.
    if (api_log_table_exists('api_request_logs')) {
        return ['api_request_logs'];
    }
    if (api_log_table_exists('api_rotation_logs')) {
        return ['api_rotation_logs'];
    }
    return [];
}

function api_log_build_event_union(): string
{
    $parts = [];
    foreach (api_log_event_tables() as $table) {
        $select = [
            "'" . $table . "' AS log_source",
            api_log_select_expr($table, 'id', 'id', '0'),
            api_log_select_expr($table, 'api_setting_id', 'api_setting_id', 'NULL'),
            api_log_select_expr($table, 'provider', 'provider', "''"),
            api_log_select_expr($table, 'endpoint', 'endpoint', "''"),
            api_log_select_expr($table, 'symbol', 'symbol', "''"),
            api_log_select_expr($table, 'timeframe', 'timeframe', "''"),
            api_log_select_expr($table, 'status', 'status', "'info'"),
            api_log_select_expr($table, 'response_ms', 'response_ms', '0'),
            api_log_select_expr($table, 'credits_used', 'credits_used', '0'),
            api_log_select_expr($table, 'error_message', 'error_message', "''"),
            api_log_select_expr($table, 'created_at', 'created_at', 'NULL'),
        ];
        $parts[] = 'SELECT ' . implode(', ', $select) . " FROM `$table`";
    }
    return $parts ? implode(' UNION ALL ', $parts) : '';
}

function api_log_filters_sql(array &$params): string
{
    $where = [];
    $provider = strtolower(trim((string)($_GET['provider'] ?? '')));
    $symbol = strtoupper(trim((string)($_GET['symbol'] ?? '')));
    $status = strtolower(trim((string)($_GET['status'] ?? '')));
    $dateFrom = trim((string)($_GET['date_from'] ?? ''));
    $dateTo = trim((string)($_GET['date_to'] ?? ''));

    if ($provider !== '') {
        $where[] = 'LOWER(provider) = ?';
        $params[] = $provider;
    }
    if ($symbol !== '') {
        $where[] = 'UPPER(symbol) = ?';
        $params[] = $symbol;
    }
    if ($status !== '') {
        $where[] = 'LOWER(status) = ?';
        $params[] = $status;
    }
    if ($dateFrom !== '') {
        $where[] = 'created_at >= ?';
        $params[] = api_log_lagos_date_to_utc($dateFrom, 'start');
    }
    if ($dateTo !== '') {
        $where[] = 'created_at <= ?';
        $params[] = api_log_lagos_date_to_utc($dateTo, 'end');
    }
    return $where ? ('WHERE ' . implode(' AND ', $where)) : '';
}

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

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

function api_log_delete_by_ids(string $table, array $ids): int
{
    if (!api_log_table_exists($table) || !api_log_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 api_log_current_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') {
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'delete_selected_events') {
            $byTable = [];
            foreach ($_POST['selected_events'] ?? [] as $item) {
                $parts = explode(':', (string)$item, 2);
                if (count($parts) !== 2) continue;
                [$table, $id] = $parts;
                if (!in_array($table, ['api_request_logs', 'api_rotation_logs'], true)) continue;
                $byTable[$table][] = (int)$id;
            }
            $deleted = 0;
            foreach ($byTable as $table => $ids) $deleted += api_log_delete_by_ids($table, $ids);
            $message = $deleted . ' provider event log row(s) deleted.';
        }

        if ($action === 'delete_selected_quotes') {
            $deleted = api_log_delete_by_ids('market_quotes', $_POST['selected_quotes'] ?? []);
            $message = $deleted . ' live quote snapshot row(s) deleted.';
        }

        if ($action === 'clear_old_logs') {
            $days = max(1, min(365, (int)($_POST['older_than_days'] ?? 30)));
            $deleted = 0;
            foreach (['api_request_logs', 'api_rotation_logs', 'market_quotes'] as $table) {
                if (!api_log_table_exists($table) || !api_log_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 log row(s) deleted.';
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

$perPage = max(25, min(200, (int)($_GET['per_page'] ?? $_GET['limit'] ?? 50)));
$eventPage = max(1, (int)($_GET['event_page'] ?? 1));
$quotePage = max(1, (int)($_GET['quote_page'] ?? 1));
$eventOffset = ($eventPage - 1) * $perPage;
$quoteOffset = ($quotePage - 1) * $perPage;

$filterParams = [];
$filterSql = api_log_filters_sql($filterParams);
$eventUnion = api_log_build_event_union();

$events = [];
$eventTotal = 0;
$providerSummary = [];
$symbolSummary = [];
$latestQuotes = [];
$quoteTotal = 0;

try {
    if ($eventUnion !== '') {
        $eventTotal = api_log_fetch_count("SELECT COUNT(*) FROM ($eventUnion) logs $filterSql", $filterParams);
        $events = api_log_fetch_rows("SELECT * FROM ($eventUnion) logs $filterSql ORDER BY created_at DESC LIMIT $perPage OFFSET $eventOffset", $filterParams);

        $providerSummary = api_log_fetch_rows("\n            SELECT provider, api_setting_id,\n                SUM(CASE WHEN status = 'attempt' THEN 1 ELSE 0 END) AS attempts,\n                SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) AS successes,\n                SUM(CASE WHEN status IN ('failed','error') THEN 1 ELSE 0 END) AS failures,\n                SUM(CASE WHEN status = 'rate_limited' THEN 1 ELSE 0 END) AS rate_limited,\n                SUM(COALESCE(credits_used,0)) AS credits_used,\n                MAX(created_at) AS last_seen\n            FROM ($eventUnion) logs\n            WHERE created_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 24 HOUR)\n            GROUP BY provider, api_setting_id\n            ORDER BY successes DESC, attempts DESC, provider ASC\n            LIMIT 50\n        ");

        $symbolSummary = api_log_fetch_rows("\n            SELECT symbol, provider, api_setting_id,\n                SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) AS successes,\n                MAX(created_at) AS last_success\n            FROM ($eventUnion) logs\n            WHERE status = 'success' AND symbol IS NOT NULL AND symbol <> ''\n              AND created_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 24 HOUR)\n            GROUP BY symbol, provider, api_setting_id\n            ORDER BY last_success DESC\n            LIMIT 50\n        ");
    }

    if (api_log_table_exists('market_quotes')) {
        $quoteWhere = [];
        $quoteParams = [];
        $provider = strtolower(trim((string)($_GET['provider'] ?? '')));
        $symbol = strtoupper(trim((string)($_GET['symbol'] ?? '')));
        $dateFrom = trim((string)($_GET['date_from'] ?? ''));
        $dateTo = trim((string)($_GET['date_to'] ?? ''));
        if ($provider !== '') { $quoteWhere[] = 'LOWER(provider) = ?'; $quoteParams[] = $provider; }
        if ($symbol !== '') { $quoteWhere[] = 'UPPER(symbol) = ?'; $quoteParams[] = $symbol; }
        if ($dateFrom !== '') { $quoteWhere[] = 'created_at >= ?'; $quoteParams[] = api_log_lagos_date_to_utc($dateFrom, 'start'); }
        if ($dateTo !== '') { $quoteWhere[] = 'created_at <= ?'; $quoteParams[] = api_log_lagos_date_to_utc($dateTo, 'end'); }
        $quoteSqlWhere = $quoteWhere ? ('WHERE ' . implode(' AND ', $quoteWhere)) : '';
        $quoteTotal = api_log_fetch_count("SELECT COUNT(*) FROM market_quotes $quoteSqlWhere", $quoteParams);
        $latestQuotes = api_log_fetch_rows("\n            SELECT id, symbol, asset_type, provider, source, provider_symbol, price, bid, ask, quote_time, created_at\n            FROM market_quotes\n            $quoteSqlWhere\n            ORDER BY created_at DESC\n            LIMIT $perPage OFFSET $quoteOffset\n        ", $quoteParams);
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$eventPages = max(1, (int)ceil($eventTotal / max(1, $perPage)));
$quotePages = max(1, (int)ceil($quoteTotal / max(1, $perPage)));

admin_layout_header('API Provider Logs');
?>
<style>
.api-log-page{max-width:1500px;margin:0 auto}.api-hero{background:linear-gradient(135deg,#020617,#0f172a,#1e293b);border-radius:34px;padding:34px;color:#fff;margin-bottom:22px}.api-title{font-size:42px;font-weight:900;letter-spacing:-.055em}.api-sub{margin-top:10px;color:#cbd5e1;font-size:15px;max-width:920px;line-height:1.7}.api-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}.api-card h2{margin:0 0 6px;font-size:25px;font-weight:900;color:#020617;letter-spacing:-.035em}.muted{color:#64748b;font-size:13px}.filter-grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:12px;margin-top:18px}.field label{display:block;font-size:11px;font-weight:900;color:#64748b;text-transform:uppercase;letter-spacing:.08em;margin-bottom:7px}.field input,.field select{width:100%;height:44px;border:1px solid #cbd5e1;border-radius:14px;padding:0 12px;font-weight:800;color:#0f172a;background:#fff}.btn{height:44px;border:0;border-radius:14px;padding:0 18px;font-weight:900;cursor:pointer;background:#020617;color:#fff}.btn-danger{background:#991b1b}.btn-soft{background:#f1f5f9;color:#0f172a;border:1px solid #cbd5e1}.summary-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px}.table-wrap{overflow:auto;border:1px solid #e2e8f0;border-radius:20px;margin-top:16px}table{width:100%;border-collapse:collapse;min-width:1050px}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}.badge{display:inline-flex;border-radius:999px;padding:5px 9px;font-size:11px;font-weight:900;text-transform:uppercase}.success{background:#dcfce7;color:#166534}.attempt{background:#dbeafe;color:#1d4ed8}.failed,.error{background:#fee2e2;color:#991b1b}.rate_limited{background:#ffedd5;color:#9a3412}.info{background:#e2e8f0;color:#334155}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono",monospace}.two-col{display:grid;grid-template-columns:1fr 1fr;gap:18px}.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}.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}@media(max-width:1100px){.filter-grid,.summary-grid,.two-col{grid-template-columns:1fr}table{min-width:850px}}
</style>
<div class="api-log-page">
    <section class="api-hero">
        <div class="api-title">API Provider Logs</div>
        <div class="api-sub">Review which provider row supplied live quotes and candle data. Times are displayed in Lagos, Nigeria time. Duplicate FMP/TwelveData rows remain separated by API settings row ID.</div>
    </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="api-card">
        <h2>Filters</h2>
        <div class="muted">Date filters are interpreted as Lagos time and converted to UTC internally for database matching.</div>
        <form method="get" class="filter-grid">
            <div class="field"><label>Provider</label><input name="provider" value="<?= e($_GET['provider'] ?? '') ?>" placeholder="fmp"></div>
            <div class="field"><label>Symbol</label><input name="symbol" value="<?= e($_GET['symbol'] ?? '') ?>" placeholder="EURUSD"></div>
            <div class="field"><label>Status</label><select name="status"><option value="">All</option><?php foreach(['attempt','success','failed','rate_limited'] as $st): ?><option value="<?= e($st) ?>" <?= (($_GET['status'] ?? '') === $st) ? 'selected' : '' ?>><?= e($st) ?></option><?php endforeach; ?></select></div>
            <div class="field"><label>From</label><input type="date" name="date_from" value="<?= e($_GET['date_from'] ?? '') ?>"></div>
            <div class="field"><label>To</label><input type="date" name="date_to" value="<?= e($_GET['date_to'] ?? '') ?>"></div>
            <div class="field"><label>Per Page</label><input type="number" name="per_page" value="<?= e($perPage) ?>"></div>
            <div class="field" style="align-self:end"><button class="btn">Apply Filters</button></div>
            <div class="field" style="align-self:end"><a class="btn btn-soft" href="?" style="display:inline-flex;align-items:center;text-decoration:none">Reset</a></div>
        </form>
        <form method="post" class="action-row" onsubmit="return confirm('Delete old API logs and quote snapshots?')">
            <input type="hidden" name="action" value="clear_old_logs">
            <div class="field" style="max-width:220px"><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 Logs</button>
        </form>
    </section>

    <section class="api-card">
        <h2>24-Hour Provider Usage Summary</h2>
        <div class="muted">Grouped by provider and API row. Last seen is Lagos time.</div>
        <div class="table-wrap"><table><thead><tr><th>Provider</th><th>API Row</th><th>Attempts</th><th>Successes</th><th>Failures</th><th>Rate Limited</th><th>Credits Counted</th><th>Last Seen Lagos</th></tr></thead><tbody>
        <?php if (!$providerSummary): ?><tr><td colspan="8" class="muted">No provider log rows found yet.</td></tr><?php endif; ?>
        <?php foreach ($providerSummary as $row): ?><tr><td><strong><?= e(strtoupper($row['provider'] ?? '')) ?></strong></td><td class="mono"><?= e($row['api_setting_id'] ?: 'public') ?></td><td><?= e($row['attempts'] ?? 0) ?></td><td><?= e($row['successes'] ?? 0) ?></td><td><?= e($row['failures'] ?? 0) ?></td><td><?= e($row['rate_limited'] ?? 0) ?></td><td><?= e($row['credits_used'] ?? 0) ?></td><td class="mono"><?= e(api_log_lagos_time($row['last_seen'] ?? '')) ?></td></tr><?php endforeach; ?>
        </tbody></table></div>
    </section>

    <section class="api-card">
        <h2>Successful Provider by Pair</h2>
        <div class="muted">Shows which provider row most recently succeeded for each symbol within the last 24 hours. Last success is Lagos time.</div>
        <div class="table-wrap"><table><thead><tr><th>Symbol</th><th>Provider</th><th>API Row</th><th>Successful Uses</th><th>Last Success Lagos</th></tr></thead><tbody>
        <?php if (!$symbolSummary): ?><tr><td colspan="5" class="muted">No successful provider rows found yet.</td></tr><?php endif; ?>
        <?php foreach ($symbolSummary as $row): ?><tr><td><strong><?= e($row['symbol'] ?? '') ?></strong></td><td><?= e(strtoupper($row['provider'] ?? '')) ?></td><td class="mono"><?= e($row['api_setting_id'] ?: 'public') ?></td><td><?= e($row['successes'] ?? 0) ?></td><td class="mono"><?= e(api_log_lagos_time($row['last_success'] ?? '')) ?></td></tr><?php endforeach; ?>
        </tbody></table></div>
    </section>

    <form method="post" class="api-card" onsubmit="return confirm('Delete selected provider event logs?')">
        <input type="hidden" name="action" value="delete_selected_events">
        <h2>Provider Event Logs</h2>
        <div class="muted">Showing <?= e(number_format(count($events))) ?> of <?= e(number_format($eventTotal)) ?> rows. Times are Lagos time.</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><th>Source</th></tr></thead><tbody>
        <?php if (!$events): ?><tr><td colspan="12" class="muted">No provider event logs found.</td></tr><?php endif; ?>
        <?php foreach ($events as $row): $st = strtolower((string)($row['status'] ?? 'info')); $logId = (int)($row['id'] ?? 0); $src = (string)($row['log_source'] ?? ''); ?>
            <tr><td><?php if ($logId > 0 && in_array($src, ['api_request_logs','api_rotation_logs'], true)): ?><input type="checkbox" name="selected_events[]" value="<?= e($src . ':' . $logId) ?>"><?php endif; ?></td><td class="mono"><?= e(api_log_lagos_time($row['created_at'] ?? '')) ?></td><td><span class="badge <?= e($st) ?>"><?= e($st) ?></span></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:360px"><?= e($row['error_message'] ?? '') ?></td><td><?= e($src) ?></td></tr>
        <?php endforeach; ?>
        </tbody></table></div>
        <div class="action-row"><button class="btn btn-danger">Delete Selected Event Logs</button><div class="pager"><?php if ($eventPage > 1): ?><a href="<?= e(api_log_current_url(['event_page'=>$eventPage-1])) ?>">Prev</a><?php endif; ?><span class="current">Page <?= e($eventPage) ?> / <?= e($eventPages) ?></span><?php if ($eventPage < $eventPages): ?><a href="<?= e(api_log_current_url(['event_page'=>$eventPage+1])) ?>">Next</a><?php endif; ?></div></div>
    </form>

    <form method="post" class="api-card" onsubmit="return confirm('Delete selected live quote snapshots?')">
        <input type="hidden" name="action" value="delete_selected_quotes">
        <h2>Latest Live Quote Snapshots</h2>
        <div class="muted">This comes from market_quotes and shows the provider/source that supplied cached live quotes. Times are Lagos time.</div>
        <div class="table-wrap"><table><thead><tr><th>Select</th><th>Created Lagos</th><th>Quote Time Lagos</th><th>Symbol</th><th>Asset</th><th>Provider</th><th>Source</th><th>Provider Symbol</th><th>Price</th><th>Bid</th><th>Ask</th></tr></thead><tbody>
        <?php if (!$latestQuotes): ?><tr><td colspan="11" class="muted">No live quote snapshots found yet.</td></tr><?php endif; ?>
        <?php foreach ($latestQuotes as $row): ?><tr><td><input type="checkbox" name="selected_quotes[]" value="<?= e($row['id'] ?? 0) ?>"></td><td class="mono"><?= e(api_log_lagos_time($row['created_at'] ?? '')) ?></td><td class="mono"><?= e(api_log_lagos_time($row['quote_time'] ?? '')) ?></td><td><strong><?= e($row['symbol'] ?? '') ?></strong></td><td><?= e($row['asset_type'] ?? '') ?></td><td><strong><?= e(strtoupper($row['provider'] ?? '')) ?></strong></td><td><?= e($row['source'] ?? '') ?></td><td><?= e($row['provider_symbol'] ?? '') ?></td><td class="mono"><?= e($row['price'] ?? '') ?></td><td class="mono"><?= e($row['bid'] ?? '') ?></td><td class="mono"><?= e($row['ask'] ?? '') ?></td></tr><?php endforeach; ?>
        </tbody></table></div>
        <div class="action-row"><button class="btn btn-danger">Delete Selected Quote Snapshots</button><div class="pager"><?php if ($quotePage > 1): ?><a href="<?= e(api_log_current_url(['quote_page'=>$quotePage-1])) ?>">Prev</a><?php endif; ?><span class="current">Page <?= e($quotePage) ?> / <?= e($quotePages) ?></span><?php if ($quotePage < $quotePages): ?><a href="<?= e(api_log_current_url(['quote_page'=>$quotePage+1])) ?>">Next</a><?php endif; ?></div></div>
    </form>
</div>
<?php admin_layout_footer(); ?>
