<?php
// ============================================================
// modules/admin/audit.php — سجل التدقيق
// ============================================================
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/rbac.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/layout.php';
require_once __DIR__ . '/../../includes/sidebar_helper.php';

requireLogin(); requireRole(ROLE_ADMIN);
$GLOBALS['BASE_URL_CSS'] = BASE_URL . '/public/assets/css/main.css';
$user = currentUser(); $pdo = db();

// ── الفلاتر ──────────────────────────────────────────────────
$fUser   = $_GET['user']    ?? '';
$fAction = trim($_GET['action']  ?? '');
$fEntity = $_GET['entity']  ?? '';
$fFrom   = $_GET['from']    ?? '';
$fTo     = $_GET['to']      ?? '';
$fSearch = trim($_GET['q']  ?? '');
$page    = max(1, (int)($_GET['page'] ?? 1));
$perPage = 30;

$where = []; $params = [];
if ($fUser !== '')   { $where[] = "al.user_id = ?";    $params[] = (int)$fUser; }
if ($fAction !== '') { $where[] = "al.action LIKE ?";  $params[] = "%$fAction%"; }
if ($fEntity !== '') { $where[] = "al.entity_type = ?";$params[] = $fEntity; }
if ($fFrom)          { $where[] = "DATE(al.created_at) >= ?"; $params[] = $fFrom; }
if ($fTo)            { $where[] = "DATE(al.created_at) <= ?"; $params[] = $fTo; }
if ($fSearch !== '') { $where[] = "(al.description LIKE ? OR al.action LIKE ? OR al.ip_address LIKE ?)";
    $p = "%$fSearch%"; $params[] = $p; $params[] = $p; $params[] = $p; }
$whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// ── إحصائيات سريعة ───────────────────────────────────────────
$total       = (int)$pdo->query("SELECT COUNT(*) FROM audit_log")->fetchColumn();
$today       = (int)$pdo->query("SELECT COUNT(*) FROM audit_log WHERE DATE(created_at)=CURDATE()")->fetchColumn();
$last7Days   = (int)$pdo->query("SELECT COUNT(*) FROM audit_log WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetchColumn();
$activeUsers = (int)$pdo->query("SELECT COUNT(DISTINCT user_id) FROM audit_log WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetchColumn();

// ── العد الإجمالي للنتائج المفلترة (لصفحات الترقيم) ─────────
$countSql = "SELECT COUNT(*) FROM audit_log al $whereSQL";
$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);
$filteredTotal = (int)$countStmt->fetchColumn();
$totalPages    = max(1, (int)ceil($filteredTotal / $perPage));
if ($page > $totalPages) $page = $totalPages;
$offset = ($page - 1) * $perPage;

// ── السجلات المفلترة ─────────────────────────────────────────
$sql = "SELECT al.*, u.full_name, u.role
        FROM audit_log al
        LEFT JOIN users u ON al.user_id = u.id
        $whereSQL
        ORDER BY al.created_at DESC, al.id DESC
        LIMIT $perPage OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$logs = $stmt->fetchAll();

// ── قوائم الفلترة ────────────────────────────────────────────
$allUsers    = $pdo->query("SELECT id, full_name, role FROM users ORDER BY full_name")->fetchAll();
$allEntities = $pdo->query("SELECT DISTINCT entity_type FROM audit_log ORDER BY entity_type")->fetchAll(PDO::FETCH_COLUMN);

// ── خرائط الترجمة ────────────────────────────────────────────
$entityLabels = [
    'users'       => 'المستخدمون',
    'cases'       => 'القضايا',
    'sessions'    => 'الجلسات',
    'judgments'   => 'الأحكام',
    'appeals'     => 'الطعون',
    'documents'   => 'الوثائق',
    'lawyer_profiles' => 'ملفات المحامين',
    'courts'      => 'المحاكم',
];
$actionColor = function($action) {
    if (preg_match('/(create|add|register)/i', $action)) return 'success';
    if (preg_match('/(update|edit|modify|approve)/i', $action)) return 'info';
    if (preg_match('/(delete|reject|cancel)/i', $action)) return 'danger';
    if (preg_match('/(login|logout|access)/i', $action)) return 'navy';
    return 'secondary';
};

$notifCount = getUnreadNotifCount($user['id']);
renderHead('سجل التدقيق');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('audit','admin'); ?></div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<div class="main-wrap">
<?php renderTopbar('سجل التدقيق', $notifCount); ?>
<div class="page-content">

  <!-- KPI cards -->
  <div class="row g-3 mb-4">
    <div class="col-6 col-xl-3">
      <div class="stat-card"><div class="stat-icon navy"><i class="bi bi-clipboard-data"></i></div>
        <div class="stat-body"><div class="stat-value"><?= number_format($total) ?></div>
        <div class="stat-label">إجمالي الإجراءات المسجَّلة</div></div></div>
    </div>
    <div class="col-6 col-xl-3">
      <div class="stat-card"><div class="stat-icon gold"><i class="bi bi-calendar-day"></i></div>
        <div class="stat-body"><div class="stat-value"><?= number_format($today) ?></div>
        <div class="stat-label">إجراءات اليوم</div></div></div>
    </div>
    <div class="col-6 col-xl-3">
      <div class="stat-card"><div class="stat-icon green"><i class="bi bi-graph-up"></i></div>
        <div class="stat-body"><div class="stat-value"><?= number_format($last7Days) ?></div>
        <div class="stat-label">آخر 7 أيام</div></div></div>
    </div>
    <div class="col-6 col-xl-3">
      <div class="stat-card"><div class="stat-icon red"><i class="bi bi-people"></i></div>
        <div class="stat-body"><div class="stat-value"><?= number_format($activeUsers) ?></div>
        <div class="stat-label">مستخدمون نشطون (7 أيام)</div></div></div>
    </div>
  </div>

  <!-- Filters -->
  <div class="panel mb-3">
    <div class="panel-body">
      <form method="GET" class="row g-2">
        <div class="col-md-3">
          <label class="form-label" style="font-size:12px">المستخدم</label>
          <select name="user" class="form-select form-select-sm">
            <option value="">— الكل —</option>
            <?php foreach ($allUsers as $u):
              $roleLbl = ['admin'=>'مدير','clerk'=>'أمين ضبط','lawyer'=>'محامٍ'][$u['role']] ?? $u['role']; ?>
              <option value="<?= $u['id'] ?>" <?= (string)$fUser === (string)$u['id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($u['full_name']) ?> (<?= $roleLbl ?>)
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label" style="font-size:12px">الكيان</label>
          <select name="entity" class="form-select form-select-sm">
            <option value="">— الكل —</option>
            <?php foreach ($allEntities as $e): ?>
              <option value="<?= htmlspecialchars($e) ?>" <?= $fEntity === $e ? 'selected' : '' ?>>
                <?= $entityLabels[$e] ?? htmlspecialchars($e) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label" style="font-size:12px">نوع الإجراء</label>
          <input type="text" name="action" class="form-control form-control-sm"
                 value="<?= htmlspecialchars($fAction) ?>" placeholder="create, update, ...">
        </div>
        <div class="col-md-2">
          <label class="form-label" style="font-size:12px">من تاريخ</label>
          <input type="date" name="from" class="form-control form-control-sm" value="<?= htmlspecialchars($fFrom) ?>">
        </div>
        <div class="col-md-2">
          <label class="form-label" style="font-size:12px">إلى تاريخ</label>
          <input type="date" name="to" class="form-control form-control-sm" value="<?= htmlspecialchars($fTo) ?>">
        </div>
        <div class="col-md-1 d-flex align-items-end">
          <button class="btn btn-sm btn-gold w-100"><i class="bi bi-search"></i></button>
        </div>
        <div class="col-12 mt-2">
          <div class="input-group input-group-sm">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" name="q" class="form-control form-control-sm"
                   value="<?= htmlspecialchars($fSearch) ?>"
                   placeholder="بحث في الوصف، الإجراء، عنوان IP...">
            <?php if ($fSearch || $fUser || $fAction || $fEntity || $fFrom || $fTo): ?>
            <a href="audit.php" class="btn btn-outline-secondary btn-sm"><i class="bi bi-x"></i> مسح الفلاتر</a>
            <?php endif; ?>
          </div>
        </div>
      </form>
    </div>
  </div>

  <!-- Results -->
  <div class="panel">
    <div class="panel-header">
      <div class="panel-title">
        <i class="bi bi-shield-check"></i>
        النتائج
        <span class="text-muted" style="font-weight:normal;font-size:13px">
          (<?= number_format($filteredTotal) ?> إجراء<?= $whereSQL ? ' مطابق' : '' ?>)
        </span>
      </div>
      <span class="badge bg-secondary">صفحة <?= $page ?> / <?= $totalPages ?></span>
    </div>

    <?php if (empty($logs)): ?>
      <div class="empty-state py-5 text-center">
        <i class="bi bi-search" style="font-size:48px;color:var(--text-muted)"></i>
        <h5 class="mt-3">لا توجد سجلات مطابقة</h5>
        <p class="text-muted">جرّب تعديل الفلاتر أو مسحها</p>
      </div>
    <?php else: ?>
    <div class="table-responsive">
      <table class="table">
        <thead><tr>
          <th>التاريخ والوقت</th>
          <th>المستخدم</th>
          <th>الإجراء</th>
          <th>الكيان</th>
          <th>الوصف</th>
          <th>عنوان IP</th>
        </tr></thead>
        <tbody>
        <?php foreach ($logs as $log):
          $roleLbl = ['admin'=>'مدير','clerk'=>'أمين ضبط','lawyer'=>'محامٍ'][$log['role'] ?? ''] ?? '—';
          $actCls  = $actionColor($log['action']);
          $entLbl  = $entityLabels[$log['entity_type']] ?? $log['entity_type'];
        ?>
        <tr>
          <td style="white-space:nowrap;font-size:12px">
            <div style="font-weight:600"><?= date('Y/m/d', strtotime($log['created_at'])) ?></div>
            <div style="color:var(--text-muted)"><?= date('H:i:s', strtotime($log['created_at'])) ?></div>
          </td>
          <td style="font-size:13px">
            <?php if ($log['full_name']): ?>
              <div style="font-weight:600"><?= htmlspecialchars($log['full_name']) ?></div>
              <div style="font-size:11px;color:var(--text-muted)"><?= $roleLbl ?></div>
            <?php else: ?>
              <span class="text-muted">نظام / مستخدم محذوف</span>
            <?php endif; ?>
          </td>
          <td><span class="badge bg-<?= $actCls ?>" style="font-size:11px"><?= htmlspecialchars($log['action']) ?></span></td>
          <td style="font-size:13px">
            <?= htmlspecialchars($entLbl) ?>
            <?php if ($log['entity_id']): ?>
              <span class="text-muted" style="font-size:11px">#<?= $log['entity_id'] ?></span>
            <?php endif; ?>
          </td>
          <td style="max-width:280px;font-size:13px"><?= htmlspecialchars($log['description'] ?? '—') ?></td>
          <td style="font-family:monospace;font-size:12px;color:var(--text-muted)"><?= htmlspecialchars($log['ip_address'] ?? '—') ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1):
      $qs = $_GET; unset($qs['page']);
      $base = '?' . http_build_query($qs);
      $sep = $qs ? '&' : '';
      $startP = max(1, $page - 3);
      $endP   = min($totalPages, $page + 3);
    ?>
    <div class="d-flex justify-content-center align-items-center gap-2 py-3 flex-wrap">
      <?php if ($page > 1): ?>
        <a href="<?= $base . $sep ?>page=1" class="btn btn-sm btn-outline-secondary">&laquo;</a>
        <a href="<?= $base . $sep ?>page=<?= $page-1 ?>" class="btn btn-sm btn-outline-secondary">&lsaquo;</a>
      <?php endif; ?>
      <?php for ($i = $startP; $i <= $endP; $i++): ?>
        <a href="<?= $base . $sep ?>page=<?= $i ?>"
           class="btn btn-sm <?= $i === $page ? 'btn-gold' : 'btn-outline-secondary' ?>">
          <?= $i ?>
        </a>
      <?php endfor; ?>
      <?php if ($page < $totalPages): ?>
        <a href="<?= $base . $sep ?>page=<?= $page+1 ?>" class="btn btn-sm btn-outline-secondary">&rsaquo;</a>
        <a href="<?= $base . $sep ?>page=<?= $totalPages ?>" class="btn btn-sm btn-outline-secondary">&raquo;</a>
      <?php endif; ?>
    </div>
    <?php endif; ?>
    <?php endif; ?>
  </div>

</div></div>
<?php renderFoot(); ?>
