File size: 14,901 Bytes
4bea261
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
---
import AdminLayout from '../../layouts/AdminLayout.astro';
import { getServers } from '../../lib/localDb.js';

const servers = await getServers();
---

<AdminLayout title="Quản lý Server">
  <div class="mb-12 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
    <div>
      <h1 class="text-4xl font-black tracking-tighter text-white">Quản lý Server</h1>
      <p class="mt-2 text-gray-500">Xem, tạo mới và đồng bộ hóa các máy chủ phát phim của hệ thống.</p>
    </div>
    <div class="flex flex-wrap gap-3">
       <button id="sync-servers-btn" class="flex items-center gap-2 rounded-2xl bg-emerald-500/10 hover:bg-emerald-500 text-emerald-400 hover:text-white border border-emerald-500/20 px-6 py-3.5 text-xs font-black uppercase tracking-widest transition-all active:scale-95 cursor-pointer">
          <i class="fas fa-sync-alt"></i>
          Đồng bộ từ Phim
       </button>
       <button id="create-server-btn" class="flex items-center gap-2 rounded-2xl bg-primary px-6 py-3.5 text-xs font-black uppercase tracking-widest text-dark hover:scale-105 transition-all shadow-[0_0_20px_var(--primary)] cursor-pointer">
          <i class="fas fa-plus"></i>
          Thêm Server mới
       </button>
    </div>
  </div>

  <!-- Bulk Action Bar -->
  <div id="bulk-bar" class="hidden glass rounded-3xl p-6 border border-primary/20 mb-8 items-center justify-between">
    <div class="flex items-center gap-3">
      <span class="text-xs font-black uppercase tracking-widest text-primary"><i class="fas fa-check-square"></i> Đã chọn <span id="selected-count">0</span> máy chủ</span>
    </div>
    <div class="flex gap-2">
      <button id="bulk-delete-btn" class="flex items-center gap-2 rounded-xl bg-red-500/10 hover:bg-red-500 text-red-400 hover:text-white border border-red-500/20 px-4 py-2.5 text-xs font-black uppercase tracking-widest transition-all active:scale-95 cursor-pointer">
        <i class="fas fa-trash"></i> Xóa hàng loạt
      </button>
    </div>
  </div>

  <div class="glass rounded-[40px] p-8 md:p-10 border border-white/5 space-y-6">
     <!-- Filter section -->
     <div class="flex items-center justify-between border-b border-white/5 pb-6">
        <div class="relative w-full max-w-md">
           <i class="fas fa-search absolute left-5 top-1/2 -translate-y-1/2 text-gray-500 text-sm"></i>
           <input type="text" id="search-input" placeholder="Tìm kiếm tên server..." class="w-full bg-[#12141d] border border-white/5 rounded-2xl pl-12 pr-5 py-3.5 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
        </div>
     </div>

     <div class="overflow-x-auto">
        <table class="w-full text-left">
           <thead>
              <tr class="border-b border-white/5">
                 <th class="pb-6 w-12">
                    <label class="relative flex items-center justify-center cursor-pointer">
                       <input type="checkbox" id="chk-all" class="peer sr-only" />
                       <div class="h-5 w-5 rounded-lg border border-white/10 bg-[#12141d] flex items-center justify-center transition-all peer-checked:bg-primary peer-checked:border-primary">
                          <i class="fas fa-check text-[10px] text-dark opacity-0 peer-checked:opacity-100 transition-opacity"></i>
                       </div>
                    </label>
                 </th>
                 <th class="pb-6 text-[10px] font-black uppercase tracking-widest text-gray-500">Tên Server</th>
                 <th class="pb-6 text-right text-[10px] font-black uppercase tracking-widest text-gray-500">Thao tác</th>
              </tr>
           </thead>
           <tbody id="table-body" class="divide-y divide-white/5">
              <!-- Rendered via Javascript -->
           </tbody>
        </table>
     </div>
  </div>
</AdminLayout>

<script is:inline define:vars={{ initialServers: servers }}>
  let servers = initialServers || [];
  let searchQuery = '';

  function renderTable() {
    const tbody = document.getElementById('table-body');
    if (!tbody) return;

    const filtered = servers.filter(s => s.name.toLowerCase().includes(searchQuery.toLowerCase()));

    if (filtered.length === 0) {
      tbody.innerHTML = `
        <tr>
          <td colspan="3" class="py-12 text-center text-gray-500 text-sm">
            <i class="fas fa-server text-3xl mb-3 block opacity-20"></i>
            Không tìm thấy server nào
          </td>
        </tr>
      `;
      return;
    }

    tbody.innerHTML = filtered.map(s => `
      <tr class="hover:bg-white/[0.01] transition-colors group">
         <td class="py-5">
            <label class="relative flex items-center justify-center cursor-pointer">
               <input type="checkbox" class="chk-item peer sr-only" data-name="${s.name}" />
               <div class="h-5 w-5 rounded-lg border border-white/10 bg-[#12141d] flex items-center justify-center transition-all peer-checked:bg-primary peer-checked:border-primary">
                  <i class="fas fa-check text-[10px] text-dark opacity-0 peer-checked:opacity-100 transition-opacity"></i>
               </div>
            </label>
         </td>
         <td class="py-5 text-sm font-bold text-white">${s.name}</td>
         <td class="py-5 text-right">
            <div class="flex justify-end gap-2">
               <button class="edit-btn h-9 w-9 rounded-xl bg-white/5 hover:bg-primary/20 text-gray-400 hover:text-primary transition-all border border-white/5 flex items-center justify-center" data-name="${s.name}">
                  <i class="fas fa-edit text-xs"></i>
               </button>
               <button class="delete-btn h-9 w-9 rounded-xl bg-white/5 hover:bg-red-500/20 text-gray-400 hover:text-red-500 transition-all border border-white/5 flex items-center justify-center" data-name="${s.name}">
                  <i class="fas fa-trash text-xs"></i>
               </button>
            </div>
         </td>
      </tr>
    `).join('');

    bindEvents();
    updateBulkBar();
  }

  function bindEvents() {
    // Edit action
    document.querySelectorAll('.edit-btn').forEach(btn => {
      btn.onclick = () => {
        const currentName = btn.getAttribute('data-name');
        window.txamodal.show({
          title: 'Sửa tên Server',
          message: `Thay đổi tên máy chủ:
            <input type="text" id="edit-sv-input" value="${currentName}" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-2.5 mt-2 text-sm text-white focus:outline-none focus:border-primary/50" />`,
          type: 'warning',
          confirmText: 'Lưu thay đổi',
          onConfirm: async () => {
            const newNameInput = document.getElementById('edit-sv-input');
            const newName = newNameInput ? newNameInput.value.trim() : '';
            if (!newName) {
              window.txatoast.error('Tên không được để trống!');
              return false;
            }

            try {
              const res = await fetch('/api/admin/servers', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name: newName, originalName: currentName })
              });
              const data = await res.json();
              if (res.ok) {
                servers = data.list;
                renderTable();
                window.txatoast.success(data.message);
              } else {
                window.txatoast.error(data.error);
              }
            } catch(e) {
              window.txatoast.error('Lỗi kết nối máy chủ!');
            }
            return true;
          }
        });
      };
    });

    // Delete action
    document.querySelectorAll('.delete-btn').forEach(btn => {
      btn.onclick = () => {
        const name = btn.getAttribute('data-name');
        window.txamodal.show({
          title: 'Xác nhận xóa Server',
          message: `Bạn có chắc chắn muốn xóa Server <b>${name}</b>? Các tập phim thuộc server này sẽ tạm thời không thể phát được.`,
          type: 'error',
          confirmText: 'Xóa ngay',
          onConfirm: async () => {
            try {
              const res = await fetch('/api/admin/servers', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name })
              });
              const data = await res.json();
              if (res.ok) {
                servers = data.list;
                renderTable();
                window.txatoast.success(data.message);
              } else {
                window.txatoast.error(data.error);
              }
            } catch(e) {
              window.txatoast.error('Lỗi kết nối máy chủ!');
            }
            return true;
          }
        });
      };
    });

    // Checkboxes click
    document.querySelectorAll('.chk-item').forEach(chk => {
      chk.onchange = () => {
        updateBulkBar();
      };
    });
  }

  function updateBulkBar() {
    const chkAll = document.getElementById('chk-all');
    const checked = document.querySelectorAll('.chk-item:checked');
    const totalCount = document.querySelectorAll('.chk-item').length;
    const bulkBar = document.getElementById('bulk-bar');
    const selectedCount = document.getElementById('selected-count');

    if (chkAll) {
      chkAll.checked = totalCount > 0 && checked.length === totalCount;
    }

    if (checked.length > 0) {
      if (bulkBar) {
        bulkBar.style.display = 'flex';
      }
      if (selectedCount) selectedCount.textContent = checked.length;
    } else {
      if (bulkBar) {
        bulkBar.style.display = 'none';
      }
    }
  }

  function init() {
    // Search Filter
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
      searchInput.oninput = (e) => {
        searchQuery = e.target.value.trim();
        renderTable();
      };
    }

    // Check all
    const chkAll = document.getElementById('chk-all');
    if (chkAll) {
      chkAll.onchange = () => {
        document.querySelectorAll('.chk-item').forEach(chk => {
          chk.checked = chkAll.checked;
        });
        updateBulkBar();
      };
    }

    // Create Server
    const createBtn = document.getElementById('create-server-btn');
    if (createBtn) {
      createBtn.onclick = () => {
        window.txamodal.show({
          title: 'Thêm Server mới',
          message: `Nhập tên máy chủ phát mới (ví dụ: Vietsub, Thuyết Minh):
            <input type="text" id="new-sv-input" placeholder="Ví dụ: Lồng Tiếng" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-2.5 mt-2 text-sm text-white focus:outline-none focus:border-primary/50" />`,
          type: 'success',
          confirmText: 'Tạo server',
          onConfirm: async () => {
            const nameInput = document.getElementById('new-sv-input');
            const name = nameInput ? nameInput.value.trim() : '';
            if (!name) {
              window.txatoast.error('Tên không được để trống!');
              return false;
            }

            try {
              const res = await fetch('/api/admin/servers', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name })
              });
              const data = await res.json();
              if (res.ok) {
                servers = data.list;
                renderTable();
                window.txatoast.success(data.message);
              } else {
                window.txatoast.error(data.error);
              }
            } catch(e) {
              window.txatoast.error('Lỗi kết nối máy chủ!');
            }
            return true;
          }
        });
      };
    }

    // Sync Servers
    const syncBtn = document.getElementById('sync-servers-btn');
    if (syncBtn) {
      syncBtn.onclick = () => {
        window.txamodal.show({
          title: 'Xác nhận đồng bộ máy chủ',
          message: 'Bạn có chắc chắn muốn đồng bộ danh sách máy chủ từ kho phim về hệ thống?',
          type: 'warning',
          confirmText: 'Xác nhận',
          onConfirm: async () => {
            window.txatoast.info('Đang đồng bộ danh sách máy chủ từ kho phim...');
            try {
              const res = await fetch('/api/admin/servers', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ sync: true })
              });
              const data = await res.json();
              if (res.ok) {
                servers = data.list;
                renderTable();
                window.txamodal.show({
                  title: 'Đồng bộ máy chủ thành công',
                  message: data.message,
                  type: 'success'
                });
              } else {
                window.txatoast.error(data.error);
              }
            } catch(e) {
              window.txatoast.error('Lỗi kết nối máy chủ khi đồng bộ!');
            }
            return true;
          }
        });
      };
    }

    // Bulk Delete
    const bulkDeleteBtn = document.getElementById('bulk-delete-btn');
    if (bulkDeleteBtn) {
      bulkDeleteBtn.onclick = () => {
        const checked = document.querySelectorAll('.chk-item:checked');
        const names = Array.from(checked).map(c => c.getAttribute('data-name'));

        window.txamodal.show({
          title: 'Xác nhận xóa hàng loạt',
          message: `Bạn có chắc chắn muốn xóa <b>${names.length}</b> máy chủ đã chọn?`,
          type: 'error',
          confirmText: 'Xóa tất cả',
          onConfirm: async () => {
            try {
              const res = await fetch('/api/admin/servers', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ names })
              });
              const data = await res.json();
              if (res.ok) {
                servers = data.list;
                renderTable();
                window.txatoast.success(data.message);
              } else {
                window.txatoast.error(data.error);
              }
            } catch(e) {
              window.txatoast.error('Lỗi kết nối máy chủ!');
            }
            return true;
          }
        });
      };
    }

    renderTable();
  }

  document.addEventListener('astro:page-load', init);
</script>

<style>
  .glass {
    background: rgba(18, 20, 29, 0.4);
    backdrop-filter: blur(40px) saturate(200%);
  }
</style>