Spaces:
Running
Running
File size: 33,478 Bytes
05a54d5 f29440b 54ba854 05a54d5 698499f 05a54d5 698499f 05a54d5 | 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 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 | <!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>لوحة إدارة المكتبة | Library Admin</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Amiri:wght@400;700&family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/dist/umd/supabase.js"></script>
<style>
:root{
--bg:#F6EFDD; --bg-elevated:#FFFDF6; --text:#2B2113; --muted:#8C7B5E;
--accent:#0F5C4E; --accent-2:#B9902E; --accent-soft:#E6E0C8; --border:#E3D6B4;
--danger:#B23B2E; --danger-soft:#F4D9D3; --shadow:0 10px 30px rgba(60,40,10,.10);
}
*{box-sizing:border-box;}
body{margin:0; background:var(--bg); color:var(--text); font-family:'Tajawal', sans-serif;}
.display{font-family:'Amiri', serif;}
[hidden]{display:none !important;}
#app{min-height:100vh;}
.topbar{display:flex; align-items:center; justify-content:space-between; padding:14px 20px;
background:var(--bg-elevated); border-bottom:1px solid var(--border); position:sticky; top:0; z-index:10;}
.brand{display:flex; align-items:center; gap:10px;}
.brand-mark{width:36px; height:36px; border-radius:9px; background:linear-gradient(160deg, var(--accent), var(--accent-2));
color:var(--bg-elevated); display:flex; align-items:center; justify-content:center; font-size:16px;}
.brand-name{font-size:16px; font-weight:700;}
.brand-sub{font-size:11.5px; color:var(--muted);}
main{max-width:920px; margin:0 auto; padding:20px 18px 60px;}
.field{text-align:start; margin-bottom:12px;}
.field label{display:block; font-size:12.5px; color:var(--muted); margin-bottom:5px;}
.field input, .field select, .field textarea{
width:100%; padding:11px 13px; border-radius:10px; border:1px solid var(--border); background:var(--bg);
color:var(--text); font-family:inherit; font-size:14px;
}
.field textarea{resize:vertical; min-height:80px; line-height:1.8;}
.btn{padding:12px 16px; border-radius:10px; border:1px solid var(--border); background:var(--bg-elevated);
color:var(--text); font-size:14.5px; cursor:pointer; font-family:inherit; display:flex; align-items:center;
justify-content:center; gap:8px; transition:transform .12s, background .2s;}
.btn:hover{transform:translateY(-1px); background:var(--accent-soft);}
.btn.primary{background:linear-gradient(160deg, var(--accent), var(--accent-2)); color:var(--bg-elevated); border-color:transparent; font-weight:700;}
.btn.danger{color:var(--danger); border-color:var(--danger-soft);}
.btn.danger:hover{background:var(--danger-soft);}
.btn.small{padding:8px 12px; font-size:13px;}
.btn.full{width:100%;}
.section-head{display:flex; align-items:center; justify-content:space-between; margin-bottom:16px; gap:10px; flex-wrap:wrap;}
.section-head h2{margin:0; font-size:19px;}
.search-row{display:flex; gap:8px; margin-bottom:16px;}
.search-row input{flex:1; padding:11px 15px; border-radius:12px; border:1px solid var(--border);
background:var(--bg-elevated); color:var(--text); font-family:inherit; font-size:14px;}
.book-row{background:var(--bg-elevated); border:1px solid var(--border); border-radius:12px; padding:14px 16px;
display:flex; align-items:center; gap:12px; margin-bottom:10px;}
.book-row .swatch{width:8px; align-self:stretch; border-radius:6px; flex-shrink:0;}
.book-row .info{flex:1; min-width:0;}
.book-row .title{font-weight:700; font-size:14.5px; margin-bottom:2px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;}
.book-row .meta{color:var(--muted); font-size:12px;}
.book-row .actions{display:flex; gap:8px; flex-shrink:0;}
.icon-action{width:36px; height:36px; border-radius:9px; border:1px solid var(--border); background:var(--bg);
cursor:pointer; font-size:15px; display:flex; align-items:center; justify-content:center;}
.icon-action:hover{background:var(--accent-soft);}
.icon-action.danger:hover{background:var(--danger-soft);}
.empty-state{text-align:center; padding:50px 20px; color:var(--muted);}
.empty-state .ee-icon{font-size:34px; margin-bottom:10px;}
/* ---------- Top-level section tabs ---------- */
.admin-tabs{display:flex; gap:6px; background:var(--bg-elevated); border:1px solid var(--border);
border-radius:12px; padding:5px; margin-bottom:20px; overflow-x:auto;}
.admin-tab-btn{flex:1; border:none; background:none; padding:10px 6px; border-radius:9px; cursor:pointer;
font-size:12.5px; color:var(--muted); font-family:inherit; font-weight:600; white-space:nowrap;}
.admin-tab-btn.active{background:var(--accent-soft); color:var(--text);}
/* ---------- Adhkar rows ---------- */
.adhkar-row{background:var(--bg-elevated); border:1px solid var(--border); border-radius:12px; padding:14px 16px;
display:flex; align-items:flex-start; gap:12px; margin-bottom:10px;}
.adhkar-row .orn-badge{font-size:20px; width:36px; height:36px; border-radius:9px; background:var(--accent-soft);
display:flex; align-items:center; justify-content:center; flex-shrink:0;}
.adhkar-row .info{flex:1; min-width:0;}
.adhkar-row .dtext{font-family:'Amiri',serif; font-size:15px; line-height:1.8; margin-bottom:4px;
display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden;}
.adhkar-row .dsource{color:var(--muted); font-size:12px;}
.adhkar-row .actions{display:flex; gap:8px; flex-shrink:0;}
/* ---------- Stats rows ---------- */
.stat-row{background:var(--bg-elevated); border:1px solid var(--border); border-radius:12px; padding:14px 16px;
display:flex; align-items:center; gap:14px; margin-bottom:10px;}
.stat-row .info{flex:1; min-width:0;}
.stat-row .title{font-weight:700; font-size:14.5px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;}
.stat-row .stat-nums{display:flex; gap:16px; flex-shrink:0; text-align:center;}
.stat-row .stat-item{min-width:56px;}
.stat-row .stat-item .num{font-weight:700; font-size:15px;}
.stat-row .stat-item .lbl{font-size:10.5px; color:var(--muted);}
/* ---------- Modal (edit form) ---------- */
.modal-overlay{position:fixed; inset:0; background:rgba(0,0,0,.45); z-index:40; display:flex;
align-items:center; justify-content:center; padding:16px;}
.modal-overlay[hidden]{display:none;}
.modal{background:var(--bg-elevated); border-radius:18px; max-width:520px; width:100%; padding:24px;
position:relative; box-shadow:var(--shadow); max-height:90vh; overflow-y:auto;}
.modal-close{position:absolute; left:16px; top:16px; border:none; background:none; font-size:18px; cursor:pointer; color:var(--muted);}
.modal h3{margin:0 0 16px;}
.form-grid{display:grid; grid-template-columns:1fr 1fr; gap:0 12px;}
.form-grid .field.full{grid-column:1/-1;}
.color-row{display:flex; align-items:center; gap:10px;}
.color-row input[type=color]{width:44px; height:38px; padding:2px; border-radius:8px; border:1px solid var(--border); background:var(--bg); cursor:pointer;}
.modal-actions{display:flex; gap:8px; margin-top:16px;}
.add-card{background:var(--bg-elevated); border:1px solid var(--border); border-radius:16px; padding:20px;}
.toast{position:fixed; bottom:26px; left:50%; transform:translateX(-50%); background:var(--text); color:var(--bg);
padding:10px 20px; border-radius:20px; font-size:13px; z-index:80; opacity:0; pointer-events:none;
transition:opacity .25s; white-space:nowrap;}
.toast.show{opacity:1;}
</style>
</head>
<body>
<div id="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark">📚</div>
<div>
<div class="brand-name">لوحة إدارة المكتبة</div>
<div class="brand-sub">وصول مفتوح بدون تسجيل دخول</div>
</div>
</div>
</header>
<main>
<div class="admin-tabs">
<button class="admin-tab-btn active" id="tabAddBtn" onclick="switchAdminSection('add')">➕ إضافة كتاب</button>
<button class="admin-tab-btn" id="tabManageBtn" onclick="switchAdminSection('manage')">📚 إدارة الكتب</button>
<button class="admin-tab-btn" id="tabStatsBtn" onclick="switchAdminSection('stats')">📊 الإحصائيات</button>
<button class="admin-tab-btn" id="tabAdhkarBtn" onclick="switchAdminSection('adhkar')">📿 الأذكار</button>
</div>
<!-- ADD BOOK SECTION -->
<div id="addSection">
<div class="section-head"><h2>إضافة كتاب جديد</h2></div>
<div class="add-card">
<form id="addBookForm" onsubmit="return addBook(event)">
<div class="form-grid">
<div class="field full">
<label>التصنيف</label>
<select id="nCategory" required>
<option value="literature">أدب</option>
<option value="religion">دين</option>
<option value="history">تاريخ</option>
<option value="spelling">الإملاء</option>
<option value="morphology">الصرف</option>
<option value="language">اللغة</option>
<option value="Curriculum">المناهج الدراسية</option>
</select>
</div>
<div class="field">
<label>العنوان (عربي)</label>
<input type="text" id="nTitleAr" required>
</div>
<div class="field">
<label>العنوان (إنجليزي)</label>
<input type="text" id="nTitleEn">
</div>
<div class="field">
<label>المؤلف (عربي)</label>
<input type="text" id="nAuthorAr">
</div>
<div class="field">
<label>المؤلف (إنجليزي)</label>
<input type="text" id="nAuthorEn">
</div>
<div class="field full">
<label>وصف الكتاب (عربي)</label>
<textarea id="nDescAr"></textarea>
</div>
<div class="field full">
<label>وصف الكتاب (إنجليزي)</label>
<textarea id="nDescEn"></textarea>
</div>
<div class="field full">
<label>ملف الكتاب (PDF) *</label>
<input type="file" id="nPdfFile" accept="application/pdf">
</div>
<div class="field">
<label>عدد الصفحات (اختياري)</label>
<input type="number" id="nTotalPages" min="1" value="60">
</div>
<div class="field">
<label>لون الغلاف</label>
<div class="color-row">
<input type="color" id="nColor" value="#0F5C4E">
<span style="color:var(--muted); font-size:12px;" id="nColorHex">#0F5C4E</span>
</div>
</div>
</div>
<button type="submit" class="btn primary full" id="addSaveBtnLabel">حفظ الكتاب</button>
</form>
</div>
</div>
<!-- MANAGE BOOKS SECTION -->
<div id="manageSection" hidden>
<div class="section-head">
<h2>إدارة الكتب (<span id="bookCount">0</span>)</h2>
</div>
<div class="search-row">
<input type="text" id="searchInput" placeholder="ابحث عن كتاب أو مؤلف..." oninput="renderList()">
</div>
<div id="bookList"></div>
</div>
<!-- STATS SECTION -->
<div id="statsSection" hidden>
<div class="section-head"><h2>إحصائيات الكتب</h2></div>
<div id="statsList"></div>
</div>
<!-- ADHKAR SECTION -->
<div id="adhkarSection" hidden>
<div class="section-head">
<h2>أذكار أهل البيت (<span id="adhkarCount">0</span>)</h2>
<button class="btn primary small" onclick="openAdhkarForm()">➕ إضافة ذكر جديد</button>
</div>
<div id="adhkarList"></div>
</div>
</main>
<!-- EDIT BOOK MODAL -->
<div class="modal-overlay" id="formOverlay" hidden onclick="closeFormOnOverlay(event)">
<div class="modal">
<button class="modal-close" onclick="closeForm()">✕</button>
<h3 class="display">تعديل الكتاب</h3>
<form id="bookForm" onsubmit="return saveBook(event)">
<input type="hidden" id="bookId">
<div class="form-grid">
<div class="field full">
<label>التصنيف</label>
<select id="fCategory" required>
<option value="literature">الأدب</option>
<option value="religion">الدين</option>
<option value="history">التاريخ</option>
<option value="spelling">الإملاء</option>
<option value="morphology">الصرف</option>
<option value="Curriculum">المناهج الدراسية</option>
</select>
</div>
<div class="field">
<label>العنوان (عربي)</label>
<input type="text" id="fTitleAr" required>
</div>
<div class="field">
<label>العنوان (إنجليزي)</label>
<input type="text" id="fTitleEn">
</div>
<div class="field">
<label>المؤلف (عربي)</label>
<input type="text" id="fAuthorAr">
</div>
<div class="field">
<label>المؤلف (إنجليزي)</label>
<input type="text" id="fAuthorEn">
</div>
<div class="field full">
<label>وصف الكتاب (عربي)</label>
<textarea id="fDescAr"></textarea>
</div>
<div class="field full">
<label>وصف الكتاب (إنجليزي)</label>
<textarea id="fDescEn"></textarea>
</div>
<div class="field full">
<label>ملف الكتاب (PDF)</label>
<div id="currentPdfInfo" style="font-size:12px; color:var(--muted); margin-bottom:6px;"></div>
<input type="file" id="fPdfFile" accept="application/pdf">
<div style="font-size:11.5px; color:var(--muted); margin-top:4px;">اتركيه فارغًا إذا ما تريدين تغيير الملف الحالي</div>
</div>
<div class="field">
<label>عدد الصفحات (اختياري)</label>
<input type="number" id="fTotalPages" min="1" value="60">
</div>
<div class="field">
<label>لون الغلاف</label>
<div class="color-row">
<input type="color" id="fColor" value="#0F5C4E">
<span style="color:var(--muted); font-size:12px;" id="colorHex">#0F5C4E</span>
</div>
</div>
</div>
<div class="modal-actions">
<button type="button" class="btn" onclick="closeForm()">إلغاء</button>
<button type="submit" class="btn primary" id="saveBtnLabel">حفظ التعديلات</button>
</div>
</form>
</div>
</div>
<!-- ADHKAR ADD/EDIT FORM MODAL -->
<div class="modal-overlay" id="adhkarFormOverlay" hidden onclick="closeAdhkarFormOnOverlay(event)">
<div class="modal">
<button class="modal-close" onclick="closeAdhkarForm()">✕</button>
<h3 class="display" id="adhkarFormTitle">إضافة ذكر جديد</h3>
<form id="adhkarForm" onsubmit="return saveAdhkar(event)">
<input type="hidden" id="adhkarId">
<div class="field full">
<label>نص الذكر</label>
<textarea id="aText" required style="min-height:120px; font-family:'Amiri', serif; font-size:15px; line-height:1.9;"></textarea>
</div>
<div class="field full">
<label>المصدر</label>
<input type="text" id="aSource" placeholder="مثال: مفاتيح الجنان، الصحيفة السجادية...">
</div>
<div class="field full">
<label>الزخرفة الإسلامية</label>
<select id="aOrnament">
<option value="hizb">۞ زخرفة الرُّبع (تقليدية)</option>
<option value="star8">✦ زخرفة نجمية</option>
<option value="floral">❧ زخرفة الأزهار</option>
<option value="classic">﴾﴿ إطار قرآني كلاسيكي</option>
</select>
</div>
<div class="modal-actions">
<button type="button" class="btn" onclick="closeAdhkarForm()">إلغاء</button>
<button type="submit" class="btn primary" id="adhkarSaveBtnLabel">حفظ الذكر</button>
</div>
</form>
</div>
</div>
<div class="toast" id="toast"></div>
</div>
<script>
/* =========================================================================
إعدادات الاتصال بـ Supabase (نفس مشروع المكتبة)
ملاحظة مهمة: هذه اللوحة بدون تسجيل دخول بناءً على طلبك، لذا جدول الكتب
والأذكار مفتوح للكتابة لأي شخص يملك رابط اللوحة (أو مفتاح anon العام
الظاهر بالكود). حافظي على رابط اللوحة خاصًا إذا ما تريدين أي شخص غيرك
يعدّل المحتوى.
========================================================================= */
const SUPABASE_URL = 'https://nshuwvmaidlagypifyde.supabase.co';
const SUPABASE_ANON_KEY = 'sb_publishable_nUbqTqIfATYfIZSPC8auFg_5ubR5cJ6';
const CONFIGURED = SUPABASE_URL.startsWith('http') && SUPABASE_ANON_KEY.length > 20;
let supabaseClient = null;
if(CONFIGURED){
supabaseClient = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
}
/* تنبيهات الأخطاء تطلع Popup على الشاشة (مفيد جدًا بالجوال بدون أدوات مطور) */
window.addEventListener('error', function(e){
alert('خطأ: ' + e.message);
});
window.addEventListener('unhandledrejection', function(e){
alert('خطأ: ' + (e.reason && e.reason.message ? e.reason.message : JSON.stringify(e.reason)));
});
let BOOKS = [];
let ADHKAR = [];
let RATINGS = [];
let adminSection = 'add';
const ORNAMENT_LABELS = {
hizb:'۞ زخرفة الرُّبع', star8:'✦ زخرفة نجمية', floral:'❧ زخرفة الأزهار', classic:'﴾﴿ إطار قرآني'
};
window.addEventListener('DOMContentLoaded', async ()=>{
if(!CONFIGURED){ showToast('لم يتم الربط بقاعدة البيانات بعد'); return; }
await Promise.all([loadBooks(), loadAdhkar(), loadRatings()]);
});
/* ---------------- Section switch ---------------- */
function switchAdminSection(section){
adminSection = section;
document.getElementById('tabAddBtn').classList.toggle('active', section==='add');
document.getElementById('tabManageBtn').classList.toggle('active', section==='manage');
document.getElementById('tabStatsBtn').classList.toggle('active', section==='stats');
document.getElementById('tabAdhkarBtn').classList.toggle('active', section==='adhkar');
document.getElementById('addSection').hidden = section !== 'add';
document.getElementById('manageSection').hidden = section !== 'manage';
document.getElementById('statsSection').hidden = section !== 'stats';
document.getElementById('adhkarSection').hidden = section !== 'adhkar';
if(section==='stats') renderStats();
}
/* ---------------- Books: load / list / search ---------------- */
async function loadBooks(){
const { data, error } = await supabaseClient.from('books').select('*').order('created_at', { ascending:false });
if(error){ console.error(error); showToast('تعذّر تحميل الكتب'); BOOKS = []; }
else { BOOKS = data || []; }
renderList();
}
function renderList(){
const query = (document.getElementById('searchInput')?.value || '').trim().toLowerCase();
const results = BOOKS.filter(b=>{
if(!query) return true;
return (b.title_ar||'').toLowerCase().includes(query) || (b.title_en||'').toLowerCase().includes(query) ||
(b.author_ar||'').toLowerCase().includes(query) || (b.author_en||'').toLowerCase().includes(query);
});
document.getElementById('bookCount').textContent = BOOKS.length;
const list = document.getElementById('bookList');
if(!BOOKS.length){
list.innerHTML = `<div class="empty-state"><div class="ee-icon">📭</div><p>لا توجد كتب بعد. روحي لتبويب "إضافة كتاب".</p></div>`;
return;
}
if(!results.length){
list.innerHTML = `<div class="empty-state"><p>لا توجد نتائج مطابقة</p></div>`;
return;
}
list.innerHTML = results.map(b=>`
<div class="book-row">
<div class="swatch" style="background:${b.cover_color||'#0F5C4E'}"></div>
<div class="info">
<div class="title">${escapeHtml(b.title_ar||b.title_en||'—')}</div>
<div class="meta">${escapeHtml(b.author_ar||b.author_en||'')} · ${categoryLabel(b.category)} · ${b.total_pages||60} صفحة</div>
</div>
<div class="actions">
<button class="icon-action" title="تعديل" onclick="openForm('${b.id}')">✏️</button>
<button class="icon-action danger" title="حذف" onclick="deleteBook('${b.id}')">🗑️</button>
</div>
</div>
`).join('');
}
function categoryLabel(key){
const map = {literature:'أدب', religion:'دين', history:'تاريخ', spelling:'الإملاء', morphology:'الصرف'};
return map[key] || key || '—';
}
function escapeHtml(s){
const d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML;
}
/* ---------------- PDF upload helper ---------------- */
async function uploadBookPdf(file){
const safeName = file.name.replace(/[^a-zA-Z0-9._-]/g, '_');
const path = `${Date.now()}-${safeName}`;
const { error } = await supabaseClient.storage.from('book-pdfs').upload(path, file, {
contentType: 'application/pdf', upsert: true
});
if(error){ console.error(error); return null; }
const { data } = supabaseClient.storage.from('book-pdfs').getPublicUrl(path);
return data.publicUrl;
}
/* ---------------- Add book (tab 1) ---------------- */
document.getElementById('nColor')?.addEventListener?.('input', function(){
document.getElementById('nColorHex').textContent = this.value;
});
async function addBook(e){
e.preventDefault();
const file = document.getElementById('nPdfFile').files[0];
if(!file){ showToast('لازم ترفع ملف PDF للكتاب'); return false; }
const btn = document.getElementById('addSaveBtnLabel');
const original = btn.textContent;
btn.textContent = '...جارِ رفع الملف';
const pdfUrl = await uploadBookPdf(file);
if(!pdfUrl){ btn.textContent = original; showToast('تعذّر رفع ملف الـ PDF'); return false; }
const payload = {
category: document.getElementById('nCategory').value,
title_ar: document.getElementById('nTitleAr').value.trim(),
title_en: document.getElementById('nTitleEn').value.trim(),
author_ar: document.getElementById('nAuthorAr').value.trim(),
author_en: document.getElementById('nAuthorEn').value.trim(),
desc_ar: document.getElementById('nDescAr').value.trim(),
desc_en: document.getElementById('nDescEn').value.trim(),
total_pages: parseInt(document.getElementById('nTotalPages').value, 10) || 60,
cover_color: document.getElementById('nColor').value,
pdf_url: pdfUrl,
};
btn.textContent = '...جارِ الحفظ';
const { error } = await supabaseClient.from('books').insert(payload);
btn.textContent = original;
if(error){ console.error(error); showToast('تعذّر حفظ الكتاب'); return false; }
document.getElementById('addBookForm').reset();
document.getElementById('nColorHex').textContent = '#0F5C4E';
showToast('تمت إضافة الكتاب بنجاح');
await loadBooks();
return false;
}
/* ---------------- Edit form (modal, tab 2) ---------------- */
function openForm(id){
const b = BOOKS.find(x=>String(x.id)===String(id));
if(!b) return;
document.getElementById('bookForm').reset();
document.getElementById('bookId').value = b.id;
document.getElementById('fCategory').value = b.category || 'literature';
document.getElementById('fTitleAr').value = b.title_ar || '';
document.getElementById('fTitleEn').value = b.title_en || '';
document.getElementById('fAuthorAr').value = b.author_ar || '';
document.getElementById('fAuthorEn').value = b.author_en || '';
document.getElementById('fDescAr').value = b.desc_ar || '';
document.getElementById('fDescEn').value = b.desc_en || '';
document.getElementById('fTotalPages').value = b.total_pages || 60;
document.getElementById('fColor').value = b.cover_color || '#0F5C4E';
document.getElementById('colorHex').textContent = b.cover_color || '#0F5C4E';
document.getElementById('currentPdfInfo').innerHTML = b.pdf_url
? `📄 يوجد ملف مرفوع حاليًا — <a href="${b.pdf_url}" target="_blank">فتح الملف</a>`
: `⚠️ لا يوجد ملف PDF مرفوع لهذا الكتاب بعد`;
document.getElementById('formOverlay').hidden = false;
}
function closeForm(){ document.getElementById('formOverlay').hidden = true; }
function closeFormOnOverlay(e){ if(e.target.id==='formOverlay') closeForm(); }
document.getElementById('fColor')?.addEventListener?.('input', function(){
document.getElementById('colorHex').textContent = this.value;
});
async function saveBook(e){
e.preventDefault();
const id = document.getElementById('bookId').value;
const payload = {
category: document.getElementById('fCategory').value,
title_ar: document.getElementById('fTitleAr').value.trim(),
title_en: document.getElementById('fTitleEn').value.trim(),
author_ar: document.getElementById('fAuthorAr').value.trim(),
author_en: document.getElementById('fAuthorEn').value.trim(),
desc_ar: document.getElementById('fDescAr').value.trim(),
desc_en: document.getElementById('fDescEn').value.trim(),
total_pages: parseInt(document.getElementById('fTotalPages').value, 10) || 60,
cover_color: document.getElementById('fColor').value,
};
const saveBtn = document.getElementById('saveBtnLabel');
const originalLabel = saveBtn.textContent;
const newFile = document.getElementById('fPdfFile').files[0];
if(newFile){
saveBtn.textContent = '...جارِ رفع الملف';
const pdfUrl = await uploadBookPdf(newFile);
if(!pdfUrl){ saveBtn.textContent = originalLabel; showToast('تعذّر رفع ملف الـ PDF'); return false; }
payload.pdf_url = pdfUrl;
}
saveBtn.textContent = '...جارِ الحفظ';
const { error } = await supabaseClient.from('books').update(payload).eq('id', id);
saveBtn.textContent = originalLabel;
if(error){ console.error(error); showToast('تعذّر حفظ التعديلات'); return false; }
closeForm();
showToast('تم حفظ التعديلات');
await loadBooks();
return false;
}
async function deleteBook(id){
const b = BOOKS.find(x=>String(x.id)===String(id));
const name = b ? (b.title_ar || b.title_en || '') : '';
if(!confirm(`هل تريد حذف كتاب "${name}"؟ لا يمكن التراجع عن هذا الإجراء.`)) return;
const { error } = await supabaseClient.from('books').delete().eq('id', id);
if(error){ console.error(error); showToast('تعذّر حذف الكتاب'); return; }
showToast('تم حذف الكتاب');
await loadBooks();
}
/* ---------------- Stats (tab 3) ---------------- */
async function loadRatings(){
const { data, error } = await supabaseClient.from('book_ratings').select('book_id, rating');
if(error){ console.error(error); RATINGS = []; }
else { RATINGS = data || []; }
}
function ratingStatsFor(bookId){
const rows = RATINGS.filter(r=>String(r.book_id)===String(bookId));
if(!rows.length) return { avg:0, count:0 };
const sum = rows.reduce((s,r)=>s+r.rating, 0);
return { avg: (sum/rows.length), count: rows.length };
}
function renderStats(){
const list = document.getElementById('statsList');
if(!BOOKS.length){
list.innerHTML = `<div class="empty-state"><div class="ee-icon">📊</div><p>لا توجد كتب بعد لعرض إحصائياتها.</p></div>`;
return;
}
const sorted = [...BOOKS].sort((a,b)=> (b.views_count||0) - (a.views_count||0));
list.innerHTML = sorted.map(b=>{
const { avg, count } = ratingStatsFor(b.id);
return `
<div class="stat-row">
<div class="info">
<div class="title">${escapeHtml(b.title_ar||b.title_en||'—')}</div>
</div>
<div class="stat-nums">
<div class="stat-item"><div class="num">${b.views_count||0}</div><div class="lbl">👁️ مشاهدة</div></div>
<div class="stat-item"><div class="num">${count ? avg.toFixed(1) : '—'}</div><div class="lbl">⭐ المعدل</div></div>
<div class="stat-item"><div class="num">${count}</div><div class="lbl">تقييم</div></div>
</div>
</div>`;
}).join('');
}
/* ---------------- Adhkar (tab 4) ---------------- */
async function loadAdhkar(){
const { data, error } = await supabaseClient.from('adhkar').select('*').order('created_at', { ascending:false });
if(error){ console.error(error); showToast('تعذّر تحميل الأذكار'); ADHKAR = []; }
else { ADHKAR = data || []; }
renderAdhkarList();
}
function renderAdhkarList(){
document.getElementById('adhkarCount').textContent = ADHKAR.length;
const list = document.getElementById('adhkarList');
if(!ADHKAR.length){
list.innerHTML = `<div class="empty-state"><div class="ee-icon">📿</div><p>لا توجد أذكار بعد. اضغط "إضافة ذكر جديد" لبدء إضافة أذكار أهل البيت.</p></div>`;
return;
}
list.innerHTML = ADHKAR.map(a=>`
<div class="adhkar-row">
<div class="orn-badge">${ornamentGlyph(a.ornament)}</div>
<div class="info">
<div class="dtext">${escapeHtml(a.text_ar||'')}</div>
<div class="dsource">${a.source ? '— ' + escapeHtml(a.source) : ''} · ${ORNAMENT_LABELS[a.ornament] || ''}</div>
</div>
<div class="actions">
<button class="icon-action" title="تعديل" onclick="openAdhkarForm('${a.id}')">✏️</button>
<button class="icon-action danger" title="حذف" onclick="deleteAdhkar('${a.id}')">🗑️</button>
</div>
</div>
`).join('');
}
function ornamentGlyph(key){
const map = {hizb:'۞', star8:'✦', floral:'❧', classic:'﴾﴿'};
return map[key] || map.hizb;
}
function openAdhkarForm(id){
document.getElementById('adhkarForm').reset();
if(id){
const a = ADHKAR.find(x=>String(x.id)===String(id));
if(!a) return;
document.getElementById('adhkarFormTitle').textContent = 'تعديل الذكر';
document.getElementById('adhkarSaveBtnLabel').textContent = 'حفظ التعديلات';
document.getElementById('adhkarId').value = a.id;
document.getElementById('aText').value = a.text_ar || '';
document.getElementById('aSource').value = a.source || '';
document.getElementById('aOrnament').value = a.ornament || 'hizb';
} else {
document.getElementById('adhkarFormTitle').textContent = 'إضافة ذكر جديد';
document.getElementById('adhkarSaveBtnLabel').textContent = 'حفظ الذكر';
document.getElementById('adhkarId').value = '';
}
document.getElementById('adhkarFormOverlay').hidden = false;
}
function closeAdhkarForm(){ document.getElementById('adhkarFormOverlay').hidden = true; }
function closeAdhkarFormOnOverlay(e){ if(e.target.id==='adhkarFormOverlay') closeAdhkarForm(); }
async function saveAdhkar(e){
e.preventDefault();
const id = document.getElementById('adhkarId').value;
const payload = {
text_ar: document.getElementById('aText').value.trim(),
source: document.getElementById('aSource').value.trim(),
ornament: document.getElementById('aOrnament').value,
};
const saveBtn = document.getElementById('adhkarSaveBtnLabel');
const originalLabel = saveBtn.textContent;
saveBtn.textContent = '...جارِ الحفظ';
let error;
if(id){
({ error } = await supabaseClient.from('adhkar').update(payload).eq('id', id));
} else {
({ error } = await supabaseClient.from('adhkar').insert(payload));
}
saveBtn.textContent = originalLabel;
if(error){ console.error(error); showToast('تعذّر حفظ الذكر'); return false; }
closeAdhkarForm();
showToast(id ? 'تم حفظ التعديلات' : 'تمت إضافة الذكر');
await loadAdhkar();
return false;
}
async function deleteAdhkar(id){
if(!confirm('هل تريد حذف هذا الذكر؟ لا يمكن التراجع عن هذا الإجراء.')) return;
const { error } = await supabaseClient.from('adhkar').delete().eq('id', id);
if(error){ console.error(error); showToast('تعذّر حذف الذكر'); return; }
showToast('تم حذف الذكر');
await loadAdhkar();
}
/* ---------------- Toast ---------------- */
function showToast(msg){
const el = document.getElementById('toast');
el.textContent = msg;
el.classList.add('show');
clearTimeout(window._toastTimer);
window._toastTimer = setTimeout(()=> el.classList.remove('show'), 2200);
}
</script>
</body>
</html> |