سجل دخولك للمتابعة

'); w.document.close(); setTimeout(function(){w.print();},300); } // ===================== SETTINGS ===================== function renderSettings(){ // Users var uh=''; D.users.forEach(function(u){ uh+='
'; uh+=''+E(u.name)+''; uh+=''+u.username+''; uh+=''+(u.role==='admin'?'أدمن':'موظف')+''; uh+=''; if(u.id!=(D.users[0]&&D.users[0].id))uh+=''; uh+='
'; }); document.getElementById('usersList').innerHTML=uh; // Svcs var svh=''; D.svcs.forEach(function(sv){ svh+='
'; svh+='
'; svh+=''; svh+=''+E(sv.name)+''; svh+=''+sv.mx+' users'; svh+=''; svh+=''; svh+='
'; }); document.getElementById('svcsList').innerHTML=svh; // Load WA template var wtEl=document.getElementById('waTemplate'); if(wtEl)wtEl.value=D.sett.waTemplate||DEFAULT_WA_TEMPLATE; // Update rdInput value var rdEl=document.getElementById('rdInput'); if(rdEl)rdEl.value=D.sett.rd||3; // Update notif button var nb=document.getElementById('notifBtn'); if(nb){ if(D.sett.notifs&&Notification.permission==='granted'){ nb.innerHTML=' الإشعارات مفعلة';nb.style.color='var(--green)'; } else { nb.innerHTML=' تفعيل الإشعارات';nb.style.color=''; } } // Ecats var ech=''; D.ecats.forEach(function(c){ ech+='
'; ech+='
'; ech+=''+E(c.name)+''; ech+=''; ech+=''; ech+='
'; }); document.getElementById('ecatsList').innerHTML=ech; } function exportBackup(){ var data={v:2,date:new Date().toISOString(),subs:D.subs,accs:D.accs,emails:D.emails,exps:D.exps,ecats:D.ecats,svcs:D.svcs,users:D.users,log:D.log,probs:D.probs,sett:D.sett}; var blob=new Blob([JSON.stringify(data,null,2)],{type:'application/json'}); var a=document.createElement('a');a.href=URL.createObjectURL(blob); a.download='streamdesk_backup_'+T()+'.json';a.click();URL.revokeObjectURL(a.href); toast('تم التصدير \u2713'); } function importBackup(input){ var file=input.files[0];if(!file)return; var reader=new FileReader(); reader.onload=function(e){ try{ var data=JSON.parse(e.target.result); if(!data.subs){toast('ملف غير صحيح!');return;} if(!confirm('سيتم استبدال كل البيانات بالباكب. متاكد؟'))return; if(data.subs)D.subs=data.subs;if(data.accs)D.accs=data.accs; if(data.emails)D.emails=data.emails;if(data.exps)D.exps=data.exps; if(data.ecats)D.ecats=data.ecats;if(data.svcs)D.svcs=data.svcs; if(data.users)D.users=data.users;if(data.log)D.log=data.log; if(data.probs)D.probs=data.probs;if(data.sett)D.sett=data.sett; SA();toast('تم الاستيراد \u2713');setTimeout(function(){location.reload();},1500); }catch(err){toast('خطأ في الملف!');} };reader.readAsText(file);input.value=''; } function exportCSV(){ var rows=[['\u0627\u0644\u0627\u0633\u0645','\u0627\u0644\u0645\u0648\u0628\u0627\u064A\u0644','\u0627\u0644\u062E\u062F\u0645\u0629','\u0627\u0644\u0628\u062F\u0627\u064A\u0629','\u0627\u0644\u0627\u0646\u062A\u0647\u0627\u0621','\u0627\u0644\u0633\u0639\u0631','\u0627\u0644\u062D\u0627\u0644\u0629']]; D.subs.forEach(function(s){ var sv=GS(s.svid);var dl=DL(s.end); var st=dl<0?'\u0645\u0646\u062A\u0647\u064A':s.paid?'\u0646\u0634\u0637':'\u063A\u064A\u0631 \u0645\u062F\u0641\u0648\u0639'; rows.push([s.name||'',s.phone||'',sv.name,s.start||'',s.end||'',s.price||0,st]); }); var csv=rows.map(function(r){return r.map(function(v){return '"'+String(v).replace(/"/g,'""')+'"';}).join(',');}).join('\n'); var blob=new Blob(['\uFEFF'+csv],{type:'text/csv;charset=utf-8'}); var a=document.createElement('a');a.href=URL.createObjectURL(blob); a.download='streamdesk_'+T()+'.csv';a.click();URL.revokeObjectURL(a.href); toast('\u062A\u0645 \u0627\u0644\u062A\u0635\u062F\u064A\u0631 \u2713'); } function toggleDark(){ var d=document.body.classList.toggle('dark'); document.documentElement.classList.toggle('dark-vars',d); localStorage.setItem('sd_dark',d?'1':''); var btn=document.getElementById('darkBtn'); if(btn)btn.innerHTML=d?'':''; } function doLogout(){ if(!confirm('هل تريد تسجيل الخروج؟'))return; localStorage.removeItem('sd_session'); location.reload(); } function checkAutoSession(){ if(!window._autoLoginUser)return false; CU=window._autoLoginUser; window._autoLoginUser=null; document.getElementById('lock').style.display='none'; document.getElementById('appMain').style.display='block'; var isStaff=CU&&CU.role!=='admin'; if(CU){ var _b=document.getElementById('cuname'); if(_b){ var _iS=CU.role!=='admin'; _b.innerHTML=''+E(CU.name)+(_iS?' (موظف)':' (أدمن)')+''; } } if(isStaff){ document.querySelectorAll('.tab').forEach(function(t){ var oc=t.getAttribute('onclick')||''; if(oc.indexOf("'expenses'")>-1||oc.indexOf("'reports'")>-1||oc.indexOf("'settings'")>-1){ t.style.display='none'; } }); } initDark(); initApp(); if(D.sett.notifs&&Notification.permission==='granted'){ setTimeout(checkNotifs,2000); } return true; } function initDark(){ if(localStorage.getItem('sd_dark')==='1'){ document.body.classList.add('dark'); document.documentElement.classList.add('dark-vars'); var btn=document.getElementById('darkBtn'); if(btn)btn.innerHTML=''; } } function savePin(){ var v=document.getElementById('newPin').value.trim(); if(!v){toast('ادخل PIN');return;} D.sett.pin=v;SA();toast('تم حفظ الـ PIN ✓'); } function saveRd(){ var v=parseInt(document.getElementById('rdInput').value)||3; D.sett.rd=v;SA();toast('تم الحفظ ✓');renderStats(); } function toggleSound(){ D.sett.sound=!D.sett.sound;SA(); var btn=document.getElementById('soundBtn'); if(btn){btn.innerHTML=D.sett.sound?' إيقاف الصوت':' تنبيه صوتي';btn.style.color=D.sett.sound?'var(--green)':'';} if(D.sett.sound)playAlert(); toast(D.sett.sound?'تم تفعيل الصوت':'تم إيقاف الصوت'); } function playAlert(){ try{ var ctx=new(window.AudioContext||window.webkitAudioContext)(); [523,659,784].forEach(function(f,i){ var o=ctx.createOscillator(),g=ctx.createGain(); o.connect(g);g.connect(ctx.destination); o.frequency.value=f;o.type='sine'; g.gain.setValueAtTime(0.25,ctx.currentTime+i*0.15); g.gain.exponentialRampToValueAtTime(0.001,ctx.currentTime+i*0.15+0.2); o.start(ctx.currentTime+i*0.15);o.stop(ctx.currentTime+i*0.15+0.2); }); }catch(e){} } function enableNotifs(){ if(!('Notification' in window)){toast('المتصفح مش بيدعم الإشعارات');return;} Notification.requestPermission().then(function(perm){ if(perm==='granted'){ D.sett.notifs=true;SA(); toast('تم تفعيل الإشعارات ✓'); document.getElementById('notifBtn').innerHTML=' الإشعارات مفعلة'; document.getElementById('notifBtn').style.color='var(--green)'; checkNotifs(); } else { toast('تم رفض الإشعارات'); } }); } function checkNotifs(){ // Check my platform accounts var rd=parseInt(D.sett.rd)||3; var myExpiring=D.myaccs.filter(function(a){var d=DL(a.renew);return d>=0&&d<=rd;}); var myExpired=D.myaccs.filter(function(a){return DL(a.renew)<0&&DL(a.renew)>=-1;}); if((myExpiring.length||myExpired.length)&&D.sett.sound)playAlert(); if(myExpiring.length&&Notification.permission==='granted'){ new Notification('Digital Store - حساباتك',{body:myExpiring.length+' حساب من حساباتك هينتهي قريباً'}); } // original notifs below... var rd=parseInt(D.sett.rd)||3; var soon=D.subs.filter(function(s){var d=DL(s.end);return d>=0&&d<=rd;}); var expired=D.subs.filter(function(s){return DL(s.end)<0&&DL(s.end)>=-1;}); if((soon.length||expired.length)&&D.sett.sound)playAlert(); if(!D.sett.notifs||Notification.permission!=='granted')return; if(soon.length)new Notification('StreamDesk',{body:soon.length+' subscriptions expiring soon'}); if(expired.length)new Notification('StreamDesk',{body:expired.length+' subscriptions expired'}); } function _old_checkNotifs_replaced(){ if(!D.sett.notifs||Notification.permission!=='granted')return; var rd=parseInt(D.sett.rd)||3; var soon=D.subs.filter(function(s){var d=DL(s.end);return d>=0&&d<=rd;}); var exp=D.subs.filter(function(s){return DL(s.end)<0&&DL(s.end)>=-1;}); if(soon.length){ new Notification('StreamDesk ⚠️', { body: soon.length+' اشتراك هينتهي خلال '+rd+' أيام', icon: '' }); } if(exp.length){ new Notification('StreamDesk 🔴', { body: exp.length+' اشتراك انتهى', icon: '' }); } } // Users CRUD function openAddUser(){ document.getElementById('mUserT').textContent='إضافة يوزر'; document.getElementById('usrId').value=''; document.getElementById('usrName').value=''; document.getElementById('usrUname').value=''; document.getElementById('usrPwd').value=''; document.getElementById('usrRole').value='staff'; openModal('mUser'); } function openEditUser(id){ var u=D.users.find(function(x){return x.id==id;}); if(!u)return; document.getElementById('mUserT').textContent='تعديل يوزر'; document.getElementById('usrId').value=id; document.getElementById('usrName').value=u.name||''; document.getElementById('usrUname').value=u.username||''; document.getElementById('usrPwd').value=u.password||''; document.getElementById('usrRole').value=u.role||'staff'; openModal('mUser'); } function saveSlot(){ var id=document.getElementById('usrId').value; var obj={id:id||UID(),name:document.getElementById('usrName').value.trim(),username:document.getElementById('usrUname').value.trim(),password:document.getElementById('usrPwd').value.trim(),role:document.getElementById('usrRole').value}; if(!obj.name){toast('ادخل الاسم');return;} if(id){D.users[D.users.findIndex(function(x){return x.id==id;})]=obj;} else D.users.push(obj); SA();closeModal('mSlot');renderSettings();toast('تم الحفظ ✓'); } function delUser(id){ if(!confirm('حذف؟'))return; D.users=D.users.filter(function(x){return x.id!=id;}); SA();renderSettings(); } // Services CRUD function openAddSvc(){ document.getElementById('mSvcT').textContent='إضافة خدمة'; document.getElementById('svcId').value=''; document.getElementById('svcName').value=''; document.getElementById('svcColor').value='#E50914'; document.getElementById('svcIcon').value='ti-device-tv'; document.getElementById('svcDefaultPrice').value=''; openModal('mSvc'); } function openEditSvc(id){ var sv=D.svcs.find(function(x){return x.id==id;}); if(!sv)return; document.getElementById('mSvcT').textContent='تعديل خدمة'; document.getElementById('svcId').value=id; document.getElementById('svcName').value=sv.name||''; document.getElementById('svcColor').value=sv.color||'#E50914'; document.getElementById('svcIcon').value=sv.icon||'ti-device-tv'; document.getElementById('svcDefaultPrice').value=sv.defaultPrice||''; openModal('mSvc'); } function saveSvc(){ var id=document.getElementById('svcId').value; var obj={id:id||UID(),name:document.getElementById('svcName').value.trim(),color:document.getElementById('svcColor').value,icon:document.getElementById('svcIcon').value.trim()||'ti-device-tv',mx:5,defaultPrice:parseFloat(document.getElementById('svcDefaultPrice').value)||0}; if(!obj.name){toast('ادخل اسم');return;} if(id){D.svcs[D.svcs.findIndex(function(x){return x.id==id;})]=obj;} else D.svcs.push(obj); SA();closeModal('mSvc');renderSettings();toast('تم الحفظ ✓'); } function delSvc(id){ if(!confirm('حذف؟'))return; D.svcs=D.svcs.filter(function(x){return x.id!=id;}); SA();renderSettings(); } // Expense cats CRUD function openAddEcat(){ document.getElementById('ecId').value=''; document.getElementById('ecName').value=''; document.getElementById('ecColor').value='#888'; document.getElementById('ecIcon').value='ti-receipt'; openModal('mEcat'); } function openEditEcat(id){ var c=D.ecats.find(function(x){return x.id==id;}); if(!c)return; document.getElementById('ecId').value=id; document.getElementById('ecName').value=c.name||''; document.getElementById('ecColor').value=c.color||'#888'; document.getElementById('ecIcon').value=c.icon||'ti-receipt'; openModal('mEcat'); } function saveEcat(){ var id=document.getElementById('ecId').value; var obj={id:id||UID(),name:document.getElementById('ecName').value.trim(),color:document.getElementById('ecColor').value,icon:document.getElementById('ecIcon').value.trim()||'ti-receipt'}; if(!obj.name){toast('ادخل اسم');return;} if(id){D.ecats[D.ecats.findIndex(function(x){return x.id==id;})]=obj;} else D.ecats.push(obj); SA();closeModal('mEcat');renderSettings();toast('تم الحفظ ✓'); } function delEcat(id){ if(!confirm('حذف؟'))return; D.ecats=D.ecats.filter(function(x){return x.id!=id;}); SA();renderSettings(); } // ===================== GLOBAL SEARCH ===================== function globalSearch(q){ var el=document.getElementById('gsres'); if(!q||q.length<2){el.innerHTML='';return;} q=q.toLowerCase(); var res=[]; D.subs.forEach(function(s){ if((s.name||'').toLowerCase().includes(q)||(s.phone||'').includes(q)){ res.push({type:'sub',label:s.name+' — '+(s.phone||''),id:s.id}); } }); D.emails.forEach(function(e){ if((e.email||'').toLowerCase().includes(q)){res.push({type:'email',label:e.email,id:e.id});} }); D.probs.forEach(function(p){ if((p.title||'').toLowerCase().includes(q)){res.push({type:'prob',label:p.title,id:p.id});} }); if(!res.length){el.innerHTML='
لا نتائج
';return;} el.innerHTML=res.slice(0,8).map(function(r){ var ico={sub:'ti-list',email:'ti-mail',prob:'ti-alert-circle'}[r.type]||'ti-search'; return '
'+E(r.label)+'
'; }).join(''); } function gotoResult(type,id){ document.getElementById('gsres').innerHTML=''; document.getElementById('gsrch').value=''; if(type==='sub'){showPage('subs');setTimeout(function(){openEditSub(id);},100);} else if(type==='email'){showPage('emails');setTimeout(function(){openEditEmail(id);},100);} else if(type==='prob'){showPage('problems');setTimeout(function(){openEditProb(id);},100);} } // ============================================================ // CLIENT PROFILE // ============================================================ var _clientId = null; function openClient(subId){ var s=D.subs.find(function(x){return x.id===subId;}); if(!s)return; _clientId=subId; showPage('client'); } function renderClientProfile(s){ var sv=GS(s.svid); var dl=DL(s.end); var el=document.getElementById('clientProfile'); if(!el)return; document.getElementById('clientPageTitle').innerHTML=' '+E(s.name); var h=''; // Header h+='
'; h+='
'; h+='
'; h+='
'+E(s.name)+'
'; h+='
'; if(s.phone){ var num=(s.phone||'').replace(/[^0-9]/g,'').replace(/^0/,'2'); h+=''+E(s.phone)+''; } if(s.email)h+=' '+E(s.email)+''; h+='
'; h+='
'; h+=''; h+=''; h+='
'; // Stats var totalPaid=+(s.price||0)+(s.renewals||[]).reduce(function(a,r){return a+(r.price||0);},0); h+='
'; h+='
الخدمة
'+E(sv.name)+'
'; h+='
الانتهاء
'+FD(s.end)+'
'; h+='
السعر
'+s.price+'ج
'; h+='
التجديدات
'+(s.renewals||[]).length+'
'; if(s.start)h+='
عميل منذ
'+FD(s.start)+'
'; h+='
اجمالي دفع
'+totalPaid+'ج
'; h+='
'; // Notes if(s.note||s.noteInt){ h+='
'; if(s.note)h+='
'+E(s.note)+'
'; if(s.noteInt)h+='
'+E(s.noteInt)+'
'; h+='
'; } // Renewals h+='
'; h+='
سجل التجديدات ('+(s.renewals||[]).length+')
'; if(!(s.renewals||[]).length){ h+='
لا يوجد تجديدات
'; } else { h+='
'; s.renewals.slice().reverse().forEach(function(r,i){ h+='
'; h+='#'+(s.renewals.length-i)+''; h+=''+FD(r.date)+''; h+=''+r.price+'ج'; h+=''+r.dur+' شهر'; if(r.by)h+=''+E(r.by)+''; if(r.note)h+=''+E(r.note)+''; h+='
'; }); h+='
'; } h+='
'; el.innerHTML=h; } function copyClientData(){ var s=D.subs.find(function(x){return x.id===_clientId;}); if(!s)return; var sv=GS(s.svid); var lines=['الاسم: '+s.name,'الخدمة: '+sv.name]; if(s.email)lines.push('الايميل: '+s.email); lines.push('تاريخ الانتهاء: '+FD(s.end)); if(s.note)lines.push('ملاحظة: '+s.note); cpCl(lines.join('\n'),'تم نسخ بيانات العميل'); } // ============================================================ // LATE PAYMENT // ============================================================ function toggleLate(subId){ var s=D.subs.find(function(x){return x.id===subId;}); if(!s)return; s.late=!s.late; SA();renderSubs(); toast(s.late?'تم تعليم كمتاخر في الدفع':'تم الغاء التعليم'); } // ============================================================ // SERVICE STATS // ============================================================ function renderSvcStats(){ var el=document.getElementById('svcStatsContent'); if(!el)return; var h=''; D.svcs.forEach(function(sv){ var subs=D.subs.filter(function(s){return s.svid==sv.id;}); var active=subs.filter(function(s){return DL(s.end)>=0;}); var rev=subs.reduce(function(a,s){ return a+(+(s.price||0))+(s.renewals||[]).reduce(function(b,r){return b+(r.price||0);},0); },0); h+='
'; h+='
'; h+='
'; h+='
'+E(sv.name)+'
'; h+='
'; h+='
اجمالي
'+subs.length+'
'; h+='
نشطة
'+active.length+'
'; h+='
الايرادات
'+rev+'ج
'; h+='
'; }); el.innerHTML=h||'
لا توجد خدمات
'; } // ============================================================ // DUPLICATE PHONE CHECK // ============================================================ function checkDupPhone(phone){ var el=document.getElementById('dupPhoneWarn'); if(!el)return; var p=(phone||'').replace(/[^0-9]/g,''); if(p.length<10){el.style.display='none';return;} var curId=document.getElementById('mSubId').value; var dups=D.subs.filter(function(s){ return s.id!==curId&&(s.phone||'').replace(/[^0-9]/g,'')===p&&DL(s.end)>=0; }); if(!dups.length){el.style.display='none';return;} var h='
'; h+='هذا الرقم مسجل مسبقاً
'; dups.forEach(function(s){ var sv=GS(s.svid); h+='
'; h+=''+E(s.name)+''; h+=''+E(sv.name)+''; h+='
'; }); h+='
يمكن اضافة خدمة جديدة لنفس الرقم
'; el.innerHTML=h; el.style.display='block'; } // ============================================================ // RECURRING EXPENSES // ============================================================ function generateRecurringExps(){ var today=T(); var thisMonth=today.slice(0,7); D.exps.forEach(function(e){ if(!e.rec||!e.date)return; var already=D.exps.some(function(x){ return x.parentId===e.id&&(x.date||'').slice(0,7)===thisMonth; }); if(already)return; if(e.endDate&&today>e.endDate)return; if(e.date.slice(0,7)>=thisMonth)return; D.exps.push({id:UID(),catId:e.catId,amt:e.amt, date:thisMonth+e.date.slice(7),note:e.note||'',rec:false,parentId:e.id}); }); SA(); } // ============================================================ // WA BULK // ============================================================ function openWaBulk(){ var rd=parseInt(D.sett.rd)||3; var targets=D.subs.filter(function(s){var d=DL(s.end);return s.phone&&(d<0||d<=rd);}); if(!targets.length){toast('مفيش اشتراكات محتاجة تذكير');return;} var h='
'; h+='
'+targets.length+' عميل:
'; targets.forEach(function(s){ var sv=GS(s.svid); var d=DL(s.end); var num=(s.phone||'').replace(/[^0-9]/g,'').replace(/^0/,'2'); var url='https://wa.me/'+num+'?text='+encodeURIComponent(getWaMsg(sv,d)); h+=''; h+=''; h+='
'+E(s.name)+'
'; h+='
'+E(sv.name)+' - '+(d<0?'منتهي':''+d+' يوم')+'
'; h+='
'; }); h+='
'; document.getElementById('waBulkBody').innerHTML=h; openModal('mWaBulk'); } // ============================================================ // MULTI-PLATFORM EMAIL // ============================================================ function cpEmail(id){ var em=D.emails.find(function(x){return x.id===id;}); if(em&&em.pass)cpCl(em.pass,'تم نسخ الباسورد'); } function fillEmPlatformBtns(selectedIds){ var el=document.getElementById('emPlatformBtns'); if(!el)return; var ids=(selectedIds||'').split(',').filter(Boolean); var h=''; D.svcs.forEach(function(sv){ var sel=ids.indexOf(String(sv.id))>-1; h+=''; }); el.innerHTML=h; document.getElementById('emPlatformIds').value=ids.join(','); } function toggleEmPlatform(svId){ var inp=document.getElementById('emPlatformIds'); var ids=inp.value.split(',').filter(Boolean); var idx=ids.indexOf(String(svId)); if(idx>-1)ids.splice(idx,1); else ids.push(String(svId)); inp.value=ids.join(','); fillEmPlatformBtns(inp.value); } // ============================================================ // CONFIRM PAY // ============================================================ function confirmPay(id){ var s=D.subs.find(function(x){return x.id===id;}); if(!s)return; s.paid=true;SA(); logIt('pay','تاكيد دفع: '+s.name); renderSubs();toast('تم'); } function onSvcChange(){ var svid=document.getElementById('fSvc').value; if(!svid)return; var sv=GS(svid); var priceEl=document.getElementById('fPrice'); if(priceEl&&sv.defaultPrice&&!priceEl.value){ priceEl.value=sv.defaultPrice; } } function loadUsers(){} // ============================================================ // MY ACCOUNTS (حساباتي) // ============================================================ function checkMyAccsAlert(){ var el=document.getElementById('myAccAlert'); if(!el)return; var rd=parseInt(D.sett.rd)||3; var expiring=D.myaccs.filter(function(a){var d=DL(a.renew);return d>=0&&d<=rd;}); var expired=D.myaccs.filter(function(a){return DL(a.renew)<0;}); if(!expiring.length&&!expired.length){el.style.display='none';return;} var h=''; if(expired.length)h+=''+expired.length+' حساب انتهى!'; if(expiring.length)h+=''+expiring.length+' حساب هينتهي قريباً —'; expiring.concat(expired).slice(0,3).forEach(function(a){ var sv=GS(a.svid); h+=''+E(sv.name)+''; }); h+='عرض الكل ←'; el.innerHTML=h; el.style.display='flex'; } function renderMyAccs(){ updateMyAccCnt(); // Fill svc selects var svSel=document.getElementById('maSvc'); if(svSel&&svSel.options.length<=1){D.svcs.forEach(function(sv){svSel.innerHTML+='';});} var svfSel=document.getElementById('myAccSvf'); if(svfSel&&svfSel.options.length<=1){D.svcs.forEach(function(sv){svfSel.innerHTML+='';});} var q=(document.getElementById('myAccSrch')&&document.getElementById('myAccSrch').value||'').toLowerCase(); var svf=document.getElementById('myAccSvf')&&document.getElementById('myAccSvf').value||''; var el=document.getElementById('myAccList'); if(!el)return; var filtAccs=D.myaccs.filter(function(a){ if(svf&&a.svid!=svf)return false; if(q&&!(a.email||'').toLowerCase().includes(q)&&!GS(a.svid).name.toLowerCase().includes(q))return false; return true; }); if(!filtAccs.length){ el.innerHTML='
لا توجد حسابات مضافة
أضف حساباتك على المنصات عشان تتذكر تجدد
'; return; } var rd=parseInt(D.sett.rd)||3; var sorted=filtAccs.slice().sort(function(a,b){return new Date(a.renew)-new Date(b.renew);}); var h=''; sorted.forEach(function(a){ var sv=GS(a.svid); var dl=DL(a.renew); var status=dl<0?'منتهي':(dl===0?'ينتهي اليوم!':('متبقي '+dl+' يوم')); var statusColor=dl<0?'var(--red)':(dl<=rd?'#d97706':'var(--green)'); h+='
'; h+='
'; h+='
'; h+='
'; h+='
'+E(sv.name)+'
'; h+='
'; h+=''+status+''; h+=''+FD(a.renew)+''; if(a.price)h+=''+a.price+'ج'; h+='
'; h+='
'; h+='
'; h+='
'; h+='
'; h+='
'; // Details h+='
'; // Email if(a.email){ h+='
'; h+=''; h+=''+E(a.email)+''; h+=''; h+='
'; } // Email password if(a.emailPass){ h+='
'; h+=''; h+='باسورد الإيميل:'; h+=''+E(a.emailPass)+''; h+=''; h+='
'; } // Platform password if(a.svcPass){ h+='
'; h+=''; h+='باسورد '+E(sv.name)+':'; h+=''+E(a.svcPass)+''; h+=''; h+='
'; } if(a.note)h+='
'+E(a.note)+'
'; h+='
'; h+='
'; }); el.innerHTML=h; } function openAddMyAcc(){ document.getElementById('mMyAccT').textContent='إضافة حساب'; document.getElementById('maId').value=''; document.getElementById('maEmail').value=''; document.getElementById('maEmailPass').value=''; document.getElementById('maSvcPass').value=''; document.getElementById('maPrice').value=''; document.getElementById('maNote').value=''; document.getElementById('maRenew').value=''; // Fill svc select var sel=document.getElementById('maSvc'); sel.innerHTML=''; D.svcs.forEach(function(sv){sel.innerHTML+='';}); openModal('mMyAcc'); } function openEditMyAcc(id){ var a=D.myaccs.find(function(x){return x.id===id;}); if(!a)return; document.getElementById('mMyAccT').textContent='تعديل حساب'; document.getElementById('maId').value=id; document.getElementById('maEmail').value=a.email||''; document.getElementById('maEmailPass').value=a.emailPass||''; document.getElementById('maSvcPass').value=a.svcPass||''; document.getElementById('maPrice').value=a.price||''; document.getElementById('maNote').value=a.note||''; document.getElementById('maRenew').value=a.renew||''; var sel=document.getElementById('maSvc'); sel.innerHTML=''; D.svcs.forEach(function(sv){sel.innerHTML+='';}); sel.value=a.svid||''; openModal('mMyAcc'); } function saveMyAcc(){ var id=document.getElementById('maId').value; var svid=document.getElementById('maSvc').value; if(!svid){toast('اختر المنصة');return;} var renew=document.getElementById('maRenew').value; if(!renew){toast('ادخل تاريخ التجديد');return;} var maEmail=document.getElementById('maEmail').value.trim(); var curMaId=document.getElementById('maId').value; if(maEmail&&svid){ var dupMa=D.myaccs.find(function(x){return x.id!==curMaId&&x.email===maEmail&&x.svid==svid;}); if(dupMa){if(!confirm('هذا الإيميل مسجل بالفعل على نفس المنصة. هل تريد الاستمرار؟'))return;} } var obj={ id:id||UID(), svid:svid, email:document.getElementById('maEmail').value.trim(), emailPass:document.getElementById('maEmailPass').value.trim(), svcPass:document.getElementById('maSvcPass').value.trim(), price:parseFloat(document.getElementById('maPrice').value)||0, renew:renew, note:document.getElementById('maNote').value.trim() }; if(id){D.myaccs[D.myaccs.findIndex(function(x){return x.id===id;})]=obj;} else D.myaccs.push(obj); SA();closeModal('mMyAcc');renderMyAccs();checkMyAccsAlert();toast('تم الحفظ'); } function delMyAcc(id){ if(!confirm('حذف الحساب؟'))return; D.myaccs=D.myaccs.filter(function(x){return x.id!==id;}); SA();renderMyAccs();checkMyAccsAlert();toast('تم الحذف'); } function openMyAccRenew(id){ var a=D.myaccs.find(function(x){return x.id===id;}); if(!a)return; var sv=GS(a.svid); document.getElementById('mMyAccRenewT').textContent='تجديد - '+sv.name; document.getElementById('marId').value=id; document.getElementById('marPrice').value=a.price||''; // Suggest next month from current renew date var base=DL(a.renew)>=0?a.renew:T(); document.getElementById('marDate').value=CE(base,1); openModal('mMyAccRenew'); } function doMyAccRenew(){ var id=document.getElementById('marId').value; var a=D.myaccs.find(function(x){return x.id===id;}); if(!a)return; a.renew=document.getElementById('marDate').value; a.price=parseFloat(document.getElementById('marPrice').value)||a.price; SA();closeModal('mMyAccRenew');renderMyAccs();checkMyAccsAlert(); toast('تم التجديد'); } // ============================================================ // DAILY SUMMARY NOTIFICATION // ============================================================ function showDailySummary(){ var rd=parseInt(D.sett.rd)||3; var today=T(); var endToday=D.subs.filter(function(s){return s.end===today;}); var endSoon=D.subs.filter(function(s){var d=DL(s.end);return d>0&&d<=rd;}); var expired=D.subs.filter(function(s){return DL(s.end)<0&&DL(s.end)>=-1;}); var myExpiring=D.myaccs.filter(function(a){var d=DL(a.renew);return d>=0&&d<=rd;}); var myExpired=D.myaccs.filter(function(a){return DL(a.renew)<0;}); var parts=[]; if(endToday.length)parts.push(endToday.length+' اشتراك ينتهي اليوم'); if(expired.length)parts.push(expired.length+' اشتراك انتهى امس'); if(endSoon.length)parts.push(endSoon.length+' اشتراك ينتهي قريباً'); if(myExpiring.length)parts.push(myExpiring.length+' حساب من حساباتك قريب ينتهي'); if(myExpired.length)parts.push(myExpired.length+' حساب من حساباتك انتهى'); if(!parts.length){ toast('كل حاجة تمام اليوم ✓'); return; } // Show summary modal var h='
'; if(endToday.length){ h+='
'; h+='
تنتهي اليوم ('+endToday.length+')
'; endToday.forEach(function(s){var sv=GS(s.svid);h+='
'+E(sv.name)+''+E(s.name)+''+s.phone+'
';}); h+='
'; } if(expired.length){ h+='
'; h+='
انتهى امس ('+expired.length+')
'; expired.forEach(function(s){var sv=GS(s.svid);h+='
'+E(sv.name)+''+E(s.name)+'
';}); h+='
'; } if(endSoon.length){ h+='
'; h+='
ينتهي قريباً ('+endSoon.length+')
'; endSoon.slice(0,5).forEach(function(s){var sv=GS(s.svid);var d=DL(s.end);h+='
'+E(sv.name)+''+E(s.name)+''+d+' يوم
';}); if(endSoon.length>5)h+='
و '+(endSoon.length-5)+' آخرين...
'; h+='
'; } if(myExpiring.length||myExpired.length){ h+='
'; h+='
حساباتك الأساسية
'; myExpired.forEach(function(a){var sv=GS(a.svid);h+='
'+E(sv.name)+' - انتهى!
';}); myExpiring.forEach(function(a){var sv=GS(a.svid);var d=DL(a.renew);h+='
'+E(sv.name)+' - '+d+' يوم
';}); h+='
'; } h+='
'; document.getElementById('dailySumBody').innerHTML=h; document.getElementById('mDailySummary').classList.add('open'); } // ============================================================ // MY ACCOUNTS COUNTER // ============================================================ function updateMyAccCnt(){ var el=document.getElementById('myAccCnt'); if(!el)return; var rd=parseInt(D.sett.rd)||3; var cnt=D.myaccs.filter(function(a){return DL(a.renew)<=rd;}).length; el.innerHTML=cnt?''+cnt+'':''; } // ============================================================ // LOG DATE FILTER UPDATE // ============================================================ function filterLog(type){ var today=T(); if(type==='today'){ _logDateFilter=today; document.getElementById('logFrom').value=today; document.getElementById('logTo').value=today; } else if(type==='week'){ var d=new Date();d.setDate(d.getDate()-7); var from=d.toISOString().slice(0,10); _logDateFilter=''; document.getElementById('logFrom').value=from; document.getElementById('logTo').value=today; } else if(type==='all'){ _logDateFilter=''; document.getElementById('logFrom').value=''; document.getElementById('logTo').value=''; } else if(type==='custom'){ _logDateFilter=''; } renderLog(); } // ============================================================ // EXPORT EXPIRED LIST (CSV) // ============================================================ function exportExpiredCSV(){ var expired=D.subs.filter(function(s){return DL(s.end)<0;}); if(!expired.length){toast('مفيش اشتراكات منتهية');return;} var rows=[['الاسم','الموبايل','الخدمة','تاريخ الانتهاء','السعر']]; expired.forEach(function(s){ var sv=GS(s.svid); rows.push([s.name||'',s.phone||'',sv.name,s.end||'',s.price||0]); }); var csv=rows.map(function(r){return r.map(function(v){return '"'+String(v).replace(/"/g,'""')+'"';}).join(',');}).join('\n'); var blob=new Blob(['\uFEFF'+csv],{type:'text/csv;charset=utf-8'}); var a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='expired_'+T()+'.csv'; a.click(); URL.revokeObjectURL(a.href); toast('تم التصدير ✓'); } // ============================================================ // PRINT CLIENT CARD // ============================================================ function printClientCard(){ var s=D.subs.find(function(x){return x.id===_clientId;}); if(!s)return; var sv=GS(s.svid); var dl=DL(s.end); var status=dl<0?'منتهي':(dl===0?'ينتهي اليوم':('متبقي '+dl+' يوم')); var w=window.open('','_blank'); w.document.write(''+s.name+''); w.document.write(''); w.document.write('
'); w.document.write('
'+s.name+'
'); w.document.write('
الخدمة'+sv.name+'
'); if(s.phone)w.document.write('
الموبايل'+s.phone+'
'); if(s.email)w.document.write('
الإيميل'+s.email+'
'); w.document.write('
تاريخ الانتهاء'+FD(s.end)+'
'); w.document.write('
الحالة'+status+'
'); w.document.write('
السعر'+s.price+'ج
'); if(s.note)w.document.write('
ملاحظة'+s.note+'
'); var totalPaid=+(s.price||0)+(s.renewals||[]).reduce(function(a,r){return a+(r.price||0);},0); w.document.write('
إجمالي المدفوع'+totalPaid+'ج
'); w.document.write('
'); w.document.write(''); w.document.write(' '); w.document.close(); setTimeout(function(){w.print();},300); } // ============================================================ // PROBLEM SOLUTION TOGGLE // ============================================================ function toggleProbSolution(){ var status=document.getElementById('probStatus').value; var fld=document.getElementById('probSolutionFld'); if(fld)fld.style.display=status==='solved'?'block':'none'; } // ============================================================ // REPORTS FILTER // ============================================================ var _repFilter = 'all'; function setRepFilter(f){ _repFilter=f; ['all','active','exp'].forEach(function(id){ var btn=document.getElementById('rf'+id); if(btn){btn.style.background=f===id?'var(--text)':'';btn.style.color=f===id?'#fff':'';} }); renderReports(); } // ============================================================ // CLEANUP OLD SUBS // ============================================================ function cleanupOldSubs(){ var days=parseInt(document.getElementById('cleanupDays').value)||30; var cutoff=new Date();cutoff.setDate(cutoff.getDate()-days); var cutoffStr=cutoff.toISOString().slice(0,10); var toDelete=D.subs.filter(function(s){return s.end&&s.end=cutoffStr;}); SA();renderSubs();renderStats(); toast('تم حذف '+toDelete.length+' اشتراك ✓'); } // ============================================================ // BACKUP REMINDER // ============================================================ function checkBackupReminder(){ var lastBackup=localStorage.getItem('sd_last_backup'); if(!lastBackup){ localStorage.setItem('sd_last_backup', T()); return; } var daysSince=Math.floor((new Date()-new Date(lastBackup))/864e5); if(daysSince>=7){ var bar=document.createElement('div'); bar.style.cssText='background:#fef3c7;border-bottom:1px solid #fbbf24;padding:.5rem 1rem;font-size:12px;color:#92400e;display:flex;align-items:center;gap:8px;justify-content:space-between'; bar.innerHTML='آخر باكب كان منذ '+daysSince+' يوم — اعمل باكب دلوقتي!' +'
' +'
'; var app=document.getElementById('appMain'); if(app)app.insertBefore(bar,app.firstChild); } } // ============================================================ // WA TEMPLATE // ============================================================ var DEFAULT_WA_TEMPLATE='مرحباً 👋\nاشتراكك في *{service}* {status}\n{action}'; function getWaMsg(sv, dl){ var template=D.sett.waTemplate||DEFAULT_WA_TEMPLATE; var status=dl<0?'انتهى!':'هينتهي خلال *'+dl+(dl===1?' يوم':' أيام')+'*'; var action=dl<0?'جدد دلوقتي عشان ترجعلك الخدمة 🙏':'جدد قبل الانقطاع 😊'; return template .replace(/{service}/g,sv.name) .replace(/{days}/g,Math.max(0,dl)) .replace(/{status}/g,status) .replace(/{action}/g,action); } function saveWaTemplate(){ var t=document.getElementById('waTemplate').value.trim(); if(!t){toast('ادخل رسالة');return;} D.sett.waTemplate=t;SA();toast('تم حفظ الرسالة ✓'); } function resetWaTemplate(){ D.sett.waTemplate='';SA(); document.getElementById('waTemplate').value=DEFAULT_WA_TEMPLATE; toast('تم الإعادة للافتراضي'); } // ============================================================ // QUICK NOTE // ============================================================ function quickNote(subId){ var s=D.subs.find(function(x){return x.id===subId;}); if(!s)return; var sv=GS(s.svid); document.getElementById('qnId').value=subId; document.getElementById('qnSubInfo').innerHTML=''+E(sv.name)+' — '+E(s.name); document.getElementById('qnText').value=s.note||''; document.getElementById('qnIntText').value=s.noteInt||''; openModal('mQuickNote'); setTimeout(function(){document.getElementById('qnText').focus();},100); } function saveQuickNote(){ var id=document.getElementById('qnId').value; var s=D.subs.find(function(x){return x.id===id;}); if(!s)return; s.note=document.getElementById('qnText').value.trim(); s.noteInt=document.getElementById('qnIntText').value.trim(); SA();closeModal('mQuickNote');renderSubs();toast('تم الحفظ ✓'); } // ============================================================ // STAFF FILTER IN SUBS // ============================================================ // ===================== MODAL HELPERS ===================== function openModal(id){document.getElementById(id).classList.add('open');} function closeModal(id){document.getElementById(id).classList.remove('open');} function togglePw(id){var el=document.getElementById(id);el.type=el.type==='password'?'text':'password';} // Auto restore session on load document.addEventListener('DOMContentLoaded',function(){checkAutoSession();}); // Close modal on background click document.querySelectorAll('.modal-bg').forEach(function(mb){ mb.addEventListener('click',function(e){if(e.target===mb)mb.classList.remove('open');}); }); // Keyboard shortcuts document.addEventListener('keydown',function(e){ if(e.target.tagName==='INPUT'||e.target.tagName==='TEXTAREA'||e.target.tagName==='SELECT')return; if(e.ctrlKey&&e.key==='n'){e.preventDefault();openAddSub();} if(e.key==='Escape'){document.querySelectorAll('.modal-bg.open').forEach(function(m){m.classList.remove('open');});} });