<?php
/**
 * @var array $entries
 * @var \App\Repositories\UserRepository $userRepo
 * @var string $search
 * @var string $filterStaff
 * @var string $filterAction
 * @var array  $staffOptions   [id => name]
 * @var array  $actionOptions  [action_string, ...]
 */

// Action label map for human-readable display
$actionLabels = [
    'APPROVE_APPT'         => ['Approved appointment',     'bg-green-500/10 text-green-400 border-green-500/20'],
    'CANCEL_APPT'          => ['Canceled appointment',     'bg-red-500/10 text-red-400 border-red-500/20'],
    'COMPLETE_APPT'        => ['Completed appointment',    'bg-blue-500/10 text-blue-400 border-blue-500/20'],
    'CREATE_WALKIN'         => ['Created walk-in',          'bg-purple-500/10 text-purple-400 border-purple-500/20'],
    'CREATE_APPT'          => ['Created appointment',      'bg-purple-500/10 text-purple-400 border-purple-500/20'],
    'PROPOSE_RESCHEDULE'   => ['Proposed reschedule',      'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'],
    'APPROVE_RESCHEDULE'   => ['Customer approved resched.','bg-green-500/10 text-green-400 border-green-500/20'],
    'REJECT_RESCHEDULE'    => ['Customer declined resched.','bg-red-500/10 text-red-400 border-red-500/20'],
    'AUTO_CANCEL_EXPIRED'  => ['Auto-canceled (expired)',  'bg-red-500/10 text-red-400/60 border-red-500/20'],
    'SET_PIN'              => ['Set PIN',                  'bg-white/5 text-bone/50 border-white/10'],
    'CHANGE_PIN'           => ['Changed PIN',              'bg-white/5 text-bone/50 border-white/10'],
    'CHANGE_PASSWORD'      => ['Changed password',         'bg-white/5 text-bone/50 border-white/10'],
    'CREATE_STAFF'         => ['Created staff account',    'bg-gold/10 text-gold border-gold/20'],
    'RESET_PIN'            => ['Reset PIN (admin)',        'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'],
    'RESET_PASSWORD'       => ['Reset password (admin)',   'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'],
    'DISABLE_STAFF'        => ['Disabled staff',           'bg-red-500/10 text-red-400 border-red-500/20'],
    'ENABLE_STAFF'         => ['Enabled staff',            'bg-green-500/10 text-green-400 border-green-500/20'],
    'DELETE_CUSTOMER'      => ['Removed customer',         'bg-red-500/10 text-red-400 border-red-500/20'],
    'UPDATE_SCHEDULE'      => ['Updated schedule',         'bg-blue-500/10 text-blue-400 border-blue-500/20'],
    'CLEAR_DATA'           => ['Cleared data',             'bg-red-500/10 text-red-400 border-red-500/20'],
    'IMPORT_DATA'          => ['Imported data',            'bg-blue-500/10 text-blue-400 border-blue-500/20'],
    'SIGN_FORM'            => ['Signed form',              'bg-gold/10 text-gold border-gold/20'],
];

$hasFilters = $search || $filterStaff || $filterAction;
?>
<div class="p-5 md:p-8 max-w-6xl">
  <div class="flex items-start justify-between mb-6">
    <div>
      <div class="text-[10px] uppercase tracking-[0.3em] text-gold"><?= e(t('admin.audit.kicker')) ?></div>
      <h1 class="mt-1 text-2xl md:text-3xl font-display"><?= e(t('admin.audit.title')) ?></h1>
      <p class="text-bone/40 text-sm mt-1"><?= count($entries) ?> <?= e(t('admin.audit.entries_shown')) ?></p>
    </div>
  </div>

  <!-- ═══ Filters ═══ -->
  <form method="GET" action="<?= url('/admin/audit') ?>" class="bg-white/[0.02] border border-white/5 rounded-2xl p-5 mb-6">
    <div class="grid sm:grid-cols-2 lg:grid-cols-4 gap-3">
      <!-- Search -->
      <div class="sm:col-span-2 lg:col-span-1">
        <label class="label"><?= e(t('admin.audit.search')) ?></label>
        <div class="relative">
          <svg class="absolute left-3 top-1/2 -translate-y-1/2 text-bone/20 w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
          <input name="q" value="<?= e($search) ?>" placeholder="<?= e(t('admin.audit.search_placeholder')) ?>" class="input pl-9 text-sm">
        </div>
      </div>

      <!-- Staff filter -->
      <div>
        <label class="label"><?= e(t('admin.audit.filter_staff')) ?></label>
        <select name="staff" class="input text-sm">
          <option value=""><?= e(t('admin.audit.all_staff')) ?></option>
          <?php foreach ($staffOptions as $sid => $sname): ?>
            <option value="<?= e($sid) ?>" <?= $filterStaff === $sid ? 'selected' : '' ?>><?= e($sname) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <!-- Action filter -->
      <div>
        <label class="label"><?= e(t('admin.audit.filter_action')) ?></label>
        <select name="action" class="input text-sm">
          <option value=""><?= e(t('admin.audit.all_actions')) ?></option>
          <?php foreach ($actionOptions as $act): ?>
            <option value="<?= e($act) ?>" <?= $filterAction === $act ? 'selected' : '' ?>><?= e($actionLabels[$act][0] ?? $act) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <!-- Apply -->
      <div class="flex items-end gap-2">
        <button class="btn-gold text-xs px-5 py-2.5 w-full"><?= e(t('admin.audit.apply')) ?></button>
      </div>
    </div>
    <?php if ($hasFilters): ?>
      <div class="mt-3 pt-3 border-t border-white/5 flex items-center gap-2">
        <span class="text-xs text-bone/30"><?= e(t('admin.audit.active_filters')) ?>:</span>
        <?php if ($search): ?>
          <span class="text-[10px] px-2 py-0.5 rounded-full bg-gold/10 text-gold border border-gold/20">"<?= e($search) ?>"</span>
        <?php endif; ?>
        <?php if ($filterStaff): ?>
          <span class="text-[10px] px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-400 border border-blue-500/20"><?= e($staffOptions[$filterStaff] ?? $filterStaff) ?></span>
        <?php endif; ?>
        <?php if ($filterAction): ?>
          <span class="text-[10px] px-2 py-0.5 rounded-full bg-purple-500/10 text-purple-400 border border-purple-500/20"><?= e($actionLabels[$filterAction][0] ?? $filterAction) ?></span>
        <?php endif; ?>
        <a href="<?= url('/admin/audit') ?>" class="text-xs text-bone/40 hover:text-bone ml-auto"><?= e(t('admin.audit.clear_filters')) ?></a>
      </div>
    <?php endif; ?>
  </form>

  <!-- ═══ Entries ═══ -->
  <?php if (empty($entries)): ?>
    <div class="bg-white/[0.02] border border-white/5 rounded-2xl p-16 text-center">
      <div class="text-4xl mb-3 opacity-20">📋</div>
      <p class="text-bone/30 text-sm"><?= e($hasFilters ? t('admin.audit.no_results') : t('admin.audit.empty')) ?></p>
    </div>
  <?php else: ?>
    <!-- Desktop table -->
    <div class="hidden md:block bg-white/[0.02] border border-white/5 rounded-2xl overflow-hidden">
      <table class="w-full text-sm">
        <thead class="text-[10px] uppercase tracking-[0.15em] text-bone/30 border-b border-white/5">
          <tr>
            <th class="text-left px-5 py-3 font-medium w-44"><?= e(t('admin.audit.when')) ?></th>
            <th class="text-left px-5 py-3 font-medium w-36"><?= e(t('admin.audit.who')) ?></th>
            <th class="text-left px-5 py-3 font-medium"><?= e(t('admin.audit.action')) ?></th>
            <th class="text-left px-5 py-3 font-medium w-44"><?= e(t('admin.audit.target')) ?></th>
            <th class="text-left px-5 py-3 font-medium w-28">IP</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($entries as $e):
            $u = $userRepo->find($e['staff_id'] ?? '');
            $staffName = $u ? trim(($u['first_name'] ?? '') . ' ' . ($u['last_name'] ?? '')) : ($e['staff_id'] === 'SYSTEM' ? 'System' : ($e['staff_id'] === 'CUSTOMER' ? 'Customer' : '—'));
            $act = $e['action'] ?? '';
            $labelInfo = $actionLabels[$act] ?? [$act, 'bg-white/5 text-bone/50 border-white/10'];
            $when = !empty($e['created_at']) ? new DateTimeImmutable($e['created_at']) : null;
          ?>
            <tr class="border-t border-white/[0.03] hover:bg-white/[0.02] transition-colors">
              <td class="px-5 py-3">
                <?php if ($when): ?>
                  <div class="text-xs text-bone/60"><?= e($when->format('M j, Y')) ?></div>
                  <div class="text-[10px] text-bone/30"><?= e($when->format('g:i:s A')) ?></div>
                <?php else: ?>
                  <span class="text-bone/20">—</span>
                <?php endif; ?>
              </td>
              <td class="px-5 py-3">
                <div class="flex items-center gap-2">
                  <?php if ($u): ?>
                    <div class="w-6 h-6 rounded-full bg-gold/10 border border-gold/20 flex items-center justify-center text-gold text-[9px] font-bold shrink-0">
                      <?= strtoupper(substr($u['first_name'] ?? '?', 0, 1)) ?>
                    </div>
                  <?php endif; ?>
                  <div>
                    <div class="text-xs font-medium"><?= e($staffName) ?></div>
                    <?php if ($u && !empty($u['role'])): ?>
                      <div class="text-[9px] text-bone/30 uppercase tracking-wider"><?= e($u['role']) ?></div>
                    <?php endif; ?>
                  </div>
                </div>
              </td>
              <td class="px-5 py-3">
                <span class="inline-flex px-2.5 py-1 rounded-lg border text-[10px] font-semibold uppercase tracking-wider <?= $labelInfo[1] ?>">
                  <?= e($labelInfo[0]) ?>
                </span>
              </td>
              <td class="px-5 py-3">
                <div class="text-[10px] text-bone/40 uppercase tracking-wider"><?= e($e['target_type'] ?? '') ?></div>
                <div class="font-mono text-[10px] text-bone/25 truncate max-w-[10rem]"><?= e($e['target_id'] ?? '') ?></div>
              </td>
              <td class="px-5 py-3 font-mono text-[10px] text-bone/25"><?= e($e['ip'] ?? '') ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <!-- Mobile cards -->
    <div class="md:hidden space-y-2">
      <?php foreach ($entries as $e):
        $u = $userRepo->find($e['staff_id'] ?? '');
        $staffName = $u ? trim(($u['first_name'] ?? '') . ' ' . ($u['last_name'] ?? '')) : ($e['staff_id'] === 'SYSTEM' ? 'System' : ($e['staff_id'] === 'CUSTOMER' ? 'Customer' : '—'));
        $act = $e['action'] ?? '';
        $labelInfo = $actionLabels[$act] ?? [$act, 'bg-white/5 text-bone/50 border-white/10'];
        $when = !empty($e['created_at']) ? new DateTimeImmutable($e['created_at']) : null;
      ?>
        <div class="bg-white/[0.02] border border-white/5 rounded-xl p-4">
          <div class="flex items-center justify-between gap-3 mb-2">
            <span class="inline-flex px-2 py-0.5 rounded-lg border text-[9px] font-semibold uppercase tracking-wider <?= $labelInfo[1] ?>">
              <?= e($labelInfo[0]) ?>
            </span>
            <span class="text-[10px] text-bone/30"><?= $when ? e($when->format('M j · g:i A')) : '' ?></span>
          </div>
          <div class="flex items-center gap-2">
            <?php if ($u): ?>
              <div class="w-5 h-5 rounded-full bg-gold/10 border border-gold/20 flex items-center justify-center text-gold text-[8px] font-bold shrink-0">
                <?= strtoupper(substr($u['first_name'] ?? '?', 0, 1)) ?>
              </div>
            <?php endif; ?>
            <span class="text-xs font-medium"><?= e($staffName) ?></span>
            <?php if ($u && !empty($u['role'])): ?>
              <span class="text-[9px] text-bone/25 uppercase"><?= e($u['role']) ?></span>
            <?php endif; ?>
          </div>
          <div class="mt-1.5 text-[10px] text-bone/30">
            <?= e($e['target_type'] ?? '') ?>: <span class="font-mono"><?= e(substr((string)($e['target_id'] ?? ''), 0, 12)) ?></span>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>
