<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>سجل التدقيق — Artal CRM</title>
  <link rel="icon" type="image/png" href="/images/icon.png">
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;700;800&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap" rel="stylesheet">
  <style>
    body { font-family: 'Inter', sans-serif; background: #f0f4f8; }
    h1,h2,h3 { font-family: 'Manrope', sans-serif; }
    .material-symbols-outlined { font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24; }
    select, input[type="text"], input[type="date"] {
      background: white; border: 1px solid #e0e3e5; border-radius: 0.75rem;
      padding: 0.5rem 0.75rem; font-size: 0.875rem; width: 100%;
      outline: none; transition: border-color 0.15s;
    }
    select:focus, input:focus { border-color: #1a3c6e; }
    .badge { display: inline-flex; align-items: center; gap: 4px; padding: 3px 10px; border-radius: 999px; font-size: 11px; font-weight: 600; white-space: nowrap; }
  </style>
</head>
<body class="text-[#191c1e]">
<%- include('partials/sidebar', { currentPage: 'audit' }) %>

<div class="lg:mr-64 min-h-screen pt-14 lg:pt-0">
  <!-- Top bar -->
  <header class="bg-white border-b border-[#eceef0] px-4 lg:px-8 py-4 flex items-center justify-between sticky top-14 lg:top-0 z-30">
    <div>
      <h1 class="text-xl font-bold text-[#1a3c6e]">سجل التدقيق</h1>
      <p class="text-xs text-[#43474f] mt-0.5">إجمالي السجلات: <strong><%= total %></strong></p>
    </div>
    <div class="flex items-center gap-2 text-xs text-[#43474f]">
      <span class="material-symbols-outlined text-base text-[#1a3c6e]">verified_user</span>
      <span>جميع العمليات مسجّلة تلقائياً</span>
    </div>
  </header>

  <main class="p-4 lg:p-8 space-y-6">

    <!-- Filter Panel -->
    <form method="GET" action="/admin/audit">
      <div class="bg-white rounded-2xl p-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="font-bold text-[#1a3c6e] text-sm flex items-center gap-2">
            <span class="material-symbols-outlined text-base">filter_list</span>
            الفلترة والبحث
          </h2>
          <a href="/admin/audit" class="text-xs text-[#43474f] hover:underline flex items-center gap-1">
            <span class="material-symbols-outlined text-sm">refresh</span>
            إعادة تعيين
          </a>
        </div>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
          <div>
            <label class="block text-xs font-medium text-[#43474f] mb-1.5">المستخدم</label>
            <select name="user">
              <option value="">جميع المستخدمين</option>
              <% users.forEach(u => { %>
              <option value="<%= u.username %>" <%= filters.user === u.username ? 'selected' : '' %>><%= u.username %></option>
              <% }) %>
            </select>
          </div>
          <div>
            <label class="block text-xs font-medium text-[#43474f] mb-1.5">نوع العملية</label>
            <select name="action">
              <option value="">جميع العمليات</option>
              <optgroup label="الدخول والخروج">
                <option value="login"          <%= filters.action === 'login'          ? 'selected' : '' %>>تسجيل الدخول</option>
                <option value="logout"         <%= filters.action === 'logout'         ? 'selected' : '' %>>تسجيل الخروج</option>
              </optgroup>
              <optgroup label="العملاء">
                <option value="client_create"  <%= filters.action === 'client_create'  ? 'selected' : '' %>>إضافة عميل</option>
                <option value="client_update"  <%= filters.action === 'client_update'  ? 'selected' : '' %>>تعديل عميل</option>
                <option value="client_delete"  <%= filters.action === 'client_delete'  ? 'selected' : '' %>>حذف عميل</option>
                <option value="stage_change"   <%= filters.action === 'stage_change'   ? 'selected' : '' %>>تغيير مرحلة</option>
                <option value="activity_add"   <%= filters.action === 'activity_add'   ? 'selected' : '' %>>إضافة نشاط</option>
                <option value="activity_delete"<%= filters.action === 'activity_delete'? 'selected' : '' %>>حذف نشاط</option>
                <option value="export"         <%= filters.action === 'export'         ? 'selected' : '' %>>تصدير Excel</option>
              </optgroup>
              <optgroup label="المهام">
                <option value="task_done"      <%= filters.action === 'task_done'      ? 'selected' : '' %>>إنجاز مهمة</option>
                <option value="task_delete"    <%= filters.action === 'task_delete'    ? 'selected' : '' %>>حذف مهمة</option>
              </optgroup>
              <optgroup label="المستخدمون">
                <option value="user_create"    <%= filters.action === 'user_create'    ? 'selected' : '' %>>إنشاء مستخدم</option>
                <option value="user_update"    <%= filters.action === 'user_update'    ? 'selected' : '' %>>تعديل مستخدم</option>
                <option value="user_delete"    <%= filters.action === 'user_delete'    ? 'selected' : '' %>>حذف مستخدم</option>
                <option value="password_reset" <%= filters.action === 'password_reset' ? 'selected' : '' %>>إعادة تعيين كلمة مرور</option>
                <option value="password_change"<%= filters.action === 'password_change'? 'selected' : '' %>>تغيير كلمة المرور</option>
              </optgroup>
              <optgroup label="الإعدادات">
                <option value="settings_update"<%= filters.action === 'settings_update'? 'selected' : '' %>>تحديث الإعدادات</option>
              </optgroup>
            </select>
          </div>
          <div>
            <label class="block text-xs font-medium text-[#43474f] mb-1.5">من تاريخ</label>
            <input type="date" name="date_from" value="<%= filters.date_from || '' %>">
          </div>
          <div>
            <label class="block text-xs font-medium text-[#43474f] mb-1.5">إلى تاريخ</label>
            <input type="date" name="date_to" value="<%= filters.date_to || '' %>">
          </div>
        </div>
        <div class="mt-4 flex justify-end">
          <button type="submit"
                  class="bg-[#1a3c6e] text-white text-sm font-medium px-6 py-2.5 rounded-xl hover:bg-[#0f2847] transition-colors flex items-center gap-2">
            <span class="material-symbols-outlined text-base">search</span>
            تطبيق الفلتر
          </button>
        </div>
      </div>
    </form>

    <!-- Logs Table -->
    <div class="bg-white rounded-2xl overflow-hidden shadow-sm">
      <% if (logs.length === 0) { %>
      <div class="py-20 text-center text-[#43474f]">
        <span class="material-symbols-outlined text-5xl text-gray-200 block mb-3">history</span>
        <p class="text-sm">لا توجد سجلات تطابق الفلتر المحدد</p>
      </div>
      <% } else { %>
      <div class="overflow-x-auto">
        <table class="w-full text-sm">
          <thead>
            <tr class="bg-[#f7f8fa] border-b border-[#eceef0] text-xs font-semibold text-[#43474f]">
              <th class="px-5 py-3.5 text-right">#</th>
              <th class="px-5 py-3.5 text-right">المستخدم</th>
              <th class="px-5 py-3.5 text-right">العملية</th>
              <th class="px-5 py-3.5 text-right">الهدف</th>
              <th class="px-5 py-3.5 text-right">التفاصيل</th>
              <th class="px-5 py-3.5 text-right">IP</th>
              <th class="px-5 py-3.5 text-right">التاريخ والوقت</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-[#f0f1f3]">
            <% logs.forEach((log, i) => { %>
            <%
              const offset = (pageNum - 1) * 50;
              const rowNum = offset + i + 1;
              const ACTION_MAP = {
                login:            { label: 'دخول',           bg: '#e8f5e9', color: '#2e7d32' },
                logout:           { label: 'خروج',           bg: '#f3f4f6', color: '#4b5563' },
                client_create:    { label: 'إضافة عميل',     bg: '#e0f2fe', color: '#0277bd' },
                client_update:    { label: 'تعديل عميل',     bg: '#e8f4fd', color: '#0369a1' },
                client_delete:    { label: 'حذف عميل',       bg: '#fce4ec', color: '#c62828' },
                stage_change:     { label: 'تغيير مرحلة',    bg: '#fff8e1', color: '#f57f17' },
                activity_add:     { label: 'نشاط جديد',      bg: '#e8edf5', color: '#1a3c6e' },
                activity_delete:  { label: 'حذف نشاط',       bg: '#fff0f0', color: '#b45309' },
                task_done:        { label: 'إنجاز مهمة',     bg: '#e8f5e9', color: '#1b5e20' },
                task_delete:      { label: 'حذف مهمة',       bg: '#fce4ec', color: '#c62828' },
                export:           { label: 'تصدير Excel',    bg: '#e8f5e9', color: '#1b5e20' },
                user_create:      { label: 'إنشاء مستخدم',   bg: '#e0f7fa', color: '#00695c' },
                user_update:      { label: 'تعديل مستخدم',   bg: '#e8eaf6', color: '#283593' },
                user_delete:      { label: 'حذف مستخدم',     bg: '#fce4ec', color: '#ad1457' },
                password_reset:   { label: 'إعادة تعيين مرور',bg: '#fff3e0', color: '#e65100' },
                password_change:  { label: 'تغيير المرور',   bg: '#fff3e0', color: '#bf360c' },
                settings_update:  { label: 'تحديث الإعدادات',bg: '#e8eaf6', color: '#3949ab' },
              };
              const a = ACTION_MAP[log.action] || { label: log.action, bg: '#f0f0f0', color: '#555' };
            %>
            <tr class="hover:bg-[#f7f8fa] transition-colors">
              <td class="px-5 py-3.5 text-[#8a9099] text-xs"><%= rowNum %></td>
              <td class="px-5 py-3.5">
                <div class="flex items-center gap-2">
                  <div class="w-7 h-7 rounded-full bg-[#e8edf5] flex items-center justify-center flex-shrink-0">
                    <span class="material-symbols-outlined text-[#1a3c6e] text-sm" style="font-variation-settings:'FILL' 1">person</span>
                  </div>
                  <span class="font-medium text-[#1a3c6e]"><%= log.username %></span>
                </div>
              </td>
              <td class="px-5 py-3.5">
                <span class="badge" style="background:<%= a.bg %>; color:<%= a.color %>"><%= a.label %></span>
              </td>
              <td class="px-5 py-3.5">
                <% if (log.target_name) { %>
                  <% if (log.target_type === 'client' && log.target_id) { %>
                    <a href="/admin/clients/<%= log.target_id %>" class="text-[#1a3c6e] hover:underline font-medium"><%= log.target_name %></a>
                  <% } else { %>
                    <span class="font-medium text-[#191c1e]"><%= log.target_name %></span>
                  <% } %>
                <% } else { %>
                  <span class="text-[#8a9099]">—</span>
                <% } %>
              </td>
              <td class="px-5 py-3.5 text-[#43474f] max-w-xs">
                <% if (log.details) { %>
                  <span class="text-xs"><%= log.details %></span>
                <% } else { %><span class="text-[#8a9099]">—</span><% } %>
              </td>
              <td class="px-5 py-3.5">
                <span class="text-xs text-[#8a9099] font-mono"><%= log.ip || '—' %></span>
              </td>
              <td class="px-5 py-3.5 whitespace-nowrap text-xs text-[#43474f]">
                <%= fmtDateTime(log.created_at) %>
              </td>
            </tr>
            <% }) %>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <% if (totalPages > 1) { %>
      <div class="px-6 py-4 border-t border-[#eceef0] flex items-center justify-between">
        <span class="text-xs text-[#43474f]">
          صفحة <strong><%= pageNum %></strong> من <strong><%= totalPages %></strong>
          &nbsp;·&nbsp; <strong><%= total %></strong> سجل
        </span>
        <div class="flex items-center gap-1.5">
          <%
            const cleanFilters = Object.fromEntries(Object.entries(filters).filter(([,v]) => v));
            const qp = new URLSearchParams(cleanFilters);
          %>
          <% if (pageNum > 1) { %>
            <% qp.set('page', pageNum - 1); %>
            <a href="/admin/audit?<%= qp.toString() %>"
               class="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-[#e0e3e5] text-xs hover:bg-[#f0f4f8] transition-colors">
              <span class="material-symbols-outlined text-sm">chevron_right</span>السابقة
            </a>
          <% } %>
          <% for (let p = Math.max(1, pageNum - 2); p <= Math.min(totalPages, pageNum + 2); p++) { %>
            <% qp.set('page', p); %>
            <a href="/admin/audit?<%= qp.toString() %>"
               class="w-8 h-8 rounded-lg text-xs flex items-center justify-center transition-colors
                      <%= p === pageNum ? 'bg-[#1a3c6e] text-white' : 'border border-[#e0e3e5] hover:bg-[#f0f4f8]' %>">
              <%= p %>
            </a>
          <% } %>
          <% if (pageNum < totalPages) { %>
            <% qp.set('page', pageNum + 1); %>
            <a href="/admin/audit?<%= qp.toString() %>"
               class="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-[#e0e3e5] text-xs hover:bg-[#f0f4f8] transition-colors">
              التالية<span class="material-symbols-outlined text-sm">chevron_left</span>
            </a>
          <% } %>
        </div>
      </div>
      <% } %>
      <% } %>
    </div>

  </main>
</div>
</body>
</html>
