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79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// نظام المصادقة والأمان
class AuthenticationManager {
    constructor() {
        this.currentUser = null;
        this.sessionTimeout = 15 * 60 * 1000; // 15 دقيقة
        this.maxLoginAttempts = 3;
        this.lockoutDuration = 30 * 60 * 1000; // 30 دقيقة
        this.biometricCredential = null;
        
        this.init();
    }

    // تهيئة نظام المصادقة
    init() {
        this.setupSessionManagement();
        this.loadStoredCredentials();
        this.checkBiometricSupport();
    }

    // إعداد إدارة الجلسة
    setupSessionManagement() {
        // تحديث وقت النشاط عند التفاعل
        document.addEventListener('click', () => this.updateLastActivity());
        document.addEventListener('keypress', () => this.updateLastActivity());
        document.addEventListener('touchstart', () => this.updateLastActivity());

        // فحص انتهاء الجلسة كل دقيقة
        setInterval(() => this.checkSessionExpiry(), 60000);
    }

    // تسجيل دخول بالرقم ورمز PIN
    async loginWithPin(phoneNumber, pin) {
        try {
            // التحقق من محاولات تسجيل الدخول
            if (this.isAccountLocked(phoneNumber)) {
                const lockoutTime = this.getLockoutRemainingTime(phoneNumber);
                throw new Error(`الحساب مقفل. المحاولة مرة أخرى خلال ${Math.ceil(lockoutTime / 60000)} دقيقة`);
            }

            // التحقق من صحة البيانات
            if (!this.validatePhoneNumber(phoneNumber)) {
                throw new Error('رقم الهاتف غير صحيح');
            }

            if (!this.validatePin(pin)) {
                throw new Error('رمز PIN يجب أن يكون 4-6 أرقام');
            }

            // محاكاة التحقق من البيانات
            const isValid = await this.verifyCredentials(phoneNumber, pin);
            
            if (!isValid) {
                this.recordFailedAttempt(phoneNumber);
                const remainingAttempts = this.getRemainingAttempts(phoneNumber);
                
                if (remainingAttempts <= 0) {
                    this.lockAccount(phoneNumber);
                    throw new Error('تم قفل الحساب بسبب المحاولات الخاطئة المتكررة');
                }
                
                throw new Error(`بيانات تسجيل الدخول غير صحيحة. المحاولات المتبقية: ${remainingAttempts}`);
            }

            // تسجيل دخول ناجح
            this.clearFailedAttempts(phoneNumber);
            const user = await this.createUserSession(phoneNumber, pin);
            
            return user;

        } catch (error) {
            console.error('خطأ في تسجيل الدخول:', error);
            throw error;
        }
    }

    // تسجيل دخول بالبصمة
    async loginWithBiometric() {
        try {
            if (!this.isBiometricSupported()) {
                throw new Error('المصادقة البيومترية غير مدعومة في هذا المتصفح');
            }

            if (!this.biometricCredential) {
                throw new Error('لم يتم تسجيل بصمة مسبقاً. يرجى تسجيل الدخول برمز PIN أولاً');
            }

            // التحقق من البصمة
            const credential = await navigator.credentials.get({
                publicKey: {
                    challenge: this.generateChallenge(),
                    allowCredentials: [{
                        type: 'public-key',
                        id: this.biometricCredential.id
                    }],
                    timeout: 60000,
                    userVerification: 'required'
                }
            });

            if (!credential) {
                throw new Error('فشل في التحقق من البصمة');
            }

            // إنشاء جلسة المستخدم
            const savedUser = this.getStoredUser();
            if (!savedUser) {
                throw new Error('لم يتم العثور على بيانات المستخدم');
            }

            const user = await this.createUserSession(savedUser.phone, null, 'biometric');
            return user;

        } catch (error) {
            console.error('خطأ في تسجيل الدخول بالبصمة:', error);
            throw error;
        }
    }

    // تسجيل البصمة
    async registerBiometric(phoneNumber) {
        try {
            if (!this.isBiometricSupported()) {
                throw new Error('المصادقة البيومترية غير مدعومة');
            }

            const credential = await navigator.credentials.create({
                publicKey: {
                    challenge: this.generateChallenge(),
                    rp: {
                        name: 'محفظتي الموحدة',
                        id: window.location.hostname
                    },
                    user: {
                        id: new TextEncoder().encode(phoneNumber),
                        name: phoneNumber,
                        displayName: `مستخدم ${phoneNumber}`
                    },
                    pubKeyCredParams: [{
                        type: 'public-key',
                        alg: -7 // ES256
                    }],
                    timeout: 60000,
                    attestation: 'none',
                    authenticatorSelection: {
                        authenticatorAttachment: 'platform',
                        userVerification: 'required'
                    }
                }
            });

            if (!credential) {
                throw new Error('فشل في تسجيل البصمة');
            }

            // حفظ بيانات البصمة
            this.biometricCredential = {
                id: credential.rawId,
                publicKey: credential.response.publicKey,
                phoneNumber: phoneNumber,
                registeredAt: new Date().toISOString()
            };

            this.storeBiometricCredential();
            return true;

        } catch (error) {
            console.error('خطأ في تسجيل البصمة:', error);
            throw error;
        }
    }

    // إنشاء جلسة مستخدم
    async createUserSession(phoneNumber, pin, authMethod = 'pin') {
        const user = {
            id: this.generateUserId(),
            phone: phoneNumber,
            name: this.extractNameFromPhone(phoneNumber),
            authMethod: authMethod,
            loginTime: new Date().toISOString(),
            lastActivity: new Date().toISOString(),
            sessionId: this.generateSessionId()
        };

        this.currentUser = user;
        this.storeUserSession(user);
        this.updateLastActivity();

        return user;
    }

    // تسجيل الخروج
    logout() {
        this.currentUser = null;
        this.clearUserSession();
        this.clearStoredCredentials();
        
        // إعادة توجيه لشاشة تسجيل الدخول
        if (window.app) {
            window.app.switchScreen('login');
        }
    }

    // التحقق من صحة الجلسة
    isSessionValid() {
        if (!this.currentUser) {
            return false;
        }

        const lastActivity = new Date(this.currentUser.lastActivity);
        const now = new Date();
        const timeDiff = now.getTime() - lastActivity.getTime();

        return timeDiff < this.sessionTimeout;
    }

    // فحص انتهاء الجلسة
    checkSessionExpiry() {
        if (this.currentUser && !this.isSessionValid()) {
            this.showSessionExpiredDialog();
        }
    }

    // عرض حوار انتهاء الجلسة
    showSessionExpiredDialog() {
        if (confirm('انتهت صلاحية الجلسة. هل تريد تسجيل الدخول مرة أخرى؟')) {
            this.logout();
        } else {
            this.logout();
        }
    }

    // تحديث وقت النشاط الأخير
    updateLastActivity() {
        if (this.currentUser) {
            this.currentUser.lastActivity = new Date().toISOString();
            this.storeUserSession(this.currentUser);
        }
    }

    // التحقق من قفل الحساب
    isAccountLocked(phoneNumber) {
        const lockData = this.getLockData(phoneNumber);
        if (!lockData) return false;

        const now = new Date().getTime();
        return now < lockData.lockedUntil;
    }

    // الحصول على الوقت المتبقي للقفل
    getLockoutRemainingTime(phoneNumber) {
        const lockData = this.getLockData(phoneNumber);
        if (!lockData) return 0;

        const now = new Date().getTime();
        return Math.max(0, lockData.lockedUntil - now);
    }

    // تسجيل محاولة فاشلة
    recordFailedAttempt(phoneNumber) {
        const attempts = this.getFailedAttempts(phoneNumber);
        attempts.push(new Date().toISOString());
        
        localStorage.setItem(`failed_attempts_${phoneNumber}`, JSON.stringify(attempts));
    }

    // الحصول على المحاولات الفاشلة
    getFailedAttempts(phoneNumber) {
        const stored = localStorage.getItem(`failed_attempts_${phoneNumber}`);
        return stored ? JSON.parse(stored) : [];
    }

    // الحصول على المحاولات المتبقية
    getRemainingAttempts(phoneNumber) {
        const attempts = this.getFailedAttempts(phoneNumber);
        return Math.max(0, this.maxLoginAttempts - attempts.length);
    }

    // قفل الحساب
    lockAccount(phoneNumber) {
        const lockData = {
            lockedAt: new Date().toISOString(),
            lockedUntil: new Date().getTime() + this.lockoutDuration
        };
        
        localStorage.setItem(`account_lock_${phoneNumber}`, JSON.stringify(lockData));
    }

    // الحصول على بيانات القفل
    getLockData(phoneNumber) {
        const stored = localStorage.getItem(`account_lock_${phoneNumber}`);
        return stored ? JSON.parse(stored) : null;
    }

    // مسح المحاولات الفاشلة
    clearFailedAttempts(phoneNumber) {
        localStorage.removeItem(`failed_attempts_${phoneNumber}`);
        localStorage.removeItem(`account_lock_${phoneNumber}`);
    }

    // التحقق من صحة رقم الهاتف
    validatePhoneNumber(phoneNumber) {
        return /^7[0-9]{8}$/.test(phoneNumber);
    }

    // التحقق من صحة رمز PIN
    validatePin(pin) {
        return /^[0-9]{4,6}$/.test(pin);
    }

    // محاكاة التحقق من البيانات
    async verifyCredentials(phoneNumber, pin) {
        // محاكاة استدعاء API
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // في التطبيق الحقيقي، سيتم التحقق من البيانات مع الخادم
        // للتجربة، نقبل أي رقم هاتف صحيح ورمز PIN من 4-6 أرقام
        return this.validatePhoneNumber(phoneNumber) && this.validatePin(pin);
    }

    // فحص دعم المصادقة البيومترية
    isBiometricSupported() {
        return window.PublicKeyCredential && 
               PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable;
    }

    // فحص دعم المصادقة البيومترية
    async checkBiometricSupport() {
        if (this.isBiometricSupported()) {
            try {
                const available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
                return available;
            } catch (error) {
                console.warn('خطأ في فحص دعم المصادقة البيومترية:', error);
                return false;
            }
        }
        return false;
    }

    // توليد تحدي للمصادقة البيومترية
    generateChallenge() {
        const array = new Uint8Array(32);
        crypto.getRandomValues(array);
        return array;
    }

    // توليد معرف مستخدم
    generateUserId() {
        return 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    // توليد معرف جلسة
    generateSessionId() {
        return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    // استخراج اسم من رقم الهاتف
    extractNameFromPhone(phoneNumber) {
        return `مستخدم ${phoneNumber.substr(-4)}`;
    }

    // حفظ جلسة المستخدم
    storeUserSession(user) {
        localStorage.setItem('unifiedWallet_session', JSON.stringify(user));
    }

    // تحميل جلسة المستخدم
    loadStoredSession() {
        const stored = localStorage.getItem('unifiedWallet_session');
        if (stored) {
            const user = JSON.parse(stored);
            if (this.isSessionValid()) {
                this.currentUser = user;
                return user;
            } else {
                this.clearUserSession();
            }
        }
        return null;
    }

    // مسح جلسة المستخدم
    clearUserSession() {
        localStorage.removeItem('unifiedWallet_session');
    }

    // حفظ بيانات البصمة
    storeBiometricCredential() {
        if (this.biometricCredential) {
            localStorage.setItem('unifiedWallet_biometric', JSON.stringify(this.biometricCredential));
        }
    }

    // تحميل بيانات البصمة
    loadStoredCredentials() {
        const stored = localStorage.getItem('unifiedWallet_biometric');
        if (stored) {
            this.biometricCredential = JSON.parse(stored);
        }
    }

    // مسح بيانات البصمة
    clearStoredCredentials() {
        localStorage.removeItem('unifiedWallet_biometric');
        this.biometricCredential = null;
    }

    // الحصول على المستخدم المحفوظ
    getStoredUser() {
        const stored = localStorage.getItem('unifiedWallet_user');
        return stored ? JSON.parse(stored) : null;
    }

    // الحصول على المستخدم الحالي
    getCurrentUser() {
        return this.currentUser;
    }

    // التحقق من تسجيل الدخول
    isLoggedIn() {
        return this.currentUser !== null && this.isSessionValid();
    }
}

// تصدير الكلاس للاستخدام في التطبيق الرئيسي
window.AuthenticationManager = AuthenticationManager;