<?php
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/audit.php';
require_login();

$pdo = db();
$cid = (int)($_SESSION['company_id'] ?? 0);
ensure_audit_tables($pdo);

$module = trim($_GET['module'] ?? '');

$sql = "
  SELECT l.*, u.name AS user_name, u.email AS user_email
  FROM audit_logs l
  LEFT JOIN users u ON u.id = l.user_id
  WHERE l.company_id = ?
";
$params = [$cid];

if ($module !== '') {
  $sql .= " AND l.module = ?";
  $params[] = $module;
}

$sql .= " ORDER BY l.id DESC LIMIT 1000";
$st = $pdo->prepare($sql);
$st->execute($params);
$rows = $st->fetchAll(PDO::FETCH_ASSOC);

$modules = [
  'auth'     => 'الدخول والخروج',
  'users'    => 'المستخدمون',
  'settings' => 'الإعدادات',
  'backup'   => 'النسخ الاحتياطي',
  'accounts' => 'الحسابات',
  'cash'     => 'الوارد والمنصرف',
  'journal'  => 'القيود',
  'hr'       => 'الموارد البشرية',
  'fleet'    => 'السيارات',
  'hotel'    => 'الفنادق',
  'tourism'  => 'العملاء والحجوزات',
];

$statusClass = static function(string $action, string $description = ''): string {
  $text = mb_strtolower(trim($action . ' ' . $description), 'UTF-8');

  foreach (['delete','removed','remove','cancel','canceled','cancelled','reverse','rollback','حذف','إلغاء','الغاء','عكس'] as $k) {
    if (mb_strpos($text, $k) !== false) return 'danger';
  }
  foreach (['error','failed','failure','invalid','cannot','not found','خطأ','خطا','فشل','تعذر','مرفوض'] as $k) {
    if (mb_strpos($text, $k) !== false) return 'danger';
  }
  foreach (['warning','alert','duplicate','already exists','تحذير','تنبيه','مكرر'] as $k) {
    if (mb_strpos($text, $k) !== false) return 'warning';
  }
  foreach (['update','updated','edit','edited','change','changed','save','saved','restore','restored','upload','uploaded','تعديل','حفظ','استعادة','رفع'] as $k) {
    if (mb_strpos($text, $k) !== false) return 'info';
  }
  foreach (['create','created','new','add','added','insert','inserted','register','registered','إنشاء','انشاء','إضافة','اضافة','فتح'] as $k) {
    if (mb_strpos($text, $k) !== false) return 'primary';
  }
  foreach (['post','posted','approve','approved','confirm','confirmed','success','successful','نجح','تم','ترحيل','اعتماد','تأكيد'] as $k) {
    if (mb_strpos($text, $k) !== false) return 'success';
  }
  return 'secondary';
};

$statusLabel = static function(string $class): string {
  return match($class) {
    'success' => 'نجاح',
    'primary' => 'إنشاء/إضافة',
    'info'    => 'تعديل/حفظ',
    'warning' => 'تنبيه',
    'danger'  => 'حذف/خطأ',
    default   => 'عام',
  };
};

render_layout(
  'سجل العمليات',
  "الرئيسية <span class='mx-1'>/</span> الإعدادات <span class='mx-1'>/</span> سجل العمليات",
  function() use ($rows, $module, $modules, $statusClass, $statusLabel) {
?>
<style>
  .audit-page .toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}
  .audit-page .status-badge{font-size:.78rem;padding:.45rem .7rem;border-radius:999px;font-weight:800}
  .audit-page .action-badge{font-size:.76rem;padding:.42rem .65rem;border-radius:999px}
  .audit-page .desc-cut{max-width:560px;white-space:normal;overflow:visible;text-overflow:unset;word-break:break-word;line-height:1.6}
  .audit-page .table td,.audit-page .table th{vertical-align:middle}.audit-page .table{table-layout:auto}
  .audit-page .audit-meta{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.8rem}
  .audit-page .meta-box{border:1px solid #e9eef5;border-radius:16px;padding:.85rem 1rem;background:#fff}
  .audit-page .meta-box .label{color:#64748b;font-size:.84rem;margin-bottom:.25rem}
  .audit-page .meta-box .value{font-weight:700;word-break:break-word}
  .audit-page .detail-box{border:1px dashed #cbd5e1;border-radius:16px;padding:1rem;background:#f8fafc}
  @media (max-width:767.98px){
    .audit-page .desc-cut{max-width:100%;font-size:.92rem}
    .audit-page .audit-meta{grid-template-columns:1fr}
  }
</style>

<div class="audit-page mt-3">
  <div class="card cardx p-3 p-md-4">
    <div class="toolbar mb-3">
      <div>
        <div class="fw-bold fs-5">سجل العمليات العام</div>
        <div class="small text-secondary mt-1">يعرض آخر 1000 عملية للشركة الحالية مع حالة ملونة وتفاصيل كاملة لكل عملية.</div>
      </div>
      <span class="badge text-bg-dark rounded-pill">العدد: <?= count($rows) ?></span>
    </div>

    <form method="get" class="row g-2 align-items-end mb-3">
      <div class="col-12 col-md-4">
        <label class="form-label">تصفية حسب القسم</label>
        <select class="form-select selectpicker" data-live-search="true" data-size="8" data-width="100%" name="module" id="auditModuleFilter">
          <option value="">الكل</option>
          <?php foreach ($modules as $key => $label): ?>
            <option value="<?= h($key) ?>" <?= $module === $key ? 'selected' : '' ?>><?= h($label) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-12 col-md-auto d-flex align-items-end">
        <div class="small text-secondary">يتم تحديث الجدول مباشرة عند اختيار القسم.</div>
      </div>
    </form>

    <?php if (!$rows): ?>
      <div class="alert alert-light border mb-0">لا توجد عمليات مسجلة حتى الآن.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table table-bordered table-hover align-middle mb-0">
          <thead class="table-light">
            <tr data-module="<?= h((string)$r['module']) ?>">
              <th style="width:70px">#</th>
              <th style="width:120px">القسم</th>
              <th style="width:140px">العملية</th>
              <th style="width:130px">الحالة</th>
              <th style="width:160px">المستخدم</th>
              <th>الوصف</th>
              <th style="width:190px">التاريخ</th>
              <th style="width:110px">التفاصيل</th>
            </tr>
          </thead>
          <tbody id="auditTableBody">
            <?php foreach ($rows as $r):
              $status = $statusClass((string)$r['action'], (string)($r['description'] ?? ''));
              $userLabel = $r['user_name'] ?: ('مستخدم #' . (int)$r['user_id']);
              $detailPayload = [
                'id'          => (int)$r['id'],
                'module'      => (string)$r['module'],
                'action'      => (string)$r['action'],
                'status'      => $statusLabel($status),
                'entity_type' => (string)($r['entity_type'] ?: ($r['table_name'] ?? '')),
                'entity_id'   => (string)($r['entity_id'] ?: ($r['record_id'] ?? '')),
                'user_name'   => (string)$userLabel,
                'user_email'  => (string)($r['user_email'] ?? ''),
                'description' => (string)($r['description'] ?? ''),
                'ip_address'  => (string)($r['ip_address'] ?? ''),
                'page_path'   => (string)($r['page_path'] ?? ($r['request_uri'] ?? '')),
                'request_method' => (string)($r['request_method'] ?? ''),
                'created_at'  => (string)$r['created_at'],
              ];
            ?>
              <tr data-module="<?= h((string)$r['module']) ?>">
                <td><?= (int)$r['id'] ?></td>
                <td><?= h($modules[$r['module']] ?? $r['module']) ?></td>
                <td><span class="badge text-bg-secondary action-badge"><?= h($r['action']) ?></span></td>
                <td><span class="badge text-bg-<?= h($status) ?> status-badge"><?= h($statusLabel($status)) ?></span></td>
                <td><?= h($userLabel) ?></td>
                <td><div class="desc-cut" title="<?= h($r['description'] ?: '-') ?>"><?= h($r['description'] ?: '-') ?></div></td>
                <td><?= h($r['created_at']) ?></td>
                <td>
                  <button
                    type="button"
                    class="btn btn-sm btn-outline-dark js-audit-detail"
                    data-audit='<?= h(json_encode($detailPayload, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)) ?>'>
                    عرض
                  </button>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>

<div class="modal fade modal-erp" id="auditDetailModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">تفاصيل العملية</h5>
        <button type="button" class="btn-close m-0" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="audit-meta mb-3">
          <div class="meta-box"><div class="label">رقم العملية</div><div class="value" id="ad_id">-</div></div>
          <div class="meta-box"><div class="label">القسم</div><div class="value" id="ad_module">-</div></div>
          <div class="meta-box"><div class="label">العملية</div><div class="value" id="ad_action">-</div></div>
          <div class="meta-box"><div class="label">الحالة</div><div class="value" id="ad_status">-</div></div>
          <div class="meta-box"><div class="label">نوع السجل</div><div class="value" id="ad_entity_type">-</div></div>
          <div class="meta-box"><div class="label">رقم السجل</div><div class="value" id="ad_entity_id">-</div></div>
          <div class="meta-box"><div class="label">المستخدم</div><div class="value" id="ad_user_name">-</div></div>
          <div class="meta-box"><div class="label">البريد الإلكتروني</div><div class="value" id="ad_user_email">-</div></div>
          <div class="meta-box"><div class="label">IP</div><div class="value" id="ad_ip_address">-</div></div>
          <div class="meta-box"><div class="label">المسار / الصفحة</div><div class="value" id="ad_page_path">-</div></div>
          <div class="meta-box"><div class="label">طريقة الطلب</div><div class="value" id="ad_request_method">-</div></div>
          <div class="meta-box"><div class="label">التاريخ</div><div class="value" id="ad_created_at">-</div></div>
        </div>

        <div class="detail-box">
          <div class="label mb-2 fw-bold">وصف العملية</div>
          <div class="value" id="ad_description">-</div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إغلاق</button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
  const modalEl = document.getElementById('auditDetailModal');
  if (!modalEl || !window.bootstrap) return;
  const modal = new bootstrap.Modal(modalEl);

  const fill = (id, value) => {
    const el = document.getElementById(id);
    if (el) el.textContent = value && String(value).trim() !== '' ? value : '-';
  };

  document.querySelectorAll('.js-audit-detail').forEach(btn => {
    btn.addEventListener('click', function(){
      let data = {};
      try { data = JSON.parse(this.getAttribute('data-audit') || '{}'); } catch(e) {}

      fill('ad_id', data.id);
      fill('ad_module', data.module);
      fill('ad_action', data.action);
      fill('ad_status', data.status);
      fill('ad_entity_type', data.entity_type);
      fill('ad_entity_id', data.entity_id);
      fill('ad_user_name', data.user_name);
      fill('ad_user_email', data.user_email);
      fill('ad_ip_address', data.ip_address);
      fill('ad_page_path', data.page_path);
      fill('ad_request_method', data.request_method);
      fill('ad_created_at', data.created_at);
      fill('ad_description', data.description);

      modal.show();
    });
  });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function(){
  const filter = document.getElementById('auditModuleFilter');
  const rows = Array.from(document.querySelectorAll('#auditTableBody tr[data-module]'));
  if (!filter || !rows.length) return;

  function applyFilter() {
    const val = (filter.value || '').trim();
    let visible = 0;
    rows.forEach(row => {
      const show = !val || row.getAttribute('data-module') === val;
      row.style.display = show ? '' : 'none';
      if (show) visible++;
    });

    const emptyId = 'audit-empty-filter-row';
    let emptyRow = document.getElementById(emptyId);
    if (visible === 0) {
      if (!emptyRow) {
        emptyRow = document.createElement('tr');
        emptyRow.id = emptyId;
        emptyRow.innerHTML = '<td colspan="8" class="text-center text-secondary py-4">لا توجد نتائج مطابقة للتصفية الحالية.</td>';
        document.getElementById('auditTableBody').appendChild(emptyRow);
      }
    } else if (emptyRow) {
      emptyRow.remove();
    }
  }

  filter.addEventListener('change', applyFilter);
  applyFilter();

  if (window.jQuery && jQuery.fn && jQuery.fn.selectpicker) {
    jQuery(filter).on('changed.bs.select', applyFilter);
  }
});
</script>

<?php
});
?>