ديار
🏠
ديار
حمّل التطبيق على موبايلك وتصفح العقارات بسهولة في أي وقت
سريع
📶يشتغل أوفلاين
🔔إشعارات
🆓مجاني
ديار
Diyar Real Estate
🏠
أهلاً بك 👋
سجّل دخولك برقم هاتفك
للوصول إلى أفضل عقارات مطروح
📱
👁️
🏖️ مرسى مطروح — ساحل المتوسط
ديار 🏠
منصتك الأولى للعقارات على ساحل البحر الأبيض
🌊 البحر اليوم: هادئ ومناسب للسباحة

ماذا تريد اليوم؟

⛱️
أنا مصيف
إيجار يومي · أسبوعي · شهري صيفي
🏠
مقيم / مستثمر
تمليك · إيجار سنوي · شتوي · أراضي · محلات
🏢
أنشئ حساب لترويج عقاراتك
سمسار أو مالك — أعلن عن عقاراتك مجاناً
🎉
تم استلام إعلانك!
إعلانك قيد المراجعة
سيتم إدراجه في أسرع وقت 🏠
📋 إعلاناتي
إعلاناتك المرسلة والمنشورة
خيارات المصيف ⛱️
اختر نوع الإيجار
سكن واستثمار 🏘️
إيجارات طويلة الأمد وتمليك وأراضي
الإعلانات
💰 فلتر السعر (ج.م)
📝 أضف إعلانك مجاناً
🏢
أنشئ حسابك
سجّل بياناتك لترويج عقاراتك بسهولة
📷
✏️
اضغط لإضافة صورتك
❤️ المفضلة
العقارات التي حفظتها
🏅
توثيق الحساب
احصل على شارة التوثيق الذهبية
⏳ جاري تحميل البيانات...
/* ════════ SPLASH SCREEN ════════ */ (function(){ // فقط في وضع PWA standalone var isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true; if(!isStandalone) return; var splash = document.getElementById('splash-screen'); if(!splash) return; // أظهر الـ splash splash.classList.add('splash-visible'); // اخفيه بعد 1500ms بـ fade ناعم 300ms ثم احذفه من DOM setTimeout(function(){ splash.classList.add('hidden'); setTimeout(function(){ if(splash.parentElement) splash.parentElement.removeChild(splash); }, 300); }, 1500); })(); /* ════════ CONFIG ════════ */ var ADMIN_PHONE = '201040986955'; var CLOUDINARY_CLOUD = 'dkq9kctcv'; var CLOUDINARY_PRESET = 'fares7877'; var ADMIN_PASS = 'fares2025'; var ADMIN_NUMBER = '01040986955'; // local format /* ════════ STATE ════════ */ var propType='', dealType='', nearSea='', finishVal='', aptFurnish='', aptPayment=''; var selectedChips={}, uploadedPhotos=[]; var currentFilter='الكل'; var currentSort='default'; var headerTaps=0, headerTimer; var currentUser = null; // {phone, isAdmin} var _otpCode = ''; var featuredEnabled = false; /* ════════ AD CODE COUNTER ════════ */ function getNextAdCode(){ var n = parseInt(localStorage.getItem('fares_ad_counter')||'100') + 1; localStorage.setItem('fares_ad_counter', n); return 'MT-' + n; } /* ════════ VIEWS ════════ */ function loadViews(){ try{return JSON.parse(localStorage.getItem('fares_views')||'{}')}catch(e){return {};} } function saveViews(v){ localStorage.setItem('fares_views', JSON.stringify(v)); } function getViews(id){ var v=loadViews(); return v[id]||0; } function incrementViews(id){ var v=loadViews(); v[id]=(v[id]||0)+1; saveViews(v); return v[id]; } /* ════════ FAVORITES ════════ */ function loadFavs(){ try{return JSON.parse(localStorage.getItem('fares_favs')||'[]')}catch(e){return [];} } function saveFavs(f){ localStorage.setItem('fares_favs', JSON.stringify(f)); } function isFav(id){ return loadFavs().indexOf(id)!==-1; } function toggleFav(id, event){ if(event) event.stopPropagation(); var f=loadFavs(), idx=f.indexOf(id); if(idx===-1){ f.push(id); saveFavs(f); toast('❤️ أُضيف للمفضلة'); } else { f.splice(idx,1); saveFavs(f); toast('💔 أُزيل من المفضلة'); } var btn=document.getElementById('fav-'+id); if(btn){ btn.textContent=isFav(id)?'❤️':'🤍'; btn.classList.toggle('on',isFav(id)); } updateFavsCard(); } function updateFavsCard(){ var f=loadFavs(), card=document.getElementById('favs-card'); if(!card) return; if(f.length>0){ card.style.display='flex'; document.getElementById('favs-card-sub').textContent=f.length+' عقار محفوظ'; } else card.style.display='none'; } function renderFavs(){ var f=loadFavs(), db=loadDB(); var favAds=(db.approved||[]).filter(a=>f.indexOf(a.id)!==-1); var sub=document.getElementById('favs-sub'), grid=document.getElementById('favs-grid'); if(!favAds.length){ sub.textContent=''; grid.innerHTML='
🤍
لا توجد مفضلات بعد
اضغط ❤️ على أي إعلان لحفظه
'; return; } sub.textContent = favAds.length + ' عقار محفوظ'; grid.innerHTML = buildAdCards(favAds); } var transferPhoto = null; /* ════════ SUPABASE CONFIG ════════ */ var SUPABASE_URL = 'https://pmraekoodbxgnybpvkzg.supabase.co'; var SUPABASE_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InBtcmFla29vZGJ4Z255YnB2a3pnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzMzMTk5MDksImV4cCI6MjA4ODg5NTkwOX0.f7mYHBT0d_0DHrC_o6n6MZeQz1B5RcHkklP6mZJXXjY'; async function sbFetch(path, opts, retries){ retries = retries || 0; var controller = new AbortController(); var timeout = retries > 0 ? 12000 : 8000; // أطول للمحاولات التانية var timer = setTimeout(function(){ controller.abort(); }, timeout); try{ var res = await fetch(SUPABASE_URL + '/rest/v1/' + path, Object.assign({ signal: controller.signal, headers: { 'apikey': SUPABASE_KEY, 'Authorization': 'Bearer ' + SUPABASE_KEY, 'Content-Type': 'application/json', 'Prefer': 'return=representation' } }, opts)); clearTimeout(timer); if(!res.ok){ // 429 = rate limit, ننتظر if(res.status === 429 && retries < 2){ await new Promise(function(r){ setTimeout(r, 2000*(retries+1)); }); return sbFetch(path, opts, retries+1); } return null; } try{ return await res.json(); }catch(e){ return null; } } catch(err){ clearTimeout(timer); // retry عند انقطاع الشبكة if(retries < 1 && err.name !== 'AbortError'){ await new Promise(function(r){ setTimeout(r, 1500); }); return sbFetch(path, opts, retries+1); } return null; } } /* ════════ STORAGE — Supabase + localStorage fallback ════════ */ var _dbCache = null; async function loadDBAsync(){ try{ var rows = await sbFetch('ads?select=id,data,status&order=created_at.desc'); if(!rows) throw new Error('fail'); var pending = [], approved = []; rows.forEach(function(r){ var ad = Object.assign({}, r.data, {id: r.id, _sbStatus: r.status}); if(r.status === 'approved') approved.push(ad); else pending.push(ad); }); var db = {pending, approved}; localStorage.setItem('fares_ads', JSON.stringify(db)); _dbCache = db; return db; } catch(e){ return JSON.parse(localStorage.getItem('fares_ads')||'{"pending":[],"approved":[]}'); } } function loadDB(){ if(_dbCache) return _dbCache; try{ return JSON.parse(localStorage.getItem('fares_ads')||'{"pending":[],"approved":[]}'); } catch(e){ return {pending:[],approved:[]}; } } async function saveAdToSB(ad, status){ status = status || 'pending'; try{ // upsert await sbFetch('ads', { method: 'POST', headers: { 'apikey': SUPABASE_KEY, 'Authorization': 'Bearer ' + SUPABASE_KEY, 'Content-Type': 'application/json', 'Prefer': 'resolution=merge-duplicates,return=representation' }, body: JSON.stringify({id: ad.id, data: ad, status: status}) }); _dbCache = null; // invalidate cache } catch(e){} } async function deleteAdFromSB(id){ try{ await sbFetch('ads?id=eq.'+id, {method:'DELETE'}); _dbCache = null; } catch(e){} } function saveDB(db){ localStorage.setItem('fares_ads', JSON.stringify(db)); _dbCache = db; } async function loadUsersAsync(){ try{ var rows = await sbFetch('users?select=*'); if(!rows) throw new Error('fail'); localStorage.setItem('fares_users', JSON.stringify(rows)); return rows; } catch(e){ return JSON.parse(localStorage.getItem('fares_users')||'[]'); } } function loadUsers(){ try{ return JSON.parse(localStorage.getItem('fares_users')||'[]'); }catch(e){return [];} } async function saveUserToSB(user){ try{ await sbFetch('users', { method: 'POST', headers:{ 'apikey': SUPABASE_KEY, 'Authorization': 'Bearer ' + SUPABASE_KEY, 'Content-Type': 'application/json', 'Prefer': 'resolution=merge-duplicates,return=representation' }, body: JSON.stringify({phone: user.phone, blocked: user.blocked||false, joined_at: new Date().toISOString()}) }); } catch(e){} } function saveUsers(u){ localStorage.setItem('fares_users',JSON.stringify(u)); } async function loadSettingsAsync(){ try{ var rows = await sbFetch('settings?select=key,value'); if(!rows) throw new Error('fail'); var s = {}; rows.forEach(function(r){ try{ s[r.key]=JSON.parse(r.value); }catch(e){ s[r.key]=r.value; } }); localStorage.setItem('fares_settings', JSON.stringify(s)); return s; } catch(e){ return JSON.parse(localStorage.getItem('fares_settings')||'{}'); } } function loadSettings(){ try{ return JSON.parse(localStorage.getItem('fares_settings')||'{}'); }catch(e){return {};} } async function saveSettingsToSB(s){ try{ var rows = Object.keys(s).map(function(k){ return {key:k, value: JSON.stringify(s[k])}; }); for(var i=0;ip!==phone); // ازل لو موجود phones.unshift(phone); // حطه في الأول phones = phones.slice(0,5); // احتفظ بآخر 5 بس localStorage.setItem('fares_saved_phones', JSON.stringify(phones)); } function loadSavedPhones(){ var phones = getSavedPhones(); var wrap = document.getElementById('saved-phones-wrap'); var list = document.getElementById('saved-phones-list'); if(!phones.length){ wrap.style.display='none'; return; } wrap.style.display='block'; list.innerHTML = phones.map(function(p){ var label = p === '01040986955' ? p + ' 👑' : p; return ''; }).join(''); } function selectSavedPhone(phone){ document.getElementById('otp-phone').value = phone; var pwInp = document.getElementById('otp-password'); if(pwInp) { pwInp.focus(); pwInp.value=''; } } function loginWithPhone(){ var phone = document.getElementById('otp-phone').value.trim(); var password = document.getElementById('otp-password') ? document.getElementById('otp-password').value.trim() : ''; if(!/^(010|011|012|015)\d{8}$/.test(phone)){ toast('⚠️ أدخل رقم هاتف مصري صحيح'); return; } if(!password || password.length < 4){ toast('⚠️ أدخل كلمة مرور (4 أحرف على الأقل)'); return; } var isAdmin = (phone === '01040986955'); if(isAdmin && password !== 'fares2025'){ toast('⚠️ كلمة السر غير صحيحة'); return; } // تحقق من كلمة السر للمستخدمين العاديين var users = loadUsers(); var existingUser = users.find(u => u.phone === phone); if(existingUser && !isAdmin){ // مستخدم موجود - تحقق من كلمة السر if(existingUser.password && existingUser.password !== password){ toast('⚠️ كلمة المرور غلط'); return; } // لو مفيش password محفوظ - حفظ الجديد if(!existingUser.password){ existingUser.password = password; saveUsers(users); saveUserToSB(existingUser); } } else if(!existingUser && !isAdmin){ // مستخدم جديد - سجّله مع كلمة السر var newUser = {phone, password, blocked:false, joinedAt:new Date().toLocaleString('ar-EG')}; users.push(newUser); saveUsers(users); saveUserToSB(newUser); } savePhone(phone); currentUser = {phone, isAdmin}; localStorage.setItem('fares_current_user', JSON.stringify({phone, isAdmin})); document.getElementById('otp-overlay').style.display='none'; updateUserBadge(); updateMyAdsCard(); updateBrokerHomeCard(); // اعرض البطاقة لو موجودة if('Notification' in window && Notification.permission === 'default'){ Notification.requestPermission(); } if(!isAdmin) restoreUserProfile(phone); if(isAdmin){ document.getElementById('admin-fab').style.display='flex'; toast('🎉 مرحباً بك يا أدمن!'); setTimeout(()=>openAdmin(),600); } else { toast('🎉 تم الدخول بنجاح'); } } async function restoreUserProfile(phone){ try{ // تحقق من وجود profile محفوظ بالفعل var existing = loadBrokerProfile(); if(existing && existing.linkedPhone === phone) { updateBrokerHomeCard(); return; } // جيب من Supabase var rows = await sbFetch('users?phone=eq.'+phone+'&select=*'); if(rows && rows.length && rows[0].profile_name){ var row = rows[0]; var profile = { name: row.profile_name, phone: row.profile_phone || phone, accountType: row.profile_type, photo: row.profile_photo || '', linkedPhone: phone }; saveBrokerProfile(profile); updateBrokerHomeCard(); toast('👋 مرحباً '+profile.name+'!'); } } catch(e){} } function sendOTP(){ loginWithPhone(); } function verifyOTP(){} function digitInput(){} function digitBack(){} function skipLogin(){ toast('⚠️ يجب تسجيل الدخول أولاً'); } function backToPhone(){ var _s2=document.getElementById('otp-step2');if(_s2)_s2.classList.remove('active'); var _s1=document.getElementById('otp-step1');if(_s1)_s1.classList.add('active'); } function updateUserBadge(){ if(!currentUser) return; var wrap = document.getElementById('user-badge-wrap'); var txt = document.getElementById('user-badge-text'); wrap.style.display='block'; txt.textContent = currentUser.isAdmin ? '👑 أدمن' : '📱 '+currentUser.phone.slice(-4); } function showUserMenu(){ if(currentUser&¤tUser.isAdmin){openAdmin();return;} var r=confirm('تسجيل الخروج؟'); if(r){currentUser=null;localStorage.removeItem('fares_current_user');document.getElementById('user-badge-wrap').style.display='none';document.getElementById('otp-overlay').style.display='flex';loadSavedPhones();} } /* ════════ FEATURED TOGGLE ════════ */ function toggleFeaturedOption(){ featuredEnabled = !featuredEnabled; var sw = document.getElementById('featured-toggle-sw'); var box = document.getElementById('featured-payment-box'); sw.classList.toggle('on', featuredEnabled); box.style.display = featuredEnabled ? 'block' : 'none'; if(featuredEnabled) updateFormFeaturedPrices(); } function updateFormFeaturedPrices(){ var s = loadSettings(); var price = s.featuredPrice || '50'; var wallet = s.vodafoneNum || '01005581620'; ['form-feat-price-hint','form-feat-price-sub','form-feat-price-pill'].forEach(function(id){ var el=document.getElementById(id); if(el) el.textContent=price; }); var fw=document.getElementById('form-feat-wallet'); if(fw) fw.textContent=wallet; } function sendFeaturedRequest(){ var settings = loadSettings(); var waNum = (settings.adminWa||ADMIN_NUMBER).replace(/^0/,'20'); var price = settings.featuredPrice || '50'; var pl={apt:'شقة',land:'أرض',shop:'محل'}; var dl={sale:'تمليك',rent:'إيجار'}; var name = document.getElementById('owner-name').value.trim() || '—'; var phone = document.getElementById('phone').value.trim() || '—'; var region = document.getElementById('region').value || '—'; var adPrice = document.getElementById('price').value; var size = document.getElementById('size').value; var desc = document.getElementById('desc').value.trim(); var rentType = dealType==='rent'&&propType==='apt' ? document.getElementById('rentType').value : ''; var msg = '⭐ *طلب تمييز إعلان*\n'; msg += '━━━━━━━━━━━━━━━━━\n'; msg += '👤 *المعلن:* ' + name + '\n'; msg += '📞 *الواتساب:* ' + phone + '\n'; msg += '🏠 *النوع:* ' + (pl[propType]||propType||'—') + ' — ' + (dl[dealType]||'—') + (rentType?' ('+rentType+')':'') + '\n'; msg += '📍 *المنطقة:* ' + region + '\n'; if(adPrice) msg += '💰 *السعر:* ' + Number(adPrice).toLocaleString('ar-EG') + ' ج.م\n'; if(size) msg += (propType==='apt'?'🛏 *الغرف:* ':'📐 *المساحة:* ') + size + (propType!=='apt'?' م²':'') + '\n'; if(nearSea) msg += '🌊 *قرب البحر:* ' + nearSea + '\n'; if(finishVal) msg += '🎨 *التشطيب:* ' + finishVal + '\n'; if(desc) msg += '📝 ' + desc + '\n'; msg += '━━━━━━━━━━━━━━━━━\n'; msg += '💳 *تم تحويل ' + price + ' ج.م فودافون كاش*\n'; msg += 'رجاء تمييز الإعلان بالإطار الذهبي ⭐🙏'; window.open('https://wa.me/'+waNum+'?text='+encodeURIComponent(msg),'_blank'); } /* ════════ HELPERS ════════ */ function go(id){ // صفحات تحتاج تسجيل دخول var authRequired=['add','myads','favs','register']; if(authRequired.indexOf(id)!==-1 && !currentUser){ toast('⚠️ سجّل دخولك أولاً'); document.getElementById('otp-overlay').style.display='flex'; loadSavedPhones(); return; } document.querySelectorAll('.screen').forEach(s=>s.classList.remove('active')); document.getElementById('s-'+id).classList.add('active'); if(id==='home'){ resetForm(); updateMyAdsCard(); updateFavsCard(); updateBrokerHomeCard(); } if(id==='add') { updateFormFeaturedPrices(); fillAddFormFromProfile(); } if(id==='register') loadRegisterForm(); if(id==='myads') renderMyAds(); if(id==='favs') renderFavs(); window.scrollTo({top:0,behavior:'smooth'}); } function toast(msg){ var t=document.getElementById('toast-el'); t.textContent=msg; t.classList.add('show'); clearTimeout(t._t); t._t=setTimeout(()=>t.classList.remove('show'),3200); } function hide(id){var e=document.getElementById(id);if(e)e.classList.add('hidden');} function show(id){var e=document.getElementById(id);if(e)e.classList.remove('hidden');} /* ════════ LISTINGS ════════ */ var _currentListingsCat = ''; async function showListings(cat){ _currentListingsCat = cat; go('listings'); currentFilter='الكل'; document.getElementById('listings-title').textContent = getCatLabel(cat); // اعرض loading document.getElementById('listings-grid').innerHTML = '
جاري تحميل الإعلانات...
'; // جيب من Supabase try{ await loadDBAsync(); } catch(e){} renderListings(cat); } function getCatLabel(c){ return { 'يومي':'إيجار يومي 📅','أسبوعي':'إيجار أسبوعي 🗓️', 'شهري (صيفي)':'إيجار شهري صيفي ☀️','شهري (شتوي)':'إيجار شتوي ❄️', 'سنوي':'إيجار سنوي 🏡','تمليك':'شقق تمليك 🔑', 'أرض':'أراضي مباني 🌍','محل':'محلات تجارية 🏪' }[c]||c; } function renderListings(cat){ var db=loadDB(); var all=db.approved||[]; var filtered=all.filter(function(a){ if(cat==='تمليك') return a.dealType==='sale'&&a.propType==='apt'; if(cat==='أرض') return a.propType==='land'; if(cat==='محل') return a.propType==='shop'; return a.rentType===cat; }); _currentListingsData = filtered; _priceFilterActive = false; currentSort = 'default'; var sortBtns = document.querySelectorAll('.sort-btn'); if(sortBtns.length){ sortBtns.forEach(b=>b.classList.remove('on')); sortBtns[0].classList.add('on'); } var clearBtn=document.getElementById('price-filter-clear'); if(clearBtn) clearBtn.style.display='none'; document.getElementById('listings-count').textContent=filtered.length?filtered.length+' إعلان متاح':''; var filEl=document.getElementById('listings-filters'); filEl.innerHTML=''; var regions=['الكل'].concat([...new Set(filtered.map(a=>a.region))]); regions.forEach(function(r){ var b=document.createElement('button'); b.className='filter-btn'+(r===currentFilter?' on':''); b.textContent=r; b.onclick=function(){ currentFilter=r; document.querySelectorAll('.filter-btn').forEach(x=>x.classList.remove('on')); b.classList.add('on'); renderCards(filtered,r); }; filEl.appendChild(b); }); renderCards(filtered,'الكل'); } function setSort(type, btn){ currentSort = type; document.querySelectorAll('.sort-btn').forEach(b=>b.classList.remove('on')); btn.classList.add('on'); renderCards(_currentListingsData, currentFilter); } function renderCards(ads,regionFilter){ var shown=regionFilter==='الكل'?ads:ads.filter(a=>a.region===regionFilter); // ترتيب shown = shown.slice(); if(currentSort==='default'){ shown.sort(function(a,b){return (b.featured?1:0)-(a.featured?1:0);}); } else if(currentSort==='new'){ shown.sort(function(a,b){ var ta=new Date(a.submittedAt||0).getTime()||0; var tb=new Date(b.submittedAt||0).getTime()||0; return tb-ta; }); } else if(currentSort==='cheap'){ shown.sort(function(a,b){return Number(a.price)-Number(b.price);}); } else if(currentSort==='expensive'){ shown.sort(function(a,b){return Number(b.price)-Number(a.price);}); } var grid=document.getElementById('listings-grid'); if(!shown.length){ grid.innerHTML='
🔍
لا توجد إعلانات في هذه الفئة حالياً
كن أول من يضيف إعلان!
'; return; } grid.innerHTML = buildAdCards(shown); } function buildAdCards(ads){ var pe={apt:'🏠',land:'🌍',shop:'🏪'}; return ads.map(function(a){ var isFeatured = !!a.featured; var favActive = isFav(a.id); var isNew = false; try{ var t=new Date(a.submittedAt); isNew=(Date.now()-t.getTime())<48*3600*1000; }catch(e){} var pLabel={apt:'شقة',land:'أرض',shop:'محل'}[a.propType]||'عقار'; var tags=[]; if(a.size) tags.push(a.propType==='apt'?'🛏 '+a.size+' غرف':'📐 '+a.size+' م²'); if(a.nearSea) tags.push('🌊 '+a.nearSea); if(a.floor&&a.floor!=='') tags.push('🏢 دور '+a.floor); var dealBdg=a.dealType==='sale' ?'تمليك' :''+(a.rentType||'إيجار')+''; var topBadges=(isFeatured?'⭐ مميز':'')+(isNew?'✨ جديد':''); var imgSrc=a.photos&&a.photos.length ?'صورة' :''+(pe[a.propType]||'🏠')+''; var aid=a.id, aphone=a.phone; var html='
'; html+='
'+imgSrc; html+='
'; html+='
'+dealBdg+topBadges+'
'; html+=''; html+='
'; html+='
'; html+='
'+pLabel+' · '+a.region+'
'; html+='
📍 '+a.region+' · مطروح
'; html+='
'; html+='
'; html+='
'+Number(a.price).toLocaleString('en-US')+' EGP
'; if(tags.length) html+='
'+tags.map(function(t){return''+t+'';}).join('')+'
'; html+='
'; html+=''; html+='
'; return html; }).join(''); } function recordView(id){ var newCount = incrementViews(id); var el = document.querySelector('#card-'+id+' .listing-views'); if(el) el.textContent = '👁️ '+newCount+' مشاهدة'; } function contactOwner(phone,id,event){ if(event) event.stopPropagation(); var db=loadDB(); var ad=(db.approved||[]).find(a=>a.id===id); if(!ad){toast('⚠️ إعلان غير موجود');return;} var clean=phone.replace(/\s/g,'').replace(/^0/,'20'); var pl={apt:'شقة',land:'أرض',shop:'محل'}; var msg='مرحبا 👋\nشفت إعلانك على موقع *ديار* 🏠\n'; msg+='📌 '+(pl[ad.propType]||'عقار')+' في '+ad.region+'\n'; msg+='💰 '+Number(ad.price).toLocaleString('ar-EG')+' ج.م\n'; if(ad.rentType) msg+='🗓️ '+ad.rentType+'\n'; if(ad.adCode) msg+='🔖 كود الإعلان: #'+ad.adCode+'\n'; msg+='هل هو متاح؟'; window.open('https://wa.me/'+clean+'?text='+encodeURIComponent(msg),'_blank'); } function callOwner(phone,event){ if(event) event.stopPropagation(); window.location.href='tel:'+phone; } function shareAd(id,event){ if(event) event.stopPropagation(); var db=loadDB(); var ad=(db.approved||[]).find(a=>a.id===id); if(!ad){toast('⚠️ إعلان غير موجود');return;} var pl={apt:'شقة',land:'أرض',shop:'محل'}; var txt='🏠 *ديار*\n'; txt+=''+(pl[ad.propType]||'عقار')+' في '+ad.region+'\n'; txt+='💰 '+Number(ad.price).toLocaleString('ar-EG')+' ج.م\n'; if(ad.rentType) txt+='🗓️ '+ad.rentType+'\n'; if(ad.adCode) txt+='🔖 #'+ad.adCode+'\n'; txt+='\nتواصل مع المعلن: 📞 '+ad.phone; if(navigator.share){ navigator.share({title:'ديار',text:txt}).catch(()=>{}); } else { navigator.clipboard.writeText(txt).then(()=>toast('✅ تم نسخ تفاصيل الإعلان')).catch(()=>{ var waNum=(loadSettings().adminWa||ADMIN_NUMBER).replace(/^0/,'20'); window.open('https://wa.me/?text='+encodeURIComponent(txt),'_blank'); }); } } /* ════════ IMAGE SLIDER ════════ */ var _sliderIdx = {}; function sliderMove(id, dir, event){ if(event) event.stopPropagation(); var inner=document.getElementById('slider-inner-'+id); if(!inner) return; var total=inner.children.length; _sliderIdx[id]=(_sliderIdx[id]||0); _sliderIdx[id]=(_sliderIdx[id]+dir+total)%total; sliderApply(id,total); } function sliderGo(id, idx, event){ if(event) event.stopPropagation(); var inner=document.getElementById('slider-inner-'+id); if(!inner) return; _sliderIdx[id]=idx; sliderApply(id,inner.children.length); } function sliderApply(id,total){ var inner=document.getElementById('slider-inner-'+id); var ctr=document.getElementById('slider-ctr-'+id); var slider=document.getElementById('slider-'+id); if(!inner) return; inner.style.transform='translateX('+((_sliderIdx[id]||0)*100)+'%)'; if(ctr) ctr.textContent=(_sliderIdx[id]+1)+' / '+total; if(slider){ slider.querySelectorAll('.img-slider-dot').forEach(function(d,i){ d.classList.toggle('active',i===_sliderIdx[id]); }); } } /* ════════ PRICE FILTER ════════ */ var _priceFilterActive = false; var _currentListingsData = []; function applyPriceFilter(){ var mn=parseFloat(document.getElementById('price-min').value)||0; var mx=parseFloat(document.getElementById('price-max').value)||Infinity; if(mn>mx){toast('⚠️ السعر الأدنى أكبر من الأقصى');return;} _priceFilterActive=true; var clearBtn=document.getElementById('price-filter-clear'); if(clearBtn) clearBtn.style.display='block'; var toShow=_currentListingsData.filter(function(a){ var p=Number(a.price||0); return p>=mn && p<=mx; }); toShow=toShow.filter(a=>currentFilter==='الكل'||a.region===currentFilter); toShow=toShow.slice().sort(function(a,b){return (b.featured?1:0)-(a.featured?1:0);}); var grid=document.getElementById('listings-grid'); document.getElementById('listings-count').textContent=toShow.length+' إعلان متاح'; if(!toShow.length){ grid.innerHTML='
🔍
لا توجد إعلانات بهذا النطاق السعري
'; return; } grid.innerHTML=buildAdCards(toShow); } function clearPriceFilter(){ _priceFilterActive=false; document.getElementById('price-min').value=''; document.getElementById('price-max').value=''; var clearBtn=document.getElementById('price-filter-clear'); if(clearBtn) clearBtn.style.display='none'; renderCards(_currentListingsData,currentFilter); document.getElementById('listings-count').textContent=_currentListingsData.length+' إعلان متاح'; } /* ════════ FORM ════════ */ function selectProp(val){ propType=val; dealType=''; selectedChips={}; nearSea=''; finishVal=''; ['apt','land','shop'].forEach(v=>document.getElementById('btn-'+v).classList.toggle('on',v===val)); ['sale','rent'].forEach(v=>document.getElementById('btn-'+v).classList.remove('on')); ['rest-form','rent-box','svc-box','finish-box','land-note','shop-deal-sec','deal-sec','svc-summary','finish-summary','shop-payment-row'].forEach(id=>hide(id)); document.querySelectorAll('.chip,.sea-btn,.finish-btn').forEach(b=>b.classList.remove('on')); // reset shop payment btns ['btn-shop-sale','btn-shop-rent','btn-pay-cash','btn-pay-install'].forEach(function(id){var b=document.getElementById(id);if(b)b.classList.remove('on');}); if(val==='land'){show('land-note');dealType='sale';showRest();} else if(val==='shop'){show('shop-deal-sec');} else show('deal-sec'); var sl=document.getElementById('size-lbl'),si=document.getElementById('size'); if(val==='apt'){sl.textContent='عدد الغرف';si.placeholder='3';} else{sl.textContent='المساحة (م²)';si.placeholder='200';} document.getElementById('price-lbl').textContent=val==='shop'?'السعر (ج.م)':'السعر (ج.م)'; var d=document.getElementById('desc'); d.placeholder=val==='apt'?'مثلاً: شقة بإطلالة بحرية، دور ثالث...':val==='land'?'مثلاً: أرض مباني على شارع رئيسي...':'مثلاً: محل في موقع حيوي، واجهة زجاجية...'; } function selectShopDeal(val){ dealType=val; ['btn-shop-sale','btn-shop-rent'].forEach(function(id){var b=document.getElementById(id);if(b)b.classList.toggle('on',id==='btn-shop-'+val);}); ['shop-payment-row','svc-box','finish-box','svc-summary','finish-summary'].forEach(id=>hide(id)); document.querySelectorAll('.chip,.finish-btn').forEach(b=>b.classList.remove('on')); selectedChips={}; finishVal=''; if(val==='sale'){ show('shop-payment-row'); // لا خدمات ولا تشطيب للمحلات تمليك } document.getElementById('price-lbl').textContent = val==='sale' ? 'سعر التمليك (ج.م)' : 'الإيجار السنوي (ج.م)'; showRest(); } var shopPayment = ''; function selectShopPayment(val){ shopPayment = val; ['btn-pay-cash','btn-pay-install'].forEach(function(id){ var b=document.getElementById(id); if(b) b.classList.toggle('on', (val==='كاش'&&id==='btn-pay-cash')||(val==='أقساط'&&id==='btn-pay-install')); }); } function selectDeal(val){ dealType=val; ['sale','rent'].forEach(v=>document.getElementById('btn-'+v).classList.toggle('on',v===val)); ['svc-box','finish-box','rent-box','svc-summary','finish-summary','apt-sale-extras'].forEach(id=>hide(id)); document.querySelectorAll('.chip,.finish-btn').forEach(b=>b.classList.remove('on')); selectedChips={}; finishVal=''; aptFurnish=''; aptPayment=''; ['btn-furn-yes','btn-furn-no','btn-apt-cash','btn-apt-install'].forEach(function(id){var b=document.getElementById(id);if(b)b.classList.remove('on');}); if(val==='rent') show('rent-box'); if(val==='sale'&&propType==='apt'){ show('svc-box'); show('finish-box'); show('apt-sale-extras'); // عند تمليك: اعرض chips المخصصة للتمليك var rc=document.getElementById('svc-chips-rent'); var sc=document.getElementById('svc-chips-sale'); if(rc) rc.style.display='none'; if(sc) sc.style.display='flex'; if(sc) sc.style.flexWrap='wrap'; if(sc) sc.style.gap='8px'; } else { // عند الإيجار: اعرض كل الخدمات var rc2=document.getElementById('svc-chips-rent'); var sc2=document.getElementById('svc-chips-sale'); if(rc2) rc2.style.display='flex'; if(rc2) rc2.style.flexWrap='wrap'; if(rc2) rc2.style.gap='8px'; if(sc2) sc2.style.display='none'; } showRest(); } function onRentTypeChange(){ var rt=document.getElementById('rentType').value; ['svc-box','finish-box','svc-summary','finish-summary'].forEach(id=>hide(id)); document.querySelectorAll('.chip,.finish-btn').forEach(b=>b.classList.remove('on')); selectedChips={}; finishVal=''; if(propType==='apt'&&(rt==='شهري (شتوي)'||rt==='سنوي')){show('svc-box');show('finish-box');} var sr=document.getElementById('sea-row'); if(rt==='يومي'||rt==='أسبوعي'||rt==='شهري (صيفي)'){sr.classList.remove('hidden');} else{sr.classList.add('hidden');document.querySelectorAll('.sea-btn').forEach(b=>b.classList.remove('on'));nearSea='';} updateStepNumbers(); } function selectFurnish(val){ aptFurnish=val; document.getElementById('btn-furn-yes').classList.toggle('on',val==='مفروشة'); document.getElementById('btn-furn-no').classList.toggle('on',val==='غير مفروشة'); } function selectAptPayment(val){ aptPayment=val; document.getElementById('btn-apt-cash').classList.toggle('on',val==='كاش'); document.getElementById('btn-apt-install').classList.toggle('on',val==='أقساط'); } function showRest(){ show('rest-form'); document.getElementById('floor-row').classList.toggle('hidden',propType!=='apt'); document.getElementById('shop-area-row').classList.add('hidden'); // always hidden var sr=document.getElementById('sea-row'); if(propType==='apt'&&dealType==='rent'){ var rt=document.getElementById('rentType').value; sr.classList.toggle('hidden',!(rt==='يومي'||rt==='أسبوعي'||rt==='شهري (صيفي)')); } else sr.classList.add('hidden'); updateStepNumbers(); } function updateStepNumbers(){ var hs=!document.getElementById('svc-box').classList.contains('hidden'); var hf=!document.getElementById('finish-box').classList.contains('hidden'); var n=3; if(hs){document.getElementById('svc-lbl').textContent='③ الخدمات والمرافق المتاحة';n++;} if(hf){document.getElementById('finish-lbl').textContent=(hs?'④':'③')+' التشطيب';n++;} document.getElementById('region-lbl').textContent=(['①','②','③','④','⑤'][n-1]||n+'.')+' المنطقة في مطروح'; } function toggleChip(el,id){ selectedChips[id]=!selectedChips[id]; el.classList.toggle('on',!!selectedChips[id]); var lm={water:'مياه',gas:'غاز',elec:'كهرباء',sewage:'صرف صحي',elev:'أسانسير',park:'جراج',sec:'أمن وحراسة',seaview:'إطلالة بحر',furn:'مفروشة',ac:'تكييف',pool:'حمام سباحة',gym:'جيم'}; var ch=Object.keys(selectedChips).filter(k=>selectedChips[k]).map(k=>lm[k]); var s=document.getElementById('svc-summary'); if(ch.length){s.textContent='✅ '+ch.join(' · ');s.classList.remove('hidden');}else s.classList.add('hidden'); } function selectFinish(val){ finishVal=val; document.querySelectorAll('.finish-btn').forEach(b=>b.classList.remove('on')); document.getElementById({'سوبر لوكس':'fin-super','لوكس':'fin-lux','نص تشطيب':'fin-semi','عظم':'fin-bare'}[val]).classList.add('on'); var s=document.getElementById('finish-summary');s.textContent='🎨 التشطيب: '+val;s.classList.remove('hidden'); } function selectSea(el,val){ nearSea=val;document.querySelectorAll('.sea-btn').forEach(b=>b.classList.remove('on'));el.classList.add('on'); } /* ════════ PHOTOS ════════ */ function handlePhotos(input){ var files=Array.from(input.files); // لا يوجد حد للملفات files.forEach(function(f){var r=new FileReader();r.onload=function(e){uploadedPhotos.push(e.target.result);renderPhotos();};r.readAsDataURL(f);}); input.value=''; } function renderPhotos(){ var prev=document.getElementById('photo-previews'),ph=document.getElementById('photo-placeholder'); prev.innerHTML=''; if(uploadedPhotos.length){ ph.style.display='none';prev.style.display='flex'; uploadedPhotos.forEach(function(src,i){ var w=document.createElement('div');w.className='photo-thumb-wrap'; w.innerHTML=''; prev.appendChild(w); }); if(true){ var a=document.createElement('div'); a.style.cssText='width:80px;height:80px;border-radius:10px;border:2px dashed #b8d4f0;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:28px;color:#0077b6;background:#f0f7ff'; a.textContent='+';a.onclick=function(){document.getElementById('photo-input').click();}; prev.appendChild(a); } } else {ph.style.display='';prev.style.display='none';} } function removePhoto(i){uploadedPhotos.splice(i,1);renderPhotos();} /* ════════ PREVIEW SYSTEM ════════ */ var _pendingAd = null; function buildAdMsg(ad){ var pl={apt:'شقة',land:'أرض',shop:'محل'}; var dl={sale:'تمليك',rent:'إيجار'}; var lm={water:'مياه',gas:'غاز',elec:'كهرباء',sewage:'صرف صحي',elev:'أسانسير',park:'جراج',sec:'أمن',seaview:'إطلالة بحر',furn:'مفروشة',ac:'تكييف',pool:'حمام سباحة',gym:'جيم'}; var msg='🔔 *إعلان جديد ينتظر مراجعتك*\n'; msg+='━━━━━━━━━━━━━━━━━\n'; msg+='👤 *المعلن:* '+ad.ownerName+'\n'; msg+='📌 *النوع:* '+(pl[ad.propType]||ad.propType)+' — '+(dl[ad.dealType]||'')+(ad.rentType?' ('+ad.rentType+')':'')+'\n'; msg+='📍 *المنطقة:* '+ad.region+'\n'; msg+='💰 *السعر:* '+Number(ad.price).toLocaleString('ar-EG')+' ج.م\n'; if(ad.size) msg+=(ad.propType==='apt'?'🛏 *الغرف:* ':'📐 *المساحة:* ')+ad.size+(ad.propType!=='apt'?' م²':'')+'\n'; if(ad.floor) msg+='🏢 *الدور:* '+ad.floor+'\n'; if(ad.nearSea) msg+='🌊 *قرب البحر:* '+ad.nearSea+'\n'; if(ad.finishVal) msg+='🎨 *التشطيب:* '+ad.finishVal+'\n'; if(ad.aptFurnish) msg+='🛋️ *الفرش:* '+ad.aptFurnish+'\n'; if(ad.aptPayment) msg+='💳 *الدفع:* '+ad.aptPayment+'\n'; if(ad.services&&ad.services.length) msg+='✅ *الخدمات:* '+ad.services.map(function(k){return lm[k]||k;}).join(' · ')+'\n'; if(ad.desc) msg+='📝 '+ad.desc+'\n'; msg+='━━━━━━━━━━━━━━━━━\n'; msg+='📞 *واتساب المعلن:* '+ad.phone+'\n'; msg+='🔗 wa.me/'+ad.phone.replace(/^0/,'20')+'\n'; msg+='🕐 '+ad.submittedAt+'\n\n'; msg+='افتح لوحة التحكم للموافقة أو الرفض ✅❌'; return msg; } function validateForm(){ var profile=loadBrokerProfile(); var name=profile?profile.name:document.getElementById('owner-name').value.trim(); var region=document.getElementById('region').value; var price=document.getElementById('price').value; var phone=profile?profile.phone:document.getElementById('phone').value.replace(/\s/g,''); if(!name){toast('⚠️ من فضلك أدخل اسمك');return null;} if(!propType){toast('⚠️ اختر نوع العقار');return null;} if(!dealType){toast('⚠️ اختر نوع المعاملة');return null;} if(!region){toast('⚠️ اختر المنطقة');return null;} if(!price){toast('⚠️ أدخل السعر');return null;} if(!phone){toast('⚠️ أدخل رقم الواتساب');return null;} if(!/^(010|011|012|015)\d{8}$/.test(phone)){toast('⚠️ رقم غير صحيح — يبدأ بـ 010/011/012/015');return null;} // الصور اختيارية return { id:'ad_'+Date.now(), adCode: getNextAdCode(), submitterPhone: currentUser ? currentUser.phone : phone, ownerName:name, region, price, phone, propType, dealType, rentType:dealType==='rent'&&propType==='apt'?document.getElementById('rentType').value:'', shopPayment:propType==='shop'&&dealType==='sale'?shopPayment:'', size:document.getElementById('size').value, floor:propType==='apt'?document.getElementById('floor').value:'', nearSea, finishVal, aptFurnish, aptPayment, services:Object.keys(selectedChips).filter(function(k){return selectedChips[k];}), desc:document.getElementById('desc').value.trim(), photos:uploadedPhotos.slice(), brokerPhoto: profile?profile.photo:'', brokerType: profile?profile.accountType:'', submittedAt:new Date().toLocaleString('ar-EG') }; } function openPreview(){ var ad = validateForm(); if(!ad) return; _pendingAd = ad; document.getElementById('preview-msg').textContent = buildAdMsg(ad); document.getElementById('preview-overlay').classList.remove('hidden'); window.scrollTo({top:0,behavior:'smooth'}); } function closePreview(){ document.getElementById('preview-overlay').classList.add('hidden'); _pendingAd = null; } function confirmSend(){ if(!_pendingAd){closePreview();return;} var ad = _pendingAd; var _bp = loadBrokerProfile(); ad.submitterPhone = _bp ? _bp.phone : ad.phone; document.getElementById('preview-overlay').classList.add('hidden'); var db=loadDB(); db.pending.push(ad); saveDB(db); updateNotifDot(); _pendingAd=null; updateMyAdsCard(); showSuccessScreen(); saveAdToSB(ad,'pending').catch(function(){}); } function submitAdDirect(){ var ad = validateForm(); if(!ad) return; var _bp2 = loadBrokerProfile(); ad.submitterPhone = _bp2 ? _bp2.phone : ad.phone; var db=loadDB(); db.pending.push(ad); saveDB(db); updateNotifDot(); updateMyAdsCard(); resetForm(); go('success'); saveAdToSB(ad,'pending').catch(function(){}); } function renderSuccessAdPreview(ad){ var pl={apt:'شقة',land:'أرض',shop:'محل'}; var pe={apt:'🏠',land:'🌍',shop:'🏪'}; var imgHtml = ad.photos && ad.photos.length ? '
' : '
'+(pe[ad.propType]||'🏠')+'
'; document.getElementById('success-ad-preview').innerHTML = '
📋 إعلانك:
'+ '
'+ imgHtml+ '
'+ '⏳ قيد المراجعة'+ '
'+(pl[ad.propType]||'عقار')+' في '+ad.region+'
'+ '
📍 '+ad.region+' · 🕐 '+ad.submittedAt+'
'+ '
'+Number(ad.price).toLocaleString('ar-EG')+' ج.م
'+ '
'+ '
'+ ''+ '
'+ '
'; } function deletePendingFromSuccess(id){ if(!confirm('هل تريد حذف هذا الإعلان؟')) return; var db=loadDB(); db.pending=(db.pending||[]).filter(a=>a.id!==id); saveDB(db); updateNotifDot(); updateMyAdsCard(); document.getElementById('success-ad-preview').innerHTML='
🗑️
تم حذف الإعلان
'; toast('🗑️ تم حذف الإعلان'); } function updatePriceHint(){ var v=document.getElementById('price').value; var el=document.getElementById('price-hint'); if(!el)return; el.textContent = (v&&Number(v)>0) ? '💰 '+Number(v).toLocaleString('ar-EG')+' ج.م' : ''; } /* ════════ SUBMIT ════════ */ function showSuccessScreen(){ resetForm(); go('success'); } function submitForm(){ openPreview(); } /* ════════ ADMIN ════════ */ var tapCount=0, tapTimer; document.getElementById('header-tap').addEventListener('click',function(){ tapCount++;clearTimeout(tapTimer); tapTimer=setTimeout(()=>tapCount=0,1500); if(tapCount>=5){ tapCount=0; document.getElementById('admin-fab').style.display='flex'; openAdmin(); } }); function updateNotifDot(){ var db=loadDB(); var n=db.pending.length; var dot=document.getElementById('notif-dot'); if(n>0){dot.textContent=n;dot.classList.remove('hidden');} else dot.classList.add('hidden'); } async function openAdmin(){ show('admin-overlay'); if(currentUser && currentUser.isAdmin){ hide('admin-login-sec'); show('admin-content'); document.querySelectorAll('.atab').forEach(b=>b.classList.remove('on')); document.querySelectorAll('.atab')[0].classList.add('on'); document.querySelectorAll('.admin-tab-content').forEach(c=>c.classList.remove('active')); document.getElementById('atab-ads').classList.add('active'); // جيب أحدث البيانات من Supabase toast('⏳ جاري تحديث البيانات...'); try{ await Promise.all([loadDBAsync(), loadUsersAsync(), loadSettingsAsync()]); _dbCache = null; } catch(e){} renderAdminPanel(); } else { hide('admin-content'); show('admin-login-sec'); document.getElementById('admin-pass').value=''; setTimeout(()=>document.getElementById('admin-pass').focus(),200); } document.getElementById('admin-fab').style.display='flex'; document.body.style.overflow='hidden'; } function closeAdmin(){ hide('admin-overlay'); hide('admin-content'); show('admin-login-sec'); document.body.style.overflow=''; document.body.style.position=''; document.body.style.height=''; } function adminLogin(){ if(document.getElementById('admin-pass').value===ADMIN_PASS){ hide('admin-login-sec'); show('admin-content'); document.querySelectorAll('.atab').forEach(b=>b.classList.remove('on')); document.querySelectorAll('.atab')[0].classList.add('on'); document.querySelectorAll('.admin-tab-content').forEach(c=>c.classList.remove('active')); document.getElementById('atab-ads').classList.add('active'); renderAdminPanel(); } else { toast('⚠️ كلمة السر غلط'); document.getElementById('admin-pass').value=''; document.getElementById('admin-pass').focus(); } } async function switchAdminTab(tab, btn){ document.querySelectorAll('.atab').forEach(b=>b.classList.remove('on')); btn.classList.add('on'); document.querySelectorAll('.admin-tab-content').forEach(c=>c.classList.remove('active')); document.getElementById('atab-'+tab).classList.add('active'); // جيب أحدث البيانات من Supabase try{ await Promise.all([loadDBAsync(), loadUsersAsync()]); _dbCache = null; } catch(e){} if(tab==='ads') renderAdminPanel(); if(tab==='featured') renderFeaturedTab(); if(tab==='users') renderUsersPanel(); if(tab==='brokers') renderBrokersPanel(); if(tab==='stats') renderStatsPanel(); if(tab==='settings') renderSettingsPanel(); } function updateAdminStats(){ var db=loadDB(); var users=loadUsers(); var approved=db.approved||[]; document.getElementById('stat-pending').textContent = (db.pending||[]).length; document.getElementById('stat-approved').textContent = approved.length; document.getElementById('stat-featured').textContent = approved.filter(a=>a.featured).length; document.getElementById('stat-users').textContent = users.length; } function renderAdminPanel(){ updateAdminStats(); var db=loadDB(); var pl={apt:'شقة',land:'أرض',shop:'محل'}; var plist=document.getElementById('pending-list'); if(!db.pending||!db.pending.length){ plist.innerHTML='
✅ لا توجد إعلانات في الانتظار
'; } else { plist.innerHTML='
⏳ قيد المراجعة '+db.pending.length+'
'+ db.pending.map(function(a){ var thumbs=a.photos&&a.photos.length ?'
'+a.photos.slice(0,4).map(p=>'').join('')+'
':''; return '
'+ '
'+(pl[a.propType]||a.propType)+' — '+(a.dealType==='sale'?'تمليك':'إيجار')+(a.rentType?' ('+a.rentType+')':'')+' · '+a.region+'
'+ '
👤 '+a.ownerName+'
📞 '+a.phone+'
💰 '+Number(a.price).toLocaleString('ar-EG')+' ج.م'+(a.size?' · '+(a.propType==='apt'?a.size+' غرف':a.size+' م²'):'')+ (a.nearSea?'
🌊 '+a.nearSea:'')+(a.finishVal?'
🎨 '+a.finishVal:'')+'
🕐 '+a.submittedAt+'
'+ thumbs+ (a.desc?'
'+a.desc+'
':'')+ '
'+ ''+ ''+ '
'; }).join(''); } var asec=document.getElementById('approved-section'); var approved=db.approved||[]; if(approved.length){ asec.innerHTML='
✅ منشورة '+approved.length+'
'+ approved.map(function(a){ var isFeatured=!!a.featured; var imgEl=a.photos&&a.photos.length ?'' :'
'+(({apt:'🏠',land:'🌍',shop:'🏪'})[a.propType]||'🏠')+'
'; return '
'+imgEl+ '
'+ '
'+(isFeatured?'⭐ ':'')+( pl[a.propType]||'عقار')+' · '+a.region+'
'+ '
👤 '+a.ownerName+' · 📞 '+a.phone+'
'+ '
'+Number(a.price).toLocaleString('ar-EG')+' ج.م
'+ '
'+ '
'+ ''+ ''+ '
'+ '
'; }).join(''); } else { asec.innerHTML=''; } } function renderFeaturedTab(){ var db=loadDB(); var pl={apt:'شقة',land:'أرض',shop:'محل'}; var featured=(db.approved||[]).filter(a=>a.featured); var el=document.getElementById('featured-list'); if(!featured.length){ el.innerHTML='
⭐ لا توجد إعلانات مميزة حالياً
';return; } el.innerHTML='
⭐ الإعلانات المميزة '+featured.length+'
'+ featured.map(function(a){ var imgEl=a.photos&&a.photos.length ?'' :'
'+(({apt:'🏠',land:'🌍',shop:'🏪'})[a.propType]||'🏠')+'
'; return ''; }).join(''); } function renderStatsPanel(){ var db=loadDB(); var users=loadUsers(); var approved=db.approved||[]; var pending=db.pending||[]; var featured=approved.filter(a=>a.featured); // By type var byType={apt:0,land:0,shop:0}; approved.forEach(a=>byType[a.propType]=(byType[a.propType]||0)+1); // By region var byRegion={}; approved.forEach(a=>{byRegion[a.region]=(byRegion[a.region]||0)+1;}); var regionRows=Object.entries(byRegion).sort((a,b)=>b[1]-a[1]).slice(0,6); var totalPrice=approved.reduce((s,a)=>s+Number(a.price||0),0); var avgPrice=approved.length?Math.round(totalPrice/approved.length):0; document.getElementById('stats-content').innerHTML= '
'+ '
📊 نظرة عامة
'+ '
'+ statCard('📋','إجمالي الإعلانات',approved.length+pending.length,'#023e8a')+ statCard('✅','منشورة',approved.length,'#0a7a4a')+ statCard('⏳','قيد المراجعة',pending.length,'#92400e')+ statCard('⭐','مميزة',featured.length,'#b45309')+ statCard('👥','المستخدمون',users.length,'#5b21b6')+ statCard('💰','متوسط السعر',avgPrice.toLocaleString('ar-EG')+' ج.م','#0077b6')+ '
'+ '
'+ '
'+ '
🏠 الإعلانات حسب النوع
'+ typeBar('🏠 شقق',byType.apt||0,approved.length,'#0077b6')+ typeBar('🌍 أراضي',byType.land||0,approved.length,'#16a34a')+ typeBar('🏪 محلات',byType.shop||0,approved.length,'#7c3aed')+ '
'+ (regionRows.length?'
'+ '
📍 أكثر المناطق إعلانات
'+ regionRows.map(function(r){return typeBar(r[0],r[1],approved.length,'#0077b6');}).join('')+ '
':''); } function statCard(ico,lbl,val,color){ return '
'+ '
'+ico+'
'+ '
'+val+'
'+ '
'+lbl+'
'+ '
'; } function typeBar(lbl,val,total,color){ var pct=total?Math.round(val/total*100):0; return '
'+ '
'+ ''+lbl+''+val+' ('+pct+'%)'+ '
'+ '
'+ '
'+ '
'+ '
'; } function toggleFeaturedAd(id){ var db=loadDB(); var ad=(db.approved||[]).find(a=>a.id===id); if(!ad){toast('⚠️ إعلان غير موجود');return;} ad.featured=!ad.featured; saveDB(db); updateAdminStats(); // refresh whichever tab is active var activeTab=document.querySelector('.admin-tab-content.active'); if(activeTab){ var tabId=activeTab.id.replace('atab-',''); if(tabId==='ads') renderAdminPanel(); else if(tabId==='featured') renderFeaturedTab(); } toast(ad.featured?'⭐ تم تمييز الإعلان بالإطار الذهبي':'☆ تم إلغاء تمييز الإعلان'); } function renderUsersPanel(){ var users=loadUsers(); var db=loadDB(); var el=document.getElementById('users-list'); if(!users.length){el.innerHTML='
👥 لا يوجد مستخدمون مسجلون بعد
';return;} el.innerHTML='
👥 المستخدمون '+users.length+'
'+ users.map(function(u){ var isBlocked=!!u.blocked; var myAds=(db.approved||[]).filter(a=>a.phone===u.phone||a.submitterPhone===u.phone).length; var myPending=(db.pending||[]).filter(a=>a.phone===u.phone||a.submitterPhone===u.phone).length; return '
'+ '
'+(isBlocked?'🚫':'👤')+'
'+ ''+ ''+ '
'; }).join(''); } function toggleBlockUser(phone){ var users=loadUsers(); var u=users.find(x=>x.phone===phone); if(!u)return; u.blocked=!u.blocked; saveUsers(users); renderUsersPanel(); toast(u.blocked?'🚫 تم حظر المستخدم':'✅ تم رفع الحظر'); } function renderSettingsPanel(){ var s=loadSettings(); document.getElementById('setting-price').value=s.featuredPrice||'50'; var vp=document.getElementById('setting-verify-price'); if(vp) vp.value=s.verifyPrice||'100'; document.getElementById('setting-vodafone').value=s.vodafoneNum||'01005581620'; document.getElementById('setting-wa').value=s.adminWa||'01040986955'; document.getElementById('setting-pass').value=''; } function clearAllData(){ if(!confirm('هتمسح كل الإعلانات والبيانات نهائياً — متعملش كده غير لو متأكد!')) return; ['fares_ads','fares_views','fares_favs','fares_users','fares_ad_counter'].forEach(function(k){ localStorage.removeItem(k); }); toast('✅ تم مسح كل البيانات'); setTimeout(function(){ location.reload(); }, 1000); } function saveSettings(){ var newPass=document.getElementById('setting-pass').value.trim(); var s={ featuredPrice:document.getElementById('setting-price').value, verifyPrice:(document.getElementById('setting-verify-price')||{value:'100'}).value, vodafoneNum:document.getElementById('setting-vodafone').value, adminWa:document.getElementById('setting-wa').value }; saveSettings2(s); if(newPass&&newPass.length>=4){ ADMIN_PASS=newPass; toast('✅ تم حفظ الإعدادات وتغيير كلمة السر'); } else toast('✅ تم حفظ الإعدادات'); } function approveAd(id){ var db=loadDB(); var idx=db.pending.findIndex(a=>a.id===id); if(idx===-1){toast('إعلان غير موجود');return;} var ad=db.pending.splice(idx,1)[0]; if(!db.approved) db.approved=[]; db.approved.unshift(ad); saveDB(db); renderAdminPanel(); updateNotifDot(); toast('✅ تم نشر الإعلان وإشعار المعلن'); saveAdToSB(ad,'approved').catch(function(){}); // إشعار حقيقي للمستخدم لو التطبيق مفتوح notifyUserAdApproved(ad); var clean=ad.phone.replace(/\s/g,'').replace(/^0/,'20'); var msg='مرحباً '+ad.ownerName+' 🎉\n\nتم قبول ونشر إعلانك على موقع *ديار* 🏠\n\nإعلانك متاح الآن للجميع على الموقع.\nشكراً لثقتك بنا! 🌊'; window.open('https://wa.me/'+clean+'?text='+encodeURIComponent(msg),'_blank'); } function notifyUserAdApproved(ad){ // إشعار للمستخدم لو التطبيق مفتوح if(currentUser && (currentUser.phone === ad.phone || currentUser.phone === ad.submitterPhone)){ showSmartToast('🎉', 'تم قبول إعلانك!', 'success', 8000); } // إشعار النظام لو مسموح if('Notification' in window && Notification.permission === 'granted'){ new Notification('ديار 🏠', { body: 'تم قبول ونشر إعلانك · ' + ad.ownerName, icon: '/icon-192.png' }); } } function rejectAd(id){ var db=loadDB(); var idx=db.pending.findIndex(a=>a.id===id); if(idx===-1){toast('إعلان غير موجود');return;} var ad=db.pending.splice(idx,1)[0]; saveDB(db); renderAdminPanel(); updateNotifDot(); toast('🗑️ تم رفض الإعلان'); deleteAdFromSB(id).catch(function(){}); var clean=ad.phone.replace(/\s/g,'').replace(/^0/,'20'); var msg='مرحباً '+ad.ownerName+'\n\nللأسف لم يتم قبول إعلانك على موقع *ديار* حالياً.\n\nيمكنك التواصل معنا لمعرفة السبب أو إعادة المحاولة بعد التعديل.'; window.open('https://wa.me/'+clean+'?text='+encodeURIComponent(msg),'_blank'); } function deleteAd(id){ var db=loadDB(); db.approved=(db.approved||[]).filter(a=>a.id!==id); saveDB(db); renderAdminPanel(); toast('🗑️ تم حذف الإعلان'); deleteAdFromSB(id).catch(function(){}); } /* ════════ MY ADS ════════ */ var _editingAdId = null; var _editingAdSource = null; // 'pending' or 'approved' function getMyPhone(){ if(currentUser && currentUser.phone) return currentUser.phone; var bp = loadBrokerProfile(); if(bp && bp.phone) return bp.phone; return null; } function getMyAds(){ var db = loadDB(); var myPhone = getMyPhone(); if(!myPhone) return {pending:[], approved:[]}; var myPending = (db.pending||[]).filter(function(a){ return a.submitterPhone === myPhone || a.phone === myPhone; }); var myApproved = (db.approved||[]).filter(function(a){ return a.submitterPhone === myPhone || a.phone === myPhone; }); return {pending: myPending, approved: myApproved}; } function updateMyAdsCard(){ var mine = getMyAds(); var hasApproved = mine.approved.length > 0; var hasPending = mine.pending.length > 0; // ─── Owner Zone (بطاقتان كبيرتان) — يظهر فقط لو عنده إعلان منشور ─── var ownerZone = document.getElementById('owner-zone'); if(ownerZone) ownerZone.style.display = hasApproved ? 'block' : 'none'; // badge + sub على owner-zone var ownerBadge = document.getElementById('owner-badge'); var ownerSub = document.getElementById('owner-myads-sub'); if(ownerBadge){ if(hasPending){ ownerBadge.textContent=mine.pending.length; ownerBadge.style.display='flex'; } else ownerBadge.style.display='none'; } if(ownerSub){ ownerSub.textContent = mine.approved.length + ' منشور' + (hasPending?' · '+mine.pending.length+' معلق':''); } // ─── My Ads Card العادية — يظهر فقط لو عنده معلقة بدون منشورة ─── var myAdsCard = document.getElementById('my-ads-card'); var badge = document.getElementById('my-ads-badge'); if(myAdsCard){ if(hasPending && !hasApproved){ myAdsCard.style.display = 'block'; if(badge){ badge.textContent=mine.pending.length; badge.style.display='flex'; } document.getElementById('my-ads-sub-text').textContent = mine.pending.length + ' إعلان قيد المراجعة'; } else { myAdsCard.style.display = 'none'; } } // ─── Pending preview strip (يظهر دايماً لو في معلقة) ─── renderHomePendingPreview(mine.pending); } function renderHomePendingPreview(pending){ var el = document.getElementById('home-pending-preview'); if(!pending || !pending.length){el.innerHTML='';return;} var pl={apt:'شقة',land:'أرض',shop:'محل'}; var pe={apt:'🏠',land:'🌍',shop:'🏪'}; el.innerHTML = pending.map(function(a){ var imgHtml = a.photos && a.photos.length ? '' : '
'+(pe[a.propType]||'🏠')+'
'; return '
'+ imgHtml+ '
'+ '
⏳ قيد المراجعة
'+ '
'+(pl[a.propType]||'عقار')+' في '+a.region+'
'+ (a.adCode?'
#'+a.adCode+'
':'')+ '
💰 '+Number(a.price).toLocaleString('ar-EG')+' ج.م'+(a.size?' · '+(a.propType==='apt'?a.size+' غرف':a.size+' م²'):'')+' · 📍 '+a.region+'
'+ '
🕐 '+a.submittedAt+'
'+ ''+ '
'+ '
'; }).join(''); } function deleteMyAdFromHome(id){ if(!confirm('هل تريد حذف هذا الإعلان؟')) return; var db=loadDB(); db.pending=(db.pending||[]).filter(a=>a.id!==id); saveDB(db); updateNotifDot(); updateMyAdsCard(); toast('🗑️ تم حذف الإعلان'); } function renderMyAds(){ // اعرض فوراً من cache _doRenderMyAds(); // حدّث من Supabase في الخلفية loadDBAsync().then(function(){ _doRenderMyAds(); }).catch(function(){}); } function _doRenderMyAds(){ var mine = getMyAds(); var all = mine.pending.map(function(a){return Object.assign({},a,{_status:'pending'});}) .concat(mine.approved.map(function(a){return Object.assign({},a,{_status:'approved'});})); var grid = document.getElementById('myads-grid'); var sub = document.getElementById('myads-sub'); if(!all.length){ sub.textContent = ''; grid.innerHTML = '
📭
'+ '
لا توجد إعلانات بعد
'+ '
ابدأ بإضافة أول إعلان لك!
'+ '
'; return; } sub.textContent = all.length + ' إعلان (' + mine.approved.length + ' منشور · ' + mine.pending.length + ' في الانتظار)'; var pl={apt:'شقة',land:'أرض',shop:'محل'}; var pe={apt:'🏠',land:'🌍',shop:'🏪'}; grid.innerHTML = all.map(function(a){ var isFeatured = !!a.featured; var isPending = a._status === 'pending'; var imgHtml = a.photos && a.photos.length ? '
' : '
'+(pe[a.propType]||'🏠')+'
'; var statusBadge = isPending ? '⏳ قيد المراجعة' : isFeatured ? '⭐ مميز ومنشور' : '✅ منشور'; var cardClass = 'my-ad-card' + (isPending?' pending-ad':'') + (isFeatured?' featured-ad':''); // Actions row — pending: delete only | approved: edit + delete + star var actionsHtml; if(isPending){ actionsHtml = '
'+ ''+ '
'; } else { var editBtn = ''; var delBtn = ''; var starBtn = ''; actionsHtml = '
'+editBtn+delBtn+starBtn+'
'; } return '
'+imgHtml+ '
'+ statusBadge+ '
'+(pl[a.propType]||'عقار')+' في '+a.region+'
'+ '
📍 '+a.region+' · 🕐 '+a.submittedAt+'
'+ '
'+Number(a.price).toLocaleString('ar-EG')+' ج.م
'+ '
'+ actionsHtml+ '
'; }).join(''); } function deleteMyAd(id, source){ if(!confirm('هل تريد حذف هذا الإعلان؟')) return; var db = loadDB(); if(source === 'pending'){ db.pending = (db.pending||[]).filter(a=>a.id!==id); } else { db.approved = (db.approved||[]).filter(a=>a.id!==id); } saveDB(db); updateMyAdsCard(); renderMyAds(); toast('🗑️ تم حذف الإعلان'); } function openEditModal(id, source){ var db = loadDB(); var list = source === 'pending' ? (db.pending||[]) : (db.approved||[]); var ad = list.find(a=>a.id===id); if(!ad){toast('⚠️ الإعلان غير موجود');return;} _editingAdId = id; _editingAdSource = source; document.getElementById('edit-name').value = ad.ownerName||''; document.getElementById('edit-region').value = ad.region||''; document.getElementById('edit-price').value = ad.price||''; document.getElementById('edit-size').value = ad.size||''; document.getElementById('edit-phone').value = ad.phone||''; document.getElementById('edit-desc').value = ad.desc||''; document.getElementById('edit-size-lbl').textContent = ad.propType==='apt'?'عدد الغرف':'المساحة (م²)'; document.getElementById('edit-overlay').classList.remove('hidden'); } function closeEditModal(){ document.getElementById('edit-overlay').classList.add('hidden'); _editingAdId = null; _editingAdSource = null; } function saveEditAd(){ if(!_editingAdId) return; var db = loadDB(); var list = _editingAdSource === 'pending' ? (db.pending||[]) : (db.approved||[]); var ad = list.find(a=>a.id===_editingAdId); if(!ad){toast('⚠️ الإعلان غير موجود');closeEditModal();return;} var newName = document.getElementById('edit-name').value.trim(); var newRegion = document.getElementById('edit-region').value; var newPrice = document.getElementById('edit-price').value; var newPhone = document.getElementById('edit-phone').value.trim(); var newDesc = document.getElementById('edit-desc').value.trim(); var newSize = document.getElementById('edit-size').value; if(!newName){toast('⚠️ أدخل الاسم');return;} if(!newRegion){toast('⚠️ اختر المنطقة');return;} if(!newPrice){toast('⚠️ أدخل السعر');return;} if(!newPhone||!/^(010|011|012|015)\d{8}$/.test(newPhone)){toast('⚠️ رقم غير صحيح');return;} ad.ownerName = newName; ad.region = newRegion; ad.price = newPrice; ad.phone = newPhone; ad.submitterPhone = newPhone; ad.desc = newDesc; ad.size = newSize; ad.editedAt = new Date().toLocaleString('ar-EG'); saveDB(db); closeEditModal(); renderMyAds(); toast('✅ تم حفظ التعديلات'); } var _featuredAdId = null; function requestFeaturedFromMyAds(id){ var db = loadDB(); var ad = (db.approved||[]).find(a=>a.id===id) || (db.pending||[]).find(a=>a.id===id); if(!ad) return; if(ad.featured){toast('⭐ إعلانك مميز بالفعل!');return;} _featuredAdId = id; // تحديث الرقم والسعر من الإعدادات var settings = loadSettings(); var walletNum = settings.vodafoneNum || '01005581620'; var price = settings.featuredPrice || '50'; document.getElementById('pay-wallet-num').textContent = walletNum; document.getElementById('pay-price-pill').textContent = price; document.getElementById('pay-price-step').textContent = price; document.getElementById('pay-overlay').classList.remove('hidden'); } function closePayOverlay(){ document.getElementById('pay-overlay').classList.add('hidden'); _featuredAdId = null; } function copyWalletNum(){ var num = document.getElementById('pay-wallet-num').textContent; navigator.clipboard.writeText(num).then(function(){ toast('📋 تم نسخ الرقم: ' + num); }).catch(function(){ toast('الرقم: ' + num); }); } function sendFeaturedFromPopup(){ var db = loadDB(); // ابحث في approved أو pending var ad = null; if(_featuredAdId){ ad = (db.approved||[]).find(a=>a.id===_featuredAdId) || (db.pending||[]).find(a=>a.id===_featuredAdId); } var settings = loadSettings(); var waNum = (settings.adminWa||ADMIN_NUMBER).replace(/^0/,'20'); var price = settings.featuredPrice || '50'; var pl={apt:'شقة',land:'أرض',shop:'محل'}; var msg = '⭐ *طلب تمييز إعلان*\n'; msg += '━━━━━━━━━━━━━━━━━\n'; if(ad){ msg += '🔢 *كود الإعلان:* ' + (ad.adCode ? '#'+ad.adCode : '(بدون كود)') + '\n'; msg += '👤 *المعلن:* ' + ad.ownerName + '\n'; msg += '📞 *الواتساب:* ' + ad.phone + '\n'; msg += '🏠 *النوع:* ' + (pl[ad.propType]||ad.propType) + '\n'; msg += '📍 *المنطقة:* ' + ad.region + '\n'; msg += '💰 *السعر:* ' + Number(ad.price).toLocaleString('ar-EG') + ' ج.م\n'; if(ad.size) msg += (ad.propType==='apt'?'🛏 *الغرف:* ':'📐 *المساحة:* ') + ad.size + '\n'; } msg += '━━━━━━━━━━━━━━━━━\n'; msg += '💳 *تم تحويل ' + price + ' ج.م فودافون كاش*\nرجاء تمييز الإعلان بالإطار الذهبي ⭐🙏'; window.open('https://wa.me/'+waNum+'?text='+encodeURIComponent(msg),'_blank'); closePayOverlay(); toast('📲 تم فتح واتساب — أرسل إيصال التحويل للإدارة'); } function adminSearchAds(){ var q = document.getElementById('admin-search-input').value.trim().toLowerCase(); var resEl = document.getElementById('admin-search-results'); var pendingEl = document.getElementById('pending-list'); var approvedEl = document.getElementById('approved-section'); if(!q){ resEl.style.display='none'; pendingEl.style.display=''; approvedEl.style.display=''; return; } pendingEl.style.display='none'; approvedEl.style.display='none'; resEl.style.display='block'; var db=loadDB(); var all=((db.pending||[]).map(a=>Object.assign({},a,{_src:'pending'}))) .concat((db.approved||[]).map(a=>Object.assign({},a,{_src:'approved'}))); var found=all.filter(function(a){ return (a.adCode&&a.adCode.toLowerCase().indexOf(q)!==-1) || (a.ownerName&&a.ownerName.indexOf(q)!==-1) || (a.phone&&a.phone.indexOf(q)!==-1) || (a.region&&a.region.indexOf(q)!==-1); }); var pl={apt:'شقة',land:'أرض',shop:'محل'}; if(!found.length){ resEl.innerHTML='
🔍 لا توجد نتائج
'; return; } resEl.innerHTML='
🔍 نتائج البحث '+found.length+'
'+ found.map(function(a){ var srcBadge = a._src==='pending' ? '⏳ انتظار' : '✅ منشور'; return '
'+ '
'+ '
'+(a.adCode?'#'+a.adCode+' · ':'')+' '+(pl[a.propType]||'عقار')+' · '+a.region+'
'+ '
'+a.ownerName+' · '+a.phone+'
'+ '
'+Number(a.price).toLocaleString('ar-EG')+' ج.م · '+srcBadge+'
'+ '
'+ (a._src==='approved'?'
': '')+ '
'; }).join(''); } /* ════════ RESET ════════ */ function resetForm(){ propType='';dealType='';nearSea='';finishVal='';aptFurnish='';aptPayment='';selectedChips={};uploadedPhotos=[]; ['apt','land','shop','sale','rent'].forEach(v=>{var b=document.getElementById('btn-'+v);if(b)b.classList.remove('on');}); ['btn-shop-sale','btn-shop-rent','btn-pay-cash','btn-pay-install'].forEach(function(id){var b=document.getElementById(id);if(b)b.classList.remove('on');}); shopPayment=''; aptFurnish=''; aptPayment=''; ['btn-furn-yes','btn-furn-no','btn-apt-cash','btn-apt-install'].forEach(function(id){var b=document.getElementById(id);if(b)b.classList.remove('on');}); ['apt-sale-extras'].forEach(id=>hide(id)); ['deal-sec','land-note','shop-deal-sec','shop-payment-row','rent-box','svc-box','finish-box','rest-form','floor-row','sea-row','shop-area-row','svc-summary','finish-summary'].forEach(id=>hide(id)); document.querySelectorAll('.chip,.sea-btn,.finish-btn').forEach(b=>b.classList.remove('on')); ['region','price','size','floor','phone','desc','shopfront','owner-name'].forEach(id=>{var e=document.getElementById(id);if(e)e.value='';}); var ph2=document.getElementById('price-hint');if(ph2)ph2.textContent=''; var rt=document.getElementById('rentType');if(rt)rt.value='يومي'; var prev=document.getElementById('photo-previews');if(prev){prev.innerHTML='';prev.style.display='none';} var ph=document.getElementById('photo-placeholder');if(ph)ph.style.display=''; // Reset featured featuredEnabled=false; transferPhoto=null; var sw=document.getElementById('featured-toggle-sw');if(sw)sw.classList.remove('on'); var pb=document.getElementById('featured-payment-box');if(pb)pb.style.display='none'; var ti=document.getElementById('transfer-preview-img');if(ti){ti.style.display='none';ti.src='';} } /* INIT */ updateNotifDot(); document.getElementById('preview-overlay').addEventListener('click',function(e){if(e.target===this)closePreview();}); document.getElementById('edit-overlay').addEventListener('click',function(e){if(e.target===this)closeEditModal();}); document.getElementById('pay-overlay').addEventListener('click',function(e){if(e.target===this)closePayOverlay();}); // PWA-first: لو متصفح عادي → PWA overlay بس، لو standalone → تسجيل دخول window.addEventListener('load', async function(){ var isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true; if(isStandalone){ // مفتوح من التطبيق - أضف app-ready document.body.classList.add('app-ready'); document.getElementById('pwa-overlay').style.display = 'none'; var savedUser = null; try{ savedUser = JSON.parse(localStorage.getItem('fares_current_user')||'null'); }catch(e){} if(savedUser && savedUser.phone){ currentUser = savedUser; document.getElementById('otp-overlay').style.display = 'none'; updateUserBadge(); if(savedUser.isAdmin) document.getElementById('admin-fab').style.display = 'flex'; updateBrokerHomeCard(); toast('🎉 مرحباً بعودتك!'); } else { // لو في broker profile محفوظ بس مش مسجل دخول var savedProfile = loadBrokerProfile(); if(savedProfile){ // اعرض شاشة تسجيل الدخول مع اسمه document.getElementById('otp-overlay').style.display = 'flex'; document.getElementById('otp-welcome').textContent = 'مرحباً، '+savedProfile.name+' 👋'; document.getElementById('otp-welcome-sub').textContent = 'أدخل رقمك وكلمة المرور للدخول'; if(savedProfile.linkedPhone){ document.getElementById('otp-phone').value = savedProfile.linkedPhone; var pwInp = document.getElementById('otp-password'); if(pwInp) pwInp.focus(); } else { loadSavedPhones(); } } else { document.getElementById('otp-overlay').style.display = 'flex'; loadSavedPhones(); } } } else { // مفتوح من المتصفح — CSS بيخفي كل حاجة تلقائي // مش محتاج نضيف app-ready عشان الـ CSS يفضل شغال } updateMyAdsCard(); updateFavsCard(); updateBrokerHomeCard(); try{ await Promise.all([loadDBAsync(), loadUsersAsync(), loadSettingsAsync()]); _dbCache = null; updateMyAdsCard(); updateFavsCard(); updateNotifDot(); } catch(e){} }); /* ════════ BROKER PROFILE ════════ */ var _regAccountType = ''; function loadBrokerProfile(){ try{ return JSON.parse(localStorage.getItem('fares_broker_profile')||'null'); }catch(e){return null;} } function saveBrokerProfile(p){ localStorage.setItem('fares_broker_profile',JSON.stringify(p)); } function selectAccountType(type){ _regAccountType = type; document.getElementById('acc-broker').classList.toggle('on', type==='سمسار'); document.getElementById('acc-owner').classList.toggle('on', type==='مالك'); } function handleRegPhoto(input){ if(!input.files||!input.files[0]) return; var reader=new FileReader(); reader.onload=function(e){ var src=e.target.result; var icon=document.getElementById('reg-avatar-icon'); var img=document.getElementById('reg-avatar-img'); if(icon) icon.style.display='none'; if(img){img.src=src;img.style.display='block';} // store temp for save document._regPhotoData=src; }; reader.readAsDataURL(input.files[0]); } function saveProfile(){ var name=document.getElementById('reg-name').value.trim(); var phone=document.getElementById('reg-phone').value.trim(); if(!_regAccountType){toast('⚠️ اختر نوع الحساب (سمسار أو مالك)');return;} if(!name){toast('⚠️ أدخل اسمك الكامل');return;} if(!phone||!/^(010|011|012|015)\d{8}$/.test(phone)){toast('⚠️ أدخل رقم واتساب صحيح');return;} var photo = document._regPhotoData || (loadBrokerProfile()||{}).photo || ''; var profile={name,phone,accountType:_regAccountType,photo,linkedPhone: currentUser?currentUser.phone:phone}; saveBrokerProfile(profile); // حفظ في Supabase في الخلفية saveUserProfileToSB(profile).catch(function(){}); updateBrokerHomeCard(); toast('✅ تم حفظ حسابك بنجاح!'); go('home'); } async function saveUserProfileToSB(profile){ try{ // أولاً حفظ في localStorage عشان renderBrokersPanel تشتغل var users = loadUsers(); var existing = users.find(function(u){ return u.phone === (profile.linkedPhone||profile.phone); }); if(existing){ existing.profile_name = profile.name; existing.profile_type = profile.accountType; existing.profile_phone = profile.phone; existing.profile_photo = profile.photo || ''; } else { users.push({ phone: profile.linkedPhone||profile.phone, blocked: false, joinedAt: new Date().toLocaleString('ar-EG'), profile_name: profile.name, profile_type: profile.accountType, profile_phone: profile.phone, profile_photo: profile.photo || '' }); } saveUsers(users); // بعدين Supabase في الخلفية await sbFetch('users', { method: 'POST', headers:{ 'apikey': SUPABASE_KEY, 'Authorization': 'Bearer ' + SUPABASE_KEY, 'Content-Type': 'application/json', 'Prefer': 'resolution=merge-duplicates,return=representation' }, body: JSON.stringify({ phone: profile.linkedPhone || profile.phone, blocked: false, joined_at: new Date().toISOString(), profile_name: profile.name, profile_type: profile.accountType, profile_phone: profile.phone }) }); } catch(e){} } function updateBrokerHomeCard(){ var profile=loadBrokerProfile(); var brokerCard=document.getElementById('broker-home-card'); var visitorChoices=document.getElementById('visitor-choices'); var ownerZone=document.getElementById('owner-zone'); var pendingPreview=document.getElementById('home-pending-preview'); var myAdsCard=document.getElementById('my-ads-card'); if(!brokerCard) return; if(profile){ if(visitorChoices) visitorChoices.style.display='none'; if(ownerZone) ownerZone.style.display='none'; if(pendingPreview) pendingPreview.innerHTML=''; if(myAdsCard) myAdsCard.style.display='none'; brokerCard.style.display='block'; var nameEl=document.getElementById('broker-home-name'); var phoneEl=document.getElementById('broker-home-phone'); var typeEl=document.getElementById('broker-home-type'); var avatarEl=document.getElementById('broker-home-avatar'); if(nameEl) nameEl.textContent='مرحباً، '+profile.name; if(phoneEl) phoneEl.textContent='📱 '+profile.phone; if(typeEl){ var verifiedMark = profile.verified ? ' ✓ موثق' : ''; typeEl.innerHTML = (profile.accountType==='سمسار'?'🤝 سمسار':'🏠 مالك') + verifiedMark; } // تحديث معلومات التوثيق var s = loadSettings(); var vPrice = document.getElementById('verify-price-display'); var vPhone = document.getElementById('verify-vodafone-display'); if(vPrice) vPrice.textContent = s.verifyPrice || '100'; if(vPhone) vPhone.textContent = s.vodafoneNum || '01005581620'; if(avatarEl){ if(profile.photo){ avatarEl.innerHTML=''; } else { avatarEl.textContent=profile.accountType==='سمسار'?'🤝':'🏠'; } } } else { if(visitorChoices) visitorChoices.style.display='block'; brokerCard.style.display='none'; } } function fillAddFormFromProfile(){ var profile=loadBrokerProfile(); var bar=document.getElementById('add-broker-bar'); var nameGroup=document.getElementById('add-name-group'); var phoneGroup=document.getElementById('add-phone-group'); var phoneInput=document.getElementById('phone'); var nameInput=document.getElementById('owner-name'); if(profile){ if(bar) bar.style.display='flex'; if(nameGroup) nameGroup.style.display='none'; if(phoneGroup) phoneGroup.style.display='none'; var nl=document.getElementById('add-broker-name-lbl'); var pl=document.getElementById('add-broker-phone-lbl'); var tl=document.getElementById('add-broker-type-lbl'); var av=document.getElementById('add-broker-avatar'); var avImg=document.getElementById('add-broker-avatar-img'); if(nl) nl.textContent=profile.name; if(pl) pl.textContent='📱 '+profile.phone; if(tl) tl.textContent=profile.accountType==='سمسار'?'🤝 سمسار':'🏠 مالك'; if(av && profile.photo){ av.style.position='relative'; if(avImg){avImg.src=profile.photo;avImg.style.display='block';} } if(nameInput) nameInput.value=profile.name; if(phoneInput) phoneInput.value=profile.phone; } else { if(bar) bar.style.display='none'; if(nameGroup) nameGroup.style.display='block'; if(phoneGroup) phoneGroup.style.display='block'; } } function loadRegisterForm(){ var profile=loadBrokerProfile(); _regAccountType=''; document.getElementById('acc-broker').classList.remove('on'); document.getElementById('acc-owner').classList.remove('on'); if(profile){ _regAccountType=profile.accountType; document.getElementById('acc-broker').classList.toggle('on',profile.accountType==='سمسار'); document.getElementById('acc-owner').classList.toggle('on',profile.accountType==='مالك'); document.getElementById('reg-name').value=profile.name||''; document.getElementById('reg-phone').value=profile.phone||''; var icon=document.getElementById('reg-avatar-icon'); var img=document.getElementById('reg-avatar-img'); if(profile.photo&&img){ if(icon) icon.style.display='none'; img.src=profile.photo; img.style.display='block'; document._regPhotoData=profile.photo; } else { if(icon) icon.style.display=''; if(img) img.style.display='none'; document._regPhotoData=''; } } else { document.getElementById('reg-name').value=''; document.getElementById('reg-phone').value=''; var icon2=document.getElementById('reg-avatar-icon'); var img2=document.getElementById('reg-avatar-img'); if(icon2) icon2.style.display=''; if(img2) img2.style.display='none'; document._regPhotoData=''; } } /* ════════ SCROLL TO TOP ════════ */ window.addEventListener('scroll', function(){ var btn=document.getElementById('scroll-top-btn'); if(!btn) return; if(window.scrollY > 300) btn.classList.add('visible'); else btn.classList.remove('visible'); }, {passive:true}); /* ════════ ADMIN COPY PHONE ════════ */ function copyPhone(phone){ navigator.clipboard.writeText(phone).then(()=>toast('✅ تم نسخ الرقم: '+phone)).catch(()=>toast('📞 '+phone)); }