👤

جاري التحميل...

---
0 نقطة | 🥉 برونزي

المعلومات الشخصية

طلباتي

جاري تحميل طلباتك...

⭐ نقاط الولاء

0
نقاطك الحالية
🥉
برونزي
مستواك الحالي
💰
0 ر.س
قيمة نقاطك

🎯 التقدم للمستوى التالي

برونزي 0 / 1000 نقطة فضي

🎁 المكافآت المتاحة

📜 سجل النقاط

جاري تحميل السجل...

🎟️ أكواد الخصم الخاصة بي

جاري تحميل الأكواد...

💳 محفظتي

الرصيد المتاح
0.00
ريال سعودي
💡 يمكنك استخدام رصيد المحفظة للدفع عند إتمام طلبك. يتم إضافة الرصيد تلقائياً عند استرداد مبالغ المرتجعات.

📜 سجل الحركات

📋

جاري تحميل الحركات...

معلومات الحساب

تفاصيل الحساب

البريد الإلكتروني ---
رقم الحساب ---
تاريخ التسجيل ---
نوع الحساب عميل

إحصائيات

عدد الطلبات 0
إجمالي المشتريات 0 ر.س

🔒 تغيير كلمة المرور

⚠️ لتغيير كلمة المرور، سنرسل رسالة إعادة تعيين إلى بريدك الإلكتروني.
`; const existingModal = document.getElementById('orderModal'); if (existingModal) existingModal.remove(); document.body.insertAdjacentHTML('beforeend', modalHTML); document.body.style.overflow = 'hidden'; } catch (error) { console.error('Error viewing order:', error); alert('حدث خطأ أثناء عرض تفاصيل الطلب'); } }; window.closeOrderModal = function() { const modal = document.getElementById('orderModal'); if (modal) { modal.remove(); document.body.style.overflow = ''; } }; document.addEventListener('keydown', function(e) { if (e.key === 'Escape') closeOrderModal(); }); // Profile menu navigation (UNCHANGED logic) document.querySelectorAll('.profile-menu a').forEach(link => { link.addEventListener('click', (e) => { const href = link.getAttribute('href'); if (href && href !== '#' && !href.startsWith('#')) return; e.preventDefault(); document.querySelectorAll('.profile-menu a').forEach(l => l.classList.remove('active')); document.querySelectorAll('.profile-section').forEach(s => s.classList.remove('active')); link.classList.add('active'); const sectionId = link.dataset.section; if (sectionId) document.getElementById(sectionId).classList.add('active'); }); }); // Personal info form (UNCHANGED) document.getElementById('personalInfoForm').addEventListener('submit', async (e) => { e.preventDefault(); if (!currentUser) return; const name = document.getElementById('userName').value.trim(); const phone = document.getElementById('userPhone').value.trim(); const city = document.getElementById('userCity').value; const district = document.getElementById('userDistrict').value.trim(); const street = document.getElementById('userStreet').value.trim(); const building = document.getElementById('userBuilding').value.trim(); const zip = document.getElementById('userZip').value.trim(); if (!name || !phone) { alert('⚠️ الاسم ورقم الجوال مطلوبين'); return; } const userData = { name, phone, city, district, street, building, zip, shippingAddress: { name, phone, city, district, street, building, zip }, updatedAt: new Date().toISOString() }; try { await setDoc(doc(db, 'users', currentUser.uid), userData, { merge: true }); document.getElementById('profileName').textContent = userData.name; document.getElementById('profileAvatar').textContent = userData.name.charAt(0).toUpperCase(); document.getElementById('accountText').textContent = userData.name; alert('✅ تم حفظ التغييرات بنجاح!'); } catch (error) { console.error('Error updating profile:', error); alert('❌ حدث خطأ أثناء حفظ التغييرات'); } }); // Change password form (UNCHANGED) document.getElementById('changePasswordForm').addEventListener('submit', async (e) => { e.preventDefault(); if (!currentUser) return; try { await sendPasswordResetEmail(auth, currentUser.email); alert('✅ تم إرسال رابط إعادة تعيين كلمة المرور إلى بريدك الإلكتروني!'); } catch (error) { console.error('Error sending reset email:', error); alert('❌ حدث خطأ أثناء إرسال الرسالة'); } }); // ============================================ // LOYALTY POINTS FUNCTIONS (UNCHANGED) // ============================================ let loyaltySettings = { earnPerAmount: 1, earnPoints: 1, redeemPoints: 100, redeemValue: 10, silverThreshold: 1000, goldThreshold: 5000, platinumThreshold: 10000 }; const defaultRewards = [ { id: 1, name: 'خصم 5%', points: 200, icon: '🏷️', desc: 'خصم على طلبك التالي', discount: 5, type: 'percent' }, { id: 2, name: 'خصم 10%', points: 500, icon: '🎫', desc: 'خصم مميز على طلبك', discount: 10, type: 'percent' }, { id: 3, name: 'شحن مجاني', points: 300, icon: '🚚', desc: 'توصيل مجاني لطلبك', discount: 0, type: 'shipping' }, { id: 4, name: 'خصم 20%', points: 1000, icon: '🎁', desc: 'خصم كبير على طلبك', discount: 20, type: 'percent' }, { id: 5, name: 'قسيمة 50 ر.س', points: 500, icon: '💵', desc: 'قسيمة شرائية', discount: 50, type: 'fixed' }, { id: 6, name: 'قسيمة 100 ر.س', points: 1000, icon: '💰', desc: 'قسيمة شرائية مميزة', discount: 100, type: 'fixed' } ]; async function loadLoyaltyData(userId, userData) { try { const settingsDoc = await getDoc(doc(db, 'settings', 'loyaltyProgram')); if (settingsDoc.exists()) loyaltySettings = { ...loyaltySettings, ...settingsDoc.data() }; let points = userData.loyaltyPoints || 0; if (points === 0) { const ordersQuery = query(collection(db, 'orders'), where('userId', '==', userId), where('status', '==', 'delivered')); const ordersSnap = await getDocs(ordersQuery); let totalSpent = 0; ordersSnap.forEach(doc => { const order = doc.data(); totalSpent += order.total || order.totalAmount || 0; }); points = Math.floor(totalSpent / loyaltySettings.earnPerAmount) * loyaltySettings.earnPoints; } const tier = getTier(points); updateLoyaltyUI(points, tier); loadRewards(points); loadPointsHistory(userId); loadUserCoupons(userId); } catch (error) { console.error('Error loading loyalty data:', error); } } function getTier(points) { if (points >= loyaltySettings.platinumThreshold) return { name: 'بلاتيني', icon: '💎', color: '#e5e4e2', next: null, nextThreshold: null }; if (points >= loyaltySettings.goldThreshold) return { name: 'ذهبي', icon: '🥇', color: '#ffd700', next: 'بلاتيني', nextThreshold: loyaltySettings.platinumThreshold }; if (points >= loyaltySettings.silverThreshold) return { name: 'فضي', icon: '🥈', color: '#c0c0c0', next: 'ذهبي', nextThreshold: loyaltySettings.goldThreshold }; return { name: 'برونزي', icon: '🥉', color: '#cd7f32', next: 'فضي', nextThreshold: loyaltySettings.silverThreshold }; } function updateLoyaltyUI(points, tier) { document.getElementById('headerPoints').textContent = points.toLocaleString(); document.getElementById('headerTier').textContent = tier.icon + ' ' + tier.name; document.getElementById('totalPoints').textContent = points.toLocaleString(); document.getElementById('tierIcon').textContent = tier.icon; document.getElementById('tierName').textContent = tier.name; const pointsValue = (points / loyaltySettings.redeemPoints) * loyaltySettings.redeemValue; document.getElementById('pointsValue').textContent = pointsValue.toFixed(2) + ' ر.س'; if (tier.nextThreshold) { const prevThreshold = tier.name === 'برونزي' ? 0 : tier.name === 'فضي' ? loyaltySettings.silverThreshold : loyaltySettings.goldThreshold; const progress = ((points - prevThreshold) / (tier.nextThreshold - prevThreshold)) * 100; document.getElementById('tierProgress').style.width = Math.min(progress, 100) + '%'; document.getElementById('currentTierLabel').textContent = tier.icon + ' ' + tier.name; document.getElementById('nextTierLabel').textContent = tier.next; document.getElementById('progressText').textContent = points.toLocaleString() + ' / ' + tier.nextThreshold.toLocaleString() + ' نقطة'; } else { document.getElementById('tierProgress').style.width = '100%'; document.getElementById('currentTierLabel').textContent = tier.icon + ' ' + tier.name; document.getElementById('nextTierLabel').textContent = '🏆 أعلى مستوى'; document.getElementById('progressText').textContent = 'مبروك! وصلت لأعلى مستوى'; } } function loadRewards(userPoints) { const grid = document.getElementById('rewardsGrid'); let html = ''; defaultRewards.forEach(reward => { const canRedeem = userPoints >= reward.points; html += `
${reward.icon}
${reward.name}
${reward.desc}
⭐ ${reward.points} نقطة
`; }); grid.innerHTML = html; } async function loadPointsHistory(userId) { const historyList = document.getElementById('historyList'); try { const historyQuery = query(collection(db, 'pointsHistory'), where('userId', '==', userId), orderBy('createdAt', 'desc')); const historySnap = await getDocs(historyQuery); if (historySnap.empty) { historyList.innerHTML = `
📜
لا يوجد سجل نقاط حتى الآن
`; return; } let html = ''; historySnap.forEach(doc => { const item = doc.data(); const isEarned = item.type === 'earned'; const date = item.createdAt?.toDate?.() || new Date(); html += `
${isEarned ? '⬆️' : '⬇️'}
${item.description || (isEarned ? 'نقاط مكتسبة' : 'نقاط مستبدلة')}
${date.toLocaleDateString('ar-SA')}
${item.couponCode ? `
🎟️ الكود: ${item.couponCode}
` : ''}
${isEarned ? '+' : '-'}${item.points}
`; }); historyList.innerHTML = html; } catch (error) { console.error('Error loading history:', error); historyList.innerHTML = `
لا يوجد سجل نقاط حتى الآن
`; } } window.redeemReward = async function(rewardId, rewardName, requiredPoints, discount, discountType) { if (!currentUser) { alert('يرجى تسجيل الدخول أولاً'); return; } if (!confirm(`هل تريد استبدال ${requiredPoints} نقطة بـ "${rewardName}"؟`)) return; try { const userDoc = await getDoc(doc(db, 'users', currentUser.uid)); const userData = userDoc.data() || {}; const currentPoints = userData.loyaltyPoints || 0; if (currentPoints < requiredPoints) { alert('❌ نقاطك غير كافية'); return; } const couponCode = 'LOYALTY-' + Date.now().toString(36).toUpperCase(); await addDoc(collection(db, 'promoCodes'), { code: couponCode, description: rewardName + ' - استبدال نقاط', discountType: discountType === 'percent' ? 'percentage' : discountType === 'shipping' ? 'freeShipping' : 'fixed', discountValue: discount, isActive: true, forAllCustomers: false, specificUserId: currentUser.uid, maxUses: 1, usageCount: 0, startDate: new Date().toISOString(), endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(), fromLoyalty: true, createdAt: serverTimestamp() }); const newPoints = currentPoints - requiredPoints; await updateDoc(doc(db, 'users', currentUser.uid), { loyaltyPoints: newPoints }); await addDoc(collection(db, 'pointsHistory'), { userId: currentUser.uid, type: 'redeemed', points: requiredPoints, description: 'استبدال: ' + rewardName, couponCode: couponCode, createdAt: serverTimestamp() }); alert(`✅ تم الاستبدال بنجاح!\n\nكود الخصم: ${couponCode}\n\nيمكنك استخدامه في طلبك التالي خلال 30 يوم\n\nتم نسخ الكود!`); navigator.clipboard.writeText(couponCode).catch(() => {}); await loadLoyaltyData(currentUser.uid, { ...userData, loyaltyPoints: newPoints }); } catch (error) { console.error('Error redeeming reward:', error); alert('❌ حدث خطأ أثناء الاستبدال'); } }; async function loadUserCoupons(userId) { const couponsList = document.getElementById('couponsList'); try { const couponsQuery = query(collection(db, 'promoCodes'), where('specificUserId', '==', userId), where('fromLoyalty', '==', true)); const couponsSnap = await getDocs(couponsQuery); if (couponsSnap.empty) { couponsList.innerHTML = `
🎟️
لا توجد أكواد خصم حتى الآن
استبدل نقاطك للحصول على أكواد خصم
`; return; } let html = ''; const now = new Date(); couponsSnap.forEach(docSnap => { const coupon = docSnap.data(); const endDate = coupon.endDate ? new Date(coupon.endDate) : null; const isExpired = endDate && endDate < now; const isUsed = coupon.usageCount >= (coupon.maxUses || 1); let statusClass = ''; let statusText = '✅ نشط'; if (isUsed) { statusClass = 'used'; statusText = '✓ مستخدم'; } else if (isExpired) { statusClass = 'expired'; statusText = '⏰ منتهي'; } const discountText = coupon.discountType === 'percentage' ? coupon.discountValue + '%' : coupon.discountType === 'freeShipping' ? 'شحن مجاني' : coupon.discountValue + ' ر.س'; html += `
${coupon.description || 'كود خصم'} ${statusText}
${coupon.code}
`; }); couponsList.innerHTML = html; } catch (error) { console.error('Error loading coupons:', error); couponsList.innerHTML = `
لا توجد أكواد خصم حتى الآن
`; } } window.copyCoupon = function(code) { navigator.clipboard.writeText(code).then(() => { alert('✅ تم نسخ الكود: ' + code); }).catch(() => { prompt('انسخ الكود:', code); }); }; // ============================================ // WALLET FUNCTIONS (UNCHANGED) // ============================================ async function loadWalletData(userId, userData) { try { const walletBalance = userData.walletBalance || 0; document.getElementById('walletBalance').textContent = walletBalance.toFixed(2); const walletBadge = document.getElementById('walletBadge'); if (walletBalance > 0) { walletBadge.textContent = walletBalance.toFixed(0); walletBadge.style.display = 'inline-block'; } else { walletBadge.style.display = 'none'; } await loadWalletTransactions(userId); } catch (error) { console.error('Error loading wallet data:', error); } } async function loadWalletTransactions(userId) { const transactionsList = document.getElementById('transactionsList'); try { const transQuery = query(collection(db, 'walletTransactions'), where('userId', '==', userId), orderBy('createdAt', 'desc')); const transSnap = await getDocs(transQuery); if (transSnap.empty) { transactionsList.innerHTML = `
📋

لا توجد حركات في المحفظة حتى الآن

ستظهر هنا حركات الإيداع والسحب
`; return; } let html = ''; transSnap.forEach(docSnap => { const trans = docSnap.data(); const isCredit = trans.type === 'credit'; const date = trans.createdAt?.toDate?.() || new Date(); html += `
${isCredit ? '⬇️' : '⬆️'}
${trans.description || (isCredit ? 'إيداع' : 'سحب')}
${date.toLocaleDateString('ar-SA')} - ${date.toLocaleTimeString('ar-SA', { hour: '2-digit', minute: '2-digit' })}
${trans.reference ? `
${trans.reference}
` : ''}
${isCredit ? '+' : '-'}${trans.amount?.toFixed(2)} ر.س
`; }); transactionsList.innerHTML = html; } catch (error) { console.error('Error loading transactions:', error); transactionsList.innerHTML = `
📋

لا توجد حركات في المحفظة

`; } } // Update cart badge try { const c = JSON.parse(localStorage.getItem('cart') || '[]'); const count = c.reduce((s, i) => s + (i.quantity || 1), 0); ['cartBadgeNew', 'mhCartBadge'].forEach(id => { const el = document.getElementById(id); if (el) { el.textContent = count; el.style.display = count > 0 ? '' : 'none'; } }); } catch {} // Logout flow with custom modal const logoutModal = document.getElementById('logoutModal'); const logoutCancelBtn = document.getElementById('logoutCancelBtn'); const logoutConfirmBtn = document.getElementById('logoutConfirmBtn'); function openLogoutModal(e) { e.preventDefault(); if (logoutModal) logoutModal.style.display = 'flex'; document.body.style.overflow = 'hidden'; } function closeLogoutModal() { if (logoutModal) logoutModal.style.display = 'none'; document.body.style.overflow = ''; } document.getElementById('profileLogoutBtn')?.addEventListener('click', openLogoutModal); logoutCancelBtn?.addEventListener('click', closeLogoutModal); logoutModal?.querySelector('.logout-modal-overlay')?.addEventListener('click', closeLogoutModal); logoutConfirmBtn?.addEventListener('click', async () => { logoutConfirmBtn.disabled = true; logoutConfirmBtn.textContent = 'جاري الخروج...'; try { await signOut(auth); window.location.href = '/index.html'; } catch (error) { console.error('Logout error:', error); logoutConfirmBtn.disabled = false; logoutConfirmBtn.textContent = 'نعم، تسجيل خروج'; alert('حدث خطأ أثناء تسجيل الخروج'); } }); document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && logoutModal && logoutModal.style.display === 'flex') closeLogoutModal(); });