<?php

/**
 * @var array $auditLog
 */

$auditLog = $auditLog ?? [];
$statusCode = (int) ($auditLog['status_code'] ?? 0);
$statusVariant = 'neutral';
if ($statusCode >= 200 && $statusCode < 300) {
  $statusVariant = 'success';
} elseif ($statusCode >= 400 && $statusCode < 500) {
  $statusVariant = 'warning';
} elseif ($statusCode >= 500) {
  $statusVariant = 'danger';
}

$queryKeys = is_array($auditLog['query_keys'] ?? null) ? $auditLog['query_keys'] : [];
$queryJson = trim((string) ($auditLog['query_json'] ?? ''));
if ($queryKeys === [] && $queryJson !== '') {
  $decoded = json_decode($queryJson, true);
  $decodedKeys = is_array($decoded['keys'] ?? null) ? $decoded['keys'] : [];
  foreach ($decodedKeys as $value) {
    $key = trim((string) $value);
    if ($key === '' || in_array($key, $queryKeys, true)) {
      continue;
    }
    $queryKeys[] = $key;
  }
}
$queryMetadataPretty = '-';
if ($queryKeys !== []) {
  $pretty = json_encode(['keys' => $queryKeys], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  $queryMetadataPretty = is_string($pretty) ? $pretty : '-';
}

$userLabel = trim((string) ($auditLog['user_display_name'] ?? ''));
$userEmail = trim((string) ($auditLog['user_email'] ?? ''));
if ($userLabel === '') {
  $userLabel = $userEmail !== '' ? $userEmail : '-';
}
$tenantLabel = trim((string) ($auditLog['tenant_description'] ?? ''));
if ($tenantLabel === '') {
  $tenantLabel = '-';
}

$requestId = trim((string) ($auditLog['request_id'] ?? ''));
$method = strtoupper(trim((string) ($auditLog['method'] ?? '')));
$path = trim((string) ($auditLog['path'] ?? ''));
$errorCode = trim((string) ($auditLog['error_code'] ?? ''));
$ipHash = trim((string) ($auditLog['ip_hash'] ?? $auditLog['ip'] ?? ''));
$userAgentHash = trim((string) ($auditLog['user_agent_hash'] ?? $auditLog['user_agent'] ?? ''));
$durationMs = (int) ($auditLog['duration_ms'] ?? 0);
$tokenId = (int) ($auditLog['api_token_id'] ?? 0);
$tokenTenantId = (int) ($auditLog['token_tenant_id'] ?? 0);
?>

<div class="app-details-container">
  <section>
    <?php
    $titlebar = [
      'title' => t('View API audit entry'),
      'backHref' => 'audit/api-audit',
      'backTitle' => t('Back'),
    ];
    require templatePath('partials/app-details-titlebar.phtml');
    ?>

    <div class="app-details-content">
      <details open>
        <summary><?php e(t('Request details')); ?></summary>
        <hr>
        <div class="grid">
          <div>
            <small><?php e(t('Method')); ?></small>
            <p><span class="badge" data-variant="neutral"><?php e($method !== '' ? $method : '-'); ?></span></p>
          </div>
          <div>
            <small><?php e(t('Path')); ?></small>
            <p><code><?php e($path !== '' ? $path : '-'); ?></code></p>
          </div>
        </div>
        <?php if ($errorCode !== '' || $ipHash !== ''): ?>
          <div class="grid">
            <div>
              <small><?php e(t('Error code')); ?></small>
              <p><?php e($errorCode !== '' ? $errorCode : '-'); ?></p>
            </div>
            <div>
              <small><?php e(t('IP hash')); ?></small>
              <p><code><?php e($ipHash !== '' ? substr($ipHash, 0, 16) . '...' : '-'); ?></code></p>
            </div>
          </div>
        <?php endif; ?>
        <?php if ($userAgentHash !== ''): ?>
          <div>
            <small><?php e(t('User agent hash')); ?></small>
            <p><code><?php e(substr($userAgentHash, 0, 16) . '...'); ?></code></p>
          </div>
        <?php endif; ?>
      </details>

      <hr>
      <details open>
        <summary><?php e(t('Scope')); ?></summary>
        <hr>
        <div class="grid">
          <div>
            <small><?php e(t('User')); ?></small>
            <p>
              <?php if (!empty($auditLog['user_uuid'])): ?>
                <a href="admin/users/edit/<?php e($auditLog['user_uuid']); ?>"><?php e($userLabel); ?></a>
              <?php else: ?>
                <?php e($userLabel); ?>
              <?php endif; ?>
            </p>
          </div>
          <div>
            <small><?php e(t('Tenant')); ?></small>
            <p>
              <?php if (!empty($auditLog['tenant_uuid'])): ?>
                <a href="admin/tenants/edit/<?php e($auditLog['tenant_uuid']); ?>"><?php e($tenantLabel); ?></a>
              <?php else: ?>
                <?php e($tenantLabel); ?>
              <?php endif; ?>
            </p>
          </div>
        </div>
        <?php if ($tokenId > 0 || $tokenTenantId > 0): ?>
          <div class="grid">
            <div>
              <small><?php e(t('Token ID')); ?></small>
              <p><?php e($tokenId > 0 ? (string) $tokenId : '-'); ?></p>
            </div>
            <div>
              <small><?php e(t('Token tenant')); ?></small>
              <p><?php e($tokenTenantId > 0 ? (string) $tokenTenantId : '-'); ?></p>
            </div>
          </div>
        <?php endif; ?>
      </details>

      <?php if ($queryMetadataPretty !== '-'): ?>
        <hr>
        <details>
          <summary><?php e(t('Query metadata (keys)')); ?></summary>
          <hr>
          <textarea readonly rows="8"><?php e($queryMetadataPretty); ?></textarea>
        </details>
      <?php endif; ?>
    </div>
  </section>

  <aside id="app-details-aside-section">
    <div class="app-details-aside-section">
      <hgroup>
        <strong><?php e(t('API audit')); ?></strong>
        <p><small><?php e($requestId !== '' ? $requestId : '-'); ?></small></p>
      </hgroup>
      <hr>
      <div class="grid">
        <div>
          <small><?php e(t('ID')); ?></small>
          <p>
            <span class="badge" data-variant="neutral" data-copy="true" data-copy-value="<?php e((string) ($auditLog['id'] ?? '')); ?>">
              <?php e((string) ($auditLog['id'] ?? '-')); ?>
            </span>
          </p>
        </div>
        <div>
          <small><?php e(t('Status')); ?></small>
          <p><span class="badge" data-variant="<?php e($statusVariant); ?>"><?php e((string) $statusCode); ?></span></p>
        </div>
      </div>
      <div>
        <small><?php e(t('Request ID')); ?></small>
        <p>
          <span class="badge" data-variant="neutral" data-copy="true" data-copy-value="<?php e($requestId); ?>">
            <?php e($requestId !== '' ? substr($requestId, 0, 10) : '-'); ?>
          </span>
        </p>
      </div>
      <div>
        <small><?php e(t('Created')); ?></small>
        <p><?php e(dt((string) ($auditLog['created_at'] ?? '')) ?: '-'); ?></p>
      </div>
      <div>
        <small><?php e(t('Duration (ms)')); ?></small>
        <p><?php e($durationMs > 0 ? (string) $durationMs : '-'); ?></p>
      </div>
    </div>
  </aside>
</div>
