<?php

declare(strict_types=1);

require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/api_client.php';
require_once __DIR__ . '/includes/api_service.php';

header('Content-Type: text/html; charset=utf-8');

$config = api_config();
$baseUrl = rtrim((string)($config['base_url'] ?? ''), '/');
$checks = [];

function api_status_row(string $label, bool $ok, string $detail = ''): array
{
    return ['label' => $label, 'ok' => $ok, 'detail' => $detail];
}

$checks[] = api_status_row('PHP cURL extension', api_curl_available(), api_curl_available() ? 'enabled' : 'MISSING — enable curl in php.ini');
$checks[] = api_status_row('API enabled', api_is_configured(), 'enabled=' . (($config['enabled'] ?? false) ? 'true' : 'false'));
$checks[] = api_status_row('Auth enabled', api_auth_enabled(), 'auth_enabled=' . (($config['auth_enabled'] ?? false) ? 'true' : 'false'));
$checks[] = api_status_row('Base URL', $baseUrl !== '', $baseUrl);

$loginId = trim((string)($config['service_login'] ?? app_config()['admin_username'] ?? 'admin'));
$loginPassword = (string)($config['service_password'] ?? app_config()['admin_password'] ?? '');
$loginResult = api_auth_login($loginId, $loginPassword);
$checks[] = api_status_row(
    'POST /karvipartner/login',
    !empty($loginResult['success']),
    (string)($loginResult['message'] ?? json_encode($loginResult, JSON_UNESCAPED_UNICODE))
);

$checks[] = api_status_row('Session bearer token', api_bearer_token() !== null, api_bearer_token() !== null ? 'present' : 'missing (login via API email for admin dashboard sync)');
$checks[] = api_status_row('Service bearer token', api_resolve_bearer_token() !== null, api_resolve_bearer_token() !== null ? 'present' : 'missing — set service_login + service_password in config/api.php');
$checks[] = api_status_row('Partner API ready', api_can_use_partner_api(), api_can_use_partner_api() ? 'yes' : 'no');

foreach ($config['endpoints'] ?? [] as $key => $path) {
    $checks[] = api_status_row('Endpoint: ' . $key, true, $path);
}

if (api_can_use_partner_api()) {
    try {
        $response = api_partner_get('contracts_list');
        $count = count(api_extract_list($response));
        $checks[] = api_status_row('GET /karvipartner/contracts', true, 'contracts=' . $count);
    } catch (Throwable $e) {
        $checks[] = api_status_row('GET /karvipartner/contracts', false, api_error_message($e));
    }
}

$localContracts = local_store_all_contracts();
$sampleToken = '';
foreach ($localContracts as $contract) {
    $candidate = trim((string)($contract['sign_token'] ?? $contract['token'] ?? ''));
    if ($candidate !== '') {
        $sampleToken = $candidate;
        break;
    }
}

if ($sampleToken !== '' && api_feature_enabled('contract_get')) {
    try {
        $response = api_public_get('contract_get', ['token' => $sampleToken]);
        $checks[] = api_status_row('GET /api/contracts/{token}', true, json_encode($response, JSON_UNESCAPED_UNICODE));
    } catch (Throwable $e) {
        $checks[] = api_status_row('GET /api/contracts/{token}', false, api_error_message($e));
    }
}

$customerFeatures = $config['customer'] ?? [];
if (is_array($customerFeatures)) {
    foreach ($customerFeatures as $feature => $enabled) {
        $checks[] = api_status_row('Customer: ' . $feature, (bool)$enabled, $enabled ? 'ON' : 'OFF');
    }
}

$allOk = true;
foreach ($checks as $check) {
    if (!$check['ok']) {
        $allOk = false;
        break;
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Karvi API Status</title>
    <style>
        body { font-family: system-ui, sans-serif; margin: 2rem; background: #f8fafc; color: #0f172a; }
        h1 { margin-bottom: 0.25rem; }
        .meta { color: #64748b; margin-bottom: 1.5rem; }
        table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 12px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
        th, td { padding: 12px 14px; border-bottom: 1px solid #e2e8f0; text-align: left; vertical-align: top; }
        th { background: #0f172a; color: #fff; }
        .ok { color: #15803d; font-weight: 600; }
        .fail { color: #b91c1c; font-weight: 600; }
        pre { white-space: pre-wrap; word-break: break-word; font-size: 12px; margin: 0; color: #334155; }
        .banner { padding: 12px 16px; border-radius: 10px; margin-bottom: 1rem; }
        .banner.ok { background: #dcfce7; color: #166534; }
        .banner.fail { background: #fee2e2; color: #991b1b; }
        a { color: #2563eb; }
    </style>
</head>
<body>
    <h1>Karvi API Status</h1>
    <p class="meta">
        Server time: <?= htmlspecialchars(date('Y-m-d H:i:s T')) ?> |
        <a href="health.php">health.php</a>
    </p>

    <div class="banner <?= $allOk ? 'ok' : 'fail' ?>">
        <?= $allOk ? 'All checks passed.' : 'Some API checks failed — see details below.' ?>
    </div>

    <table>
        <thead>
            <tr>
                <th>Check</th>
                <th>Status</th>
                <th>Detail</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($checks as $check): ?>
            <tr>
                <td><?= htmlspecialchars($check['label']) ?></td>
                <td class="<?= $check['ok'] ? 'ok' : 'fail' ?>"><?= $check['ok'] ? 'OK' : 'FAIL' ?></td>
                <td><pre><?= htmlspecialchars($check['detail']) ?></pre></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <p class="meta" style="margin-top: 1.5rem;">
        Admin sync ke liye <code>config/api.php</code> mein Karvi API email/password set karein:<br>
        <code>'service_login' => 'your@email.com', 'service_password' => 'your_password'</code>
    </p>
</body>
</html>
