<?php
use MintyPHP\Domain\Taxonomy\ImportAuditStatus;

/**
 * @var array $auditRun
 */

$auditRun = $auditRun ?? [];
$status = ImportAuditStatus::normalizeOr((string) ($auditRun['status'] ?? ''), ImportAuditStatus::Failed);
$statusVariant = $status->badgeVariant();

$profileKey = strtolower(trim((string) ($auditRun['profile_key'] ?? '')));
$profileLabel = $profileKey;
if ($profileKey === 'users') {
  $profileLabel = t('Users');
} elseif ($profileKey === 'departments') {
  $profileLabel = t('Departments');
}

$mappedCsv = trim((string) ($auditRun['mapped_targets_csv'] ?? ''));
$mappedFields = [];
if ($mappedCsv !== '') {
  $mappedFields = array_values(array_filter(array_map('trim', explode(',', $mappedCsv)), static fn ($item) => $item !== ''));
}

$errorCodesJson = trim((string) ($auditRun['error_codes_json'] ?? ''));
$errorCodes = [];
if ($errorCodesJson !== '') {
  $decoded = json_decode($errorCodesJson, true);
  if (is_array($decoded)) {
    foreach ($decoded as $code => $count) {
      $code = trim((string) $code);
      $count = (int) $count;
      if ($code === '' || $count <= 0) {
        continue;
      }
      $errorCodes[$code] = $count;
    }
  }
}
arsort($errorCodes);

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

<div class="app-details-container">
  <section>
    <?php
    $breadcrumbs = [
      ['label' => t('Home'), 'path' => 'admin'],
      ['label' => t('Import audit logs'), 'path' => 'admin/import-audit'],
      ['label' => t('View')],
    ];
    require templatePath('partials/app-breadcrumb.phtml');

    $titlebar = [
      'title' => t('View import audit entry'),
      'backHref' => 'admin/import-audit',
      'backTitle' => t('Back'),
    ];
    require templatePath('partials/app-details-titlebar.phtml');
    ?>

    <div class="app-details-content">
      <details open>
        <summary><?php e(t('Import details')); ?></summary>
        <hr>
        <div class="grid">
          <div>
            <small><?php e(t('Profile')); ?></small>
            <p><span class="badge" data-variant="neutral"><?php e($profileLabel !== '' ? $profileLabel : '-'); ?></span></p>
          </div>
          <div>
            <small><?php e(t('Status')); ?></small>
            <p><span class="badge" data-variant="<?php e($statusVariant); ?>"><?php e(t($status->labelToken())); ?></span></p>
          </div>
        </div>
        <div class="grid">
          <div>
            <small><?php e(t('Started')); ?></small>
            <p><?php e(dt((string) ($auditRun['started_at'] ?? '')) ?: '-'); ?></p>
          </div>
          <div>
            <small><?php e(t('Finished')); ?></small>
            <p><?php e(dt((string) ($auditRun['finished_at'] ?? '')) ?: '-'); ?></p>
          </div>
        </div>
        <div class="grid">
          <div>
            <small><?php e(t('Duration (ms)')); ?></small>
            <p><?php e((int) ($auditRun['duration_ms'] ?? 0) > 0 ? (string) ((int) $auditRun['duration_ms']) : '-'); ?></p>
          </div>
          <div>
            <small><?php e(t('File')); ?></small>
            <p><?php e((string) ($auditRun['source_filename'] ?? '') !== '' ? (string) $auditRun['source_filename'] : '-'); ?></p>
          </div>
        </div>
      </details>

      <hr>
      <details open>
        <summary><?php e(t('Counters')); ?></summary>
        <hr>
        <div class="grid">
          <div>
            <small><?php e(t('Rows total')); ?></small>
            <p><?php e((string) ((int) ($auditRun['rows_total'] ?? 0))); ?></p>
          </div>
          <div>
            <small><?php e(t('Created count')); ?></small>
            <p><?php e((string) ((int) ($auditRun['created_count'] ?? 0))); ?></p>
          </div>
        </div>
        <div class="grid">
          <div>
            <small><?php e(t('Skipped count')); ?></small>
            <p><?php e((string) ((int) ($auditRun['skipped_count'] ?? 0))); ?></p>
          </div>
          <div>
            <small><?php e(t('Failed count')); ?></small>
            <p><?php e((string) ((int) ($auditRun['failed_count'] ?? 0))); ?></p>
          </div>
        </div>
      </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($auditRun['user_uuid'])): ?>
                <a href="admin/users/edit/<?php e((string) $auditRun['user_uuid']); ?>"><?php e($userLabel); ?></a>
              <?php else: ?>
                <?php e($userLabel); ?>
              <?php endif; ?>
            </p>
          </div>
          <div>
            <small><?php e(t('Current tenant')); ?></small>
            <p>
              <?php if (!empty($auditRun['current_tenant_uuid'])): ?>
                <a href="admin/tenants/edit/<?php e((string) $auditRun['current_tenant_uuid']); ?>"><?php e($tenantLabel); ?></a>
              <?php else: ?>
                <?php e($tenantLabel); ?>
              <?php endif; ?>
            </p>
          </div>
        </div>
      </details>

      <?php if ($mappedFields): ?>
        <hr>
        <details>
          <summary><?php e(t('Mapped fields')); ?></summary>
          <hr>
          <p><?php e(implode(', ', $mappedFields)); ?></p>
        </details>
      <?php endif; ?>

      <?php if ($errorCodes): ?>
        <hr>
        <details>
          <summary><?php e(t('Error code distribution')); ?></summary>
          <hr>
          <div class="app-list-table">
            <table>
              <thead>
                <tr>
                  <th><?php e(t('Error code')); ?></th>
                  <th><?php e(t('Count')); ?></th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($errorCodes as $code => $count): ?>
                  <tr>
                    <td><code><?php e((string) $code); ?></code></td>
                    <td><?php e((string) $count); ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </details>
      <?php endif; ?>
    </div>
  </section>

  <aside id="app-details-aside-section">
    <div class="app-details-aside-section">
      <hgroup>
        <strong><?php e(t('Import logs')); ?></strong>
        <p><small><?php e((string) ($auditRun['run_uuid'] ?? '') !== '' ? (string) $auditRun['run_uuid'] : '-'); ?></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) ($auditRun['id'] ?? '')); ?>">
              <?php e((string) ($auditRun['id'] ?? '-')); ?>
            </span>
          </p>
        </div>
        <div>
          <small><?php e(t('Status')); ?></small>
          <p><span class="badge" data-variant="<?php e($statusVariant); ?>"><?php e(t($status->labelToken())); ?></span></p>
        </div>
      </div>
      <div>
        <small><?php e(t('Run UUID')); ?></small>
        <p>
          <span class="badge" data-variant="neutral" data-copy="true" data-copy-value="<?php e((string) ($auditRun['run_uuid'] ?? '')); ?>">
            <?php e((string) ($auditRun['run_uuid'] ?? '') !== '' ? substr((string) $auditRun['run_uuid'], 0, 10) : '-'); ?>
          </span>
        </p>
      </div>
      <div>
        <small><?php e(t('Created')); ?></small>
        <p><?php e(dt((string) ($auditRun['started_at'] ?? '')) ?: '-'); ?></p>
      </div>
      <div>
        <small><?php e(t('Duration (ms)')); ?></small>
        <p><?php e((int) ($auditRun['duration_ms'] ?? 0) > 0 ? (string) ((int) $auditRun['duration_ms']) : '-'); ?></p>
      </div>
    </div>
  </aside>
</div>
