File size: 12,317 Bytes
a9b4899
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
class ModalComponent {
    static showLogin() {
        const modalHTML = `
            <div class="modal-overlay active" id="loginModal">
                <div class="modal-content">
                    <button class="modal-close" onclick="ModalComponent.closeCurrentModal()">&times;</button>
                    <div class="modal-header">
                        <h3>🔐 ورود به سیستم</h3>
                    </div>
                    <div class="modal-body">
                        <form id="modalLoginForm">
                            <div class="form-group">
                                <label for="modalUsername">نام کاربری</label>
                                <input type="text" id="modalUsername" name="username" required>
                            </div>
                            <div class="form-group">
                                <label for="modalPassword">رمز عبور</label>
                                <input type="password" id="modalPassword" name="password" required>
                            </div>
                            <button type="submit" class="btn btn-primary btn-block">ورود</button>
                        </form>
                        
                        <div class="auth-links">
                            <p>حساب کاربری ندارید؟ <a href="register.html">ثبت نام کنید</a></p>
                        </div>
                        
                        <div class="demo-accounts">
                            <h4>حساب‌های آزمایشی:</h4>
                            <div class="demo-account">
                                <strong>student</strong> / <strong>password123</strong>
                            </div>
                            <div class="demo-account">
                                <strong>admin</strong> / <strong>admin123</strong>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        this.showCustomModal('login-modal', modalHTML);
        this.setupLoginForm();
    }

    static showRegister() {
        const modalHTML = `
            <div class="modal-overlay active" id="registerModal">
                <div class="modal-content">
                    <button class="modal-close" onclick="ModalComponent.closeCurrentModal()">&times;</button>
                    <div class="modal-header">
                        <h3>📝 ثبت نام</h3>
                    </div>
                    <div class="modal-body">
                        <form id="modalRegisterForm">
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="modalFirstName">نام</label>
                                    <input type="text" id="modalFirstName" name="firstName">
                                </div>
                                <div class="form-group">
                                    <label for="modalLastName">نام خانوادگی</label>
                                    <input type="text" id="modalLastName" name="lastName">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="modalRegUsername">نام کاربری *</label>
                                <input type="text" id="modalRegUsername" name="username" required>
                            </div>
                            <div class="form-group">
                                <label for="modalRegEmail">ایمیل *</label>
                                <input type="email" id="modalRegEmail" name="email" required>
                            </div>
                            <div class="form-group">
                                <label for="modalRegPassword">رمز عبور *</label>
                                <input type="password" id="modalRegPassword" name="password" required>
                            </div>
                            <div class="form-group">
                                <label for="modalRegConfirmPassword">تکرار رمز عبور *</label>
                                <input type="password" id="modalRegConfirmPassword" name="confirmPassword" required>
                            </div>
                            <button type="submit" class="btn btn-primary btn-block">ثبت نام</button>
                        </form>
                        
                        <div class="auth-links">
                            <p>قبلاً ثبت نام کرده‌اید؟ <a href="login.html">وارد شوید</a></p>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        this.showCustomModal('register-modal', modalHTML);
        this.setupRegisterForm();
    }

    static showCustomModal(modalId, contentHTML) {
        // بستن مودال قبلی
        this.closeCurrentModal();

        const modalContainer = document.getElementById('modalContainer');
        if (!modalContainer) return;

        const modalElement = document.createElement('div');
        modalElement.id = modalId;
        modalElement.innerHTML = contentHTML;
        modalContainer.appendChild(modalElement);

        // بستن مودال با کلیک روی overlay
        const overlay = modalElement.querySelector('.modal-overlay');
        if (overlay) {
            overlay.addEventListener('click', (e) => {
                if (e.target === overlay) {
                    this.closeCurrentModal();
                }
            });
        }

        // بستن مودال با کلید Escape
        const escapeHandler = (e) => {
            if (e.key === 'Escape') {
                this.closeCurrentModal();
                document.removeEventListener('keydown', escapeHandler);
            }
        };
        document.addEventListener('keydown', escapeHandler);

        // ذخیره handler برای حذف بعدی
        modalElement._escapeHandler = escapeHandler;
    }

    static closeCurrentModal() {
        const modalContainer = document.getElementById('modalContainer');
        if (!modalContainer) return;

        // حذف همه مودال‌ها
        while (modalContainer.firstChild) {
            const modal = modalContainer.firstChild;
            if (modal._escapeHandler) {
                document.removeEventListener('keydown', modal._escapeHandler);
            }
            modalContainer.removeChild(modal);
        }
    }

    static setupLoginForm() {
        const loginForm = document.getElementById('modalLoginForm');
        if (!loginForm) return;

        loginForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData(loginForm);
            const data = {
                username: formData.get('username').trim(),
                password: formData.get('password')
            };

            // اعتبارسنجی
            const validation = ValidationMiddleware.validateLoginData(data);
            if (!validation.isValid) {
                Utils.showNotification(validation.errors.join(' • '), 'error');
                return;
            }

            const submitBtn = loginForm.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.disabled = true;
            submitBtn.textContent = '⏳ در حال ورود...';

            try {
                const result = authManager.loginUser(data.username, data.password);
                
                if (result.success) {
                    authManager.setToken(result.token);
                    authManager.setCurrentUser(result.user);
                    
                    Utils.showNotification('ورود موفقیت‌آمیز!', 'success');
                    this.closeCurrentModal();
                    
                    // ارسال event برای به‌روزرسانی UI
                    document.dispatchEvent(new CustomEvent('authStateChanged'));
                    
                } else {
                    Utils.showNotification(result.message, 'error');
                }
            } catch (error) {
                console.error('Login error:', error);
                Utils.showNotification('خطا در ورود به سیستم', 'error');
            } finally {
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });
    }

    static setupRegisterForm() {
        const registerForm = document.getElementById('modalRegisterForm');
        if (!registerForm) return;

        registerForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData(registerForm);
            const data = {
                firstName: formData.get('firstName')?.trim(),
                lastName: formData.get('lastName')?.trim(),
                username: formData.get('username').trim(),
                email: formData.get('email').trim(),
                password: formData.get('password'),
                confirmPassword: formData.get('confirmPassword')
            };

            // اعتبارسنجی
            const validation = ValidationMiddleware.validateRegisterData(data);
            if (!validation.isValid) {
                Utils.showNotification(validation.errors.join(' • '), 'error');
                return;
            }

            const submitBtn = registerForm.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.disabled = true;
            submitBtn.textContent = '⏳ در حال ثبت نام...';

            try {
                const profile = {
                    fullName: `${data.firstName || ''} ${data.lastName || ''}`.trim()
                };

                const result = authManager.registerUser(
                    data.username,
                    data.email,
                    data.password,
                    'student',
                    profile
                );

                if (result.success) {
                    Utils.showNotification('حساب کاربری با موفقیت ایجاد شد!', 'success');
                    this.closeCurrentModal();
                    
                    // نمایش فرم ورود
                    setTimeout(() => {
                        this.showLogin();
                    }, 1500);
                    
                } else {
                    Utils.showNotification(result.message, 'error');
                }
            } catch (error) {
                console.error('Registration error:', error);
                Utils.showNotification('خطا در ایجاد حساب کاربری', 'error');
            } finally {
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        });
    }

    static showMessage(title, message, type = 'info') {
        const modalHTML = `
            <div class="modal-overlay active">
                <div class="modal-content">
                    <button class="modal-close" onclick="ModalComponent.closeCurrentModal()">&times;</button>
                    <div class="modal-header">
                        <h3>${title}</h3>
                    </div>
                    <div class="modal-body">
                        <div class="message-content ${type}">
                            <p>${message}</p>
                        </div>
                        <button class="btn btn-primary btn-block" onclick="ModalComponent.closeCurrentModal()">
                            متوجه شدم
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        this.showCustomModal('message-modal', modalHTML);
    }

    static showError(message) {
        this.showMessage('❌ خطا', message, 'error');
    }

    static showSuccess(message) {
        this.showMessage('✅ موفقیت', message, 'success');
    }
}