<?php
require __DIR__ . '/_common.php';
require_perm('view_audit');

$q = trim($_GET['q'] ?? '');
$entity = trim($_GET['entity_type'] ?? '');
$user_id = intval($_GET['user_id'] ?? 0);
$from = trim($_GET['from'] ?? '');
$to = trim($_GET['to'] ?? '');

$where = [];
$params = [];

if ($q !== '') {
  $where[] = "(action LIKE ? OR entity_type LIKE ? OR old_data LIKE ? OR new_data LIKE ?)";
  $params[] = "%$q%"; $params[]="%$q%"; $params[]="%$q%"; $params[]="%$q%";
}
if ($entity !== '') {
  $where[] = "entity_type = ?";
  $params[] = $entity;
}
if ($user_id > 0) {
  $where[] = "user_id = ?";
  $params[] = $user_id;
}
if ($from !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/',$from)) {
  $where[] = "DATE(created_at) >= ?";
  $params[] = $from;
}
if ($to !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/',$to)) {
  $where[] = "DATE(created_at) <= ?";
  $params[] = $to;
}

$whereSql = $where ? ("WHERE " . implode(" AND ", $where)) : "";
$rows = db_all("SELECT al.*, u.name user_name, u.email user_email
               FROM audit_logs al
               LEFT JOIN users u ON u.id = al.user_id
               $whereSql
               ORDER BY al.id DESC
               LIMIT 300", $params);

$entities = db_all("SELECT DISTINCT entity_type FROM audit_logs ORDER BY entity_type");
$users = db_all("SELECT id,name,role FROM users ORDER BY name");
?>

<h1>سجل التدقيق</h1>
<div class="small muted">يُسجل كل التغييرات المهمة (إنشاء/تعديل/حذف/تغيير صلاحيات...).</div>

<hr>

<form class="actions" method="get" action="<?= e(url('/index.php')) ?>">
  <input type="hidden" name="page" value="audit">
  <input class="input" style="max-width:240px" name="q" placeholder="بحث..." value="<?= e($q) ?>">
  <select class="input" name="entity_type" style="max-width:200px">
    <option value="">كل الأنواع</option>
    <?php foreach ($entities as $e1): ?>
      <?php $t = (string)$e1['entity_type']; ?>
      <option value="<?= e($t) ?>" <?= $entity===$t?'selected':'' ?>><?= e($t) ?></option>
    <?php endforeach; ?>
  </select>
  <select class="input" name="user_id" style="max-width:240px">
    <option value="0">كل المستخدمين</option>
    <?php foreach ($users as $u): ?>
      <option value="<?= e((string)$u['id']) ?>" <?= $user_id==intval($u['id'])?'selected':'' ?>>
        <?= e($u['name']) ?> (<?= e($u['role']) ?>)
      </option>
    <?php endforeach; ?>
  </select>
  <input class="input" style="max-width:140px" type="date" name="from" value="<?= e($from) ?>">
  <input class="input" style="max-width:140px" type="date" name="to" value="<?= e($to) ?>">
  <button class="btn primary">تطبيق</button>
  <a class="btn" href="<?= e(url('/index.php?page=audit')) ?>">إعادة ضبط</a>
</form>

<hr>

<div style="overflow:auto">
  <table class="table">
    <thead>
      <tr>
        <th>#</th>
        <th>التاريخ</th>
        <th>المستخدم</th>
        <th>الحدث</th>
        <th>الكيان</th>
        <th>قبل/بعد</th>
        <th>IP</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($rows as $r): ?>
        <tr>
          <td><?= e((string)$r['id']) ?></td>
          <td class="small"><?= e((string)$r['created_at']) ?></td>
          <td class="small">
            <?= e((string)($r['user_name'] ?? '-')) ?><br>
            <span class="muted"><?= e((string)($r['user_email'] ?? '')) ?></span>
          </td>
          <td><?= e((string)$r['action']) ?></td>
          <td class="small"><?= e((string)$r['entity_type']) ?><?= $r['entity_id'] ? ' #'.e((string)$r['entity_id']) : '' ?></td>
          <td style="min-width:280px">
            <details class="json">
              <summary>عرض التفاصيل</summary>
              <div class="small muted">Old</div>
              <pre class="json"><?= e((string)($r['old_data'] ?? '')) ?></pre>
              <div class="small muted">New</div>
              <pre class="json"><?= e((string)($r['new_data'] ?? '')) ?></pre>
            </details>
          </td>
          <td class="small"><?= e((string)($r['ip'] ?? '-')) ?></td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$rows): ?>
        <tr><td colspan="7" class="small">لا توجد سجلات.</td></tr>
      <?php endif; ?>
    </tbody>
  </table>
</div>
