<?php
require_once '../../includes/header.php';
require_once '../../classes/MraEisOnboarding.php';

if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    header('Location: ../../unauthorized.php');
    exit;
}

$branchId = isset($_GET['branch_id']) && $_GET['branch_id'] !== '' ? (int)$_GET['branch_id'] : 7;
$diagnostics = null;
$message = null;

try {
    $eis = new MraEisOnboarding($conn);
    $diagnostics = $eis->warehouseTerminalDiagnostics($branchId);
} catch (Throwable $e) {
    $message = $e->getMessage();
}

function mra_diag_status_badge($status) {
    if ($status === null) {
        return 'secondary';
    }
    if ($status >= 200 && $status < 300) {
        return 'success';
    }
    if ($status === 401 || $status === 403) {
        return 'warning';
    }
    return 'danger';
}
?>

<style>
    body { background: #f4f6f8; }
    .eis-shell { max-width: 1100px; margin: 30px auto; padding: 0 15px; }
    .eis-topbar { display: flex; justify-content: space-between; gap: 16px; align-items: center; margin-bottom: 20px; }
    .eis-title { font-weight: 800; color: #172033; }
    .eis-card { border: 0; border-radius: 8px; box-shadow: 0 2px 12px rgba(15, 23, 42, 0.08); margin-bottom: 20px; }
    .eis-card .card-header { background: #1f2937; color: #fff; border-radius: 8px 8px 0 0; }
    .table td, .table th { vertical-align: middle; }
    pre.diag-body { white-space: pre-wrap; background: #f8f9fa; border: 1px solid #e5e7eb; border-radius: 6px; padding: 10px; margin: 0; }
</style>

<div class="eis-shell">
    <?php $eisNavCurrent = ''; require __DIR__ . '/../../includes/eis_admin_nav.php'; ?>

    <div class="eis-topbar">
        <div>
            <h2 class="eis-title mb-1"><i class="fas fa-stethoscope"></i> MRA EIS Warehouse Diagnostics</h2>
            <p class="text-muted mb-0">Checks which terminal token would be used for warehouse stock, and tests it against MRA independently of the warehouse-inventory endpoint.</p>
        </div>
        <div class="d-flex flex-wrap" style="gap: 8px;">
            <a href="mra_eis_site_products.php?warehouse_stock=1" class="btn btn-outline-primary">
                <i class="fas fa-warehouse"></i> Warehouse Stock
            </a>
            <a href="mra_eis_onboarding.php" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left"></i> Onboarding
            </a>
        </div>
    </div>

    <form method="GET" class="card eis-card">
        <div class="card-body d-flex flex-wrap align-items-end" style="gap: 12px;">
            <div>
                <label class="form-label" for="branch_id">Branch ID</label>
                <input type="number" class="form-control" id="branch_id" name="branch_id" value="<?php echo htmlspecialchars((string)$branchId); ?>" style="width: 140px;">
            </div>
            <button type="submit" class="btn btn-primary"><i class="fas fa-sync-alt"></i> Run Diagnostics</button>
        </div>
    </form>

    <?php if ($message): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($message); ?></div>
    <?php elseif ($diagnostics): ?>

        <div class="card eis-card">
            <div class="card-header"><h5 class="mb-0"><i class="fas fa-server"></i> Terminal Candidates for Branch <?php echo (int)$branchId; ?></h5></div>
            <div class="card-body">
                <?php if ($diagnostics['used_fallback']): ?>
                    <div class="alert alert-warning">No activated terminal is assigned to branch <?php echo (int)$branchId; ?> directly &mdash; falling back to the best activated terminal from any branch, exactly like the live warehouse page does.</div>
                <?php endif; ?>

                <?php if (empty($diagnostics['candidates'])): ?>
                    <div class="alert alert-info mb-0">No activated EIS terminal with a stored token exists anywhere. Activate and confirm a terminal first.</div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered mb-0">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Label</th>
                                    <th>Branch</th>
                                    <th>Environment</th>
                                    <th>API Base URL</th>
                                    <th>Site ID</th>
                                    <th>TIN</th>
                                    <th>JWT Length</th>
                                    <th>JWT Preview</th>
                                    <th>Confirmed At</th>
                                    <th>Updated At</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($diagnostics['candidates'] as $i => $terminal): ?>
                                    <tr class="<?php echo $i === 0 ? 'table-primary' : ''; ?>">
                                        <td><?php echo $i === 0 ? '<strong>Used</strong>' : ($i + 1); ?></td>
                                        <td><?php echo htmlspecialchars((string)$terminal['terminal_label']); ?></td>
                                        <td><?php echo htmlspecialchars((string)($terminal['branch_name'] ?? $terminal['branch_id'])); ?></td>
                                        <td><?php echo htmlspecialchars((string)$terminal['environment']); ?></td>
                                        <td><?php echo htmlspecialchars((string)$terminal['api_base_url']); ?></td>
                                        <td><?php echo htmlspecialchars((string)($terminal['site_id'] ?? '')); ?></td>
                                        <td><?php echo htmlspecialchars((string)($terminal['taxpayer_tin'] ?? '')); ?></td>
                                        <td><?php echo (int)$terminal['jwt_length']; ?></td>
                                        <td><code><?php echo htmlspecialchars((string)$terminal['jwt_preview']); ?></code></td>
                                        <td><?php echo htmlspecialchars((string)($terminal['confirmed_at'] ?? '')); ?></td>
                                        <td><?php echo htmlspecialchars((string)($terminal['updated_at'] ?? '')); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($diagnostics['ping']): ?>
            <div class="card eis-card">
                <div class="card-header"><h5 class="mb-0"><i class="fas fa-heartbeat"></i> Auth-only Check: POST /utilities/ping</h5></div>
                <div class="card-body">
                    <p class="text-muted">Tests whether the resolved terminal's token is accepted by MRA at all, independent of the warehouse-inventory endpoint. If this fails the same way, the problem is the token/environment &mdash; not warehouse-inventory specifically.</p>
                    <table class="table table-sm table-bordered mb-2">
                        <thead>
                            <tr><th>Method</th><th>HTTP Status</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($diagnostics['ping']['attempts'] as $attempt): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($attempt['method']); ?></td>
                                    <td><span class="badge bg-<?php echo mra_diag_status_badge($attempt['status']); ?>"><?php echo (int)$attempt['status']; ?></span></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <details>
                        <summary>Raw response body (last attempt)</summary>
                        <pre class="diag-body mt-2"><?php echo htmlspecialchars(end($diagnostics['ping']['attempts'])['body'] ?? ''); ?></pre>
                    </details>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($diagnostics['warehouse_test']): ?>
            <div class="card eis-card">
                <div class="card-header"><h5 class="mb-0"><i class="fas fa-warehouse"></i> Direct Test: GET /stock/warehouse-inventory (1 row)</h5></div>
                <div class="card-body">
                    <p>
                        HTTP Status:
                        <span class="badge bg-<?php echo mra_diag_status_badge($diagnostics['warehouse_test']['status']); ?>">
                            <?php echo (int)$diagnostics['warehouse_test']['status']; ?>
                        </span>
                        &nbsp; Authorization used: <?php echo htmlspecialchars((string)($diagnostics['warehouse_test']['authorization_method'] ?? 'none succeeded')); ?>
                    </p>
                    <details open>
                        <summary>Raw response body</summary>
                        <pre class="diag-body mt-2"><?php echo htmlspecialchars((string)($diagnostics['warehouse_test']['body'] ?? '')); ?></pre>
                    </details>
                </div>
            </div>
        <?php endif; ?>

        <div class="alert alert-secondary">
            <strong>How to read this:</strong>
            <ul class="mb-0">
                <li>Ping succeeds, warehouse-inventory fails &rarr; MRA-side issue specific to that endpoint/terminal (e.g. terminal not provisioned for warehouse stock, or a transient MRA outage). Not fixable from our code.</li>
                <li>Both ping and warehouse-inventory fail with the same status/body &rarr; the token itself is invalid/expired or pointed at the wrong environment (sandbox token vs production URL or vice versa). Re-confirm the terminal on the Onboarding page to get a fresh token.</li>
                <li>Ping fails with a clean 401, warehouse-inventory fails with 500 &rarr; MRA's warehouse-inventory endpoint is mishandling an expired/invalid token as a server error instead of a clean 401. Still fixed by re-confirming the terminal.</li>
            </ul>
        </div>
    <?php endif; ?>
</div>

<?php include '../../includes/footer.php'; ?>
