File size: 9,072 Bytes
b1a4165
 
8ecf0f5
b1a4165
 
 
 
 
 
bc41fa6
c4b33ef
8ecf0f5
 
8db9a13
b1a4165
 
c4b33ef
b1a4165
 
 
 
8ecf0f5
b1a4165
 
 
bc41fa6
b1a4165
 
8ecf0f5
b1a4165
 
 
 
 
 
8ecf0f5
 
b1a4165
 
 
 
 
 
 
8ecf0f5
b1a4165
 
 
 
 
 
 
 
 
8ecf0f5
 
b1a4165
 
 
bc41fa6
b1a4165
8ecf0f5
b1a4165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ecf0f5
b1a4165
8ecf0f5
 
b1a4165
 
 
 
 
 
 
735085e
b1a4165
8ecf0f5
b1a4165
 
 
 
 
 
8ecf0f5
b1a4165
 
 
 
 
 
 
 
 
 
 
 
8ecf0f5
b1a4165
8ecf0f5
 
 
 
 
b1a4165
 
 
 
 
 
 
 
 
 
 
 
 
 
8ecf0f5
b1a4165
 
 
 
 
 
 
8ecf0f5
 
b1a4165
 
 
bc41fa6
b1a4165
 
c4b33ef
 
b1a4165
 
8ecf0f5
 
 
 
b1a4165
 
 
 
8ecf0f5
c4b33ef
cd250b5
 
b1a4165
34b0899
8ecf0f5
b1a4165
 
34b0899
b1a4165
 
34b0899
b1a4165
 
 
 
 
 
34b0899
c4b33ef
735085e
7eeb134
ac25ba9
b1a4165
 
 
 
 
 
8ecf0f5
b1a4165
 
 
 
 
 
 
 
 
 
bc41fa6
b1a4165
 
 
 
d53ab3d
b1a4165
 
 
 
 
34b0899
8ecf0f5
 
 
 
 
b1a4165
 
 
bc41fa6
b1a4165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ecf0f5
b1a4165
 
 
 
 
 
 
 
 
8ecf0f5
b1a4165
 
 
 
 
 
 
 
bc41fa6
b1a4165
 
 
8ecf0f5
b1a4165
 
bc41fa6
8ecf0f5
b1a4165
 
 
 
 
 
 
 
 
 
 
 
8ecf0f5
b1a4165
8ecf0f5
 
 
b1a4165
 
 
bc41fa6
8ecf0f5
b1a4165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ecf0f5
 
b1a4165
 
 
 
 
8ecf0f5
b1a4165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e5eb20
 
5d692ef
3cd334b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// عناصر الواجهة
const searchBox = document.getElementById("searchBox");
const clearSearch = document.getElementById("clearSearch");
const pageSizeEl = document.getElementById("pageSize");
const themeBtn = document.getElementById("themeToggle");
const tableBody = document.getElementById("tableBody");
const pagination = document.getElementById("pagination");
const counter = document.getElementById("counter");
const loading = document.getElementById("loading");

let data = [];
let filtered = [];
let currentPage = 1;

const DEFAULT_PAGE_SIZE = 10;
let rowsPerPage = DEFAULT_PAGE_SIZE;

// ضبط قيمة عدد الصفوف الافتراضي إن وُجد العنصر
if (pageSizeEl) {
  pageSizeEl.value = String(DEFAULT_PAGE_SIZE);
}

/* ========================
   دوال مساعدة للبحث بالعربية
   ======================== */

// توحيد الحروف العربية لتسهيل البحث
function normalizeArabic(str = "") {
  return str
    .replace(/[\u064B-\u0652]/g, "") // إزالة التشكيل
    .replace(/[أإآا]/g, "ا")
    .replace(/ى/g, "ي")
    .replace(/ؤ/g, "و")
    .replace(/ئ/g, "ي")
    .replace(/ة/g, "ه")
    .toLowerCase();
}

// التحقق إن كان النص يحتوي على عبارة البحث
function matches(text, query) {
  if (!query) return true;
  return normalizeArabic(String(text ?? "")).includes(
    normalizeArabic(query)
  );
}

// تمييز كلمة البحث داخل النص
function highlight(text, query) {
  if (!query) return String(text ?? "");
  const safe = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return String(text ?? "").replace(
    new RegExp(safe, "gi"),
    (m) => `<mark class="hl">${m}</mark>`
  );
}

/* ========================
   الترقيم (Pagination)
   ======================== */

function renderPagination() {
  pagination.innerHTML = "";

  const totalRows = filtered.length;
  const totalPages = Math.ceil(totalRows / rowsPerPage);

  if (totalPages <= 1) return;

  const makeBtn = (label, page, options = {}) => {
    const btn = document.createElement("button");
    btn.textContent = label;
    btn.className = "page-btn" + (options.ghost ? " ghost" : "");
    if (options.disabled) btn.disabled = true;
    btn.addEventListener("click", () => {
      currentPage = page;
      updateView();
      window.scrollTo({ top: 0, behavior: "smooth" });
    });
    return btn;
  };

  // السابق
  pagination.appendChild(
    makeBtn("‹", Math.max(1, currentPage - 1), {
      ghost: true,
      disabled: currentPage === 1,
    })
  );

  // منطق إظهار أرقام الصفحات
  const windowSize = 5;
  let start = Math.max(1, currentPage - Math.floor(windowSize / 2));
  let end = Math.min(totalPages, start + windowSize - 1);

  if (end - start + 1 < windowSize) {
    start = Math.max(1, end - windowSize + 1);
  }

  if (start > 1) {
    pagination.appendChild(
      makeBtn("1", 1, { ghost: currentPage !== 1 })
    );
  }

  if (start > 2) {
    const dots = document.createElement("span");
    dots.className = "dots";
    dots.textContent = "...";
    pagination.appendChild(dots);
  }

  for (let p = start; p <= end; p++) {
    const btn = makeBtn(String(p), p);
    if (p === currentPage) btn.classList.add("active");
    pagination.appendChild(btn);
  }

  if (end < totalPages - 1) {
    const dots = document.createElement("span");
    dots.className = "dots";
    dots.textContent = "...";
    pagination.appendChild(dots);
  }

  if (end < totalPages) {
    pagination.appendChild(
      makeBtn(String(totalPages), totalPages, {
        ghost: currentPage !== totalPages,
      })
    );
  }

  // التالي
  pagination.appendChild(
    makeBtn("›", Math.min(totalPages, currentPage + 1), {
      ghost: true,
      disabled: currentPage === totalPages,
    })
  );
}

/* ========================
   رسم الجدول (3 أعمدة)
   ======================== */

function renderTable() {
  const query = searchBox ? searchBox.value.trim() : "";
  tableBody.innerHTML = "";

  const startIndex = (currentPage - 1) * rowsPerPage;
  const pageItems = filtered.slice(startIndex, startIndex + rowsPerPage);

  if (pageItems.length === 0) {
    const tr = document.createElement("tr");
    const td = document.createElement("td");
    td.colSpan = 3;
    td.className = "no-results";
    td.textContent = "لا توجد نتائج مطابقة لبحثك.";
    tr.appendChild(td);
    tableBody.appendChild(tr);
    return;
  }

  pageItems.forEach((item) => {
    const tr = document.createElement("tr");

    const nameTd = document.createElement("td");
    nameTd.innerHTML = highlight(item.name, query);

    const qtyTd = document.createElement("td");
    qtyTd.innerHTML = highlight(item.quantity, query);

    const unitTd = document.createElement("td");
    unitTd.innerHTML = highlight(item.unit, query);

    tr.appendChild(nameTd);
    tr.appendChild(qtyTd);
    tr.appendChild(unitTd);

    tableBody.appendChild(tr);
  });
}

/* ========================
   تحديث العرض (فلترة + عداد)
   ======================== */

function updateView() {
  const query = searchBox ? searchBox.value.trim() : "";

  filtered = data.filter((item) => {
    return (
      matches(item.code, query) ||
      matches(item.name, query) ||
      matches(item.quantity, query) ||
      matches(item.unit, query)
    );
  });

  if (!counter) return;

  if (!query) {
    counter.textContent = `إجمالي البنود: ${data.length.toLocaleString()}`;
  } else if (filtered.length) {
    counter.textContent = `✅ عدد النتائج: ${filtered.length.toLocaleString()}`;
  } else {
    counter.textContent = "لا توجد نتائج مطابقة";
  }

  if (loading) {
    loading.style.display = "none";
  }

  renderTable();
  renderPagination();
}

/* ========================
   أدوات مساعدة
   ======================== */

function debounce(fn, delay = 220) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

/* ========================
   ربط الأحداث
   ======================== */

// البحث الفوري
if (searchBox) {
  searchBox.addEventListener(
    "input",
    debounce(() => {
      currentPage = 1;
      updateView();
    })
  );
}

// زر مسح البحث
if (clearSearch) {
  clearSearch.addEventListener("click", () => {
    searchBox.value = "";
    searchBox.focus();
    currentPage = 1;
    updateView();
  });
}

// تغيير عدد الصفوف
if (pageSizeEl) {
  pageSizeEl.addEventListener("change", () => {
    const val = parseInt(pageSizeEl.value, 10);
    rowsPerPage = !isNaN(val) && val > 0 ? val : DEFAULT_PAGE_SIZE;
    currentPage = 1;
    updateView();
  });
}

// اختصار / للتركيز على البحث
document.addEventListener("keydown", (e) => {
  if (e.key === "/") {
    if (document.activeElement === searchBox) return;
    e.preventDefault();
    if (searchBox) searchBox.focus();
  }
});

/* ========================
   الثيم (فاتح / ليلي)
   ======================== */

(function initTheme() {
  if (!themeBtn) return;

  const saved = localStorage.getItem("theme") || "light";
  const root = document.documentElement;

  if (saved === "dark") {
    root.classList.add("dark");
    themeBtn.textContent = "☀️ فاتح";
  } else {
    root.classList.remove("dark");
    themeBtn.textContent = "ليلي";
  }

  themeBtn.addEventListener("click", () => {
    const isDark = root.classList.toggle("dark");
    localStorage.setItem("theme", isDark ? "dark" : "light");
    themeBtn.textContent = isDark ? "☀️ فاتح" : "ليلي";
  });
})();

/* ========================
   تحميل data.json
   ======================== */

fetch("data.json", { cache: "no-cache" })
  .then((res) => res.json())
  .then((json) => {
    // توحيد الحقول + دعم أي تسميات قديمة
    data = (Array.isArray(json) ? json : []).map((row) => ({
      code:
        row.code ??
        row.Code ??
        row["رمز البند"] ??
        "",
      name:
        row.name ??
        row["اسم البند"] ??
        "",
      quantity:
        row.quantity ??
        row["الكمية المطلوبة"] ??
        "",
      unit:
        row.unit ??
        row["وحدة البند"] ??
        "",
    }));

    currentPage = 1;
    updateView();
  })
  .catch((err) => {
    console.error("تعذر تحميل data.json:", err);
    if (loading) {
      loading.textContent = "تعذر تحميل البيانات ❌";
    }
  });

/* ========================
   تأثير بسيط لحالة التمرير
   ======================== */

(function attachScrollHint() {
  const wrap = document.querySelector(".table-wrap");
  if (!wrap) return;

  let timer;
  wrap.addEventListener("scroll", () => {
    wrap.classList.add("scrolling");
    clearTimeout(timer);
    timer = setTimeout(() => {
      wrap.classList.remove("scrolling");
    }, 200);
  });
})();