File size: 41,121 Bytes
5074056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
The user wants to convert the provided HTML/CSS/JavaScript chat room demo into a real working application using HTML, CSS, PHP, and a database (implied by "real" and "host").

Key requirements:
1. Convert the frontend demo to a real backend application
2. Use PHP for backend
3. Use MySQL/MariaDB for database (implied by "real")
4. Keep the Persian (Farsi) language and RTL layout
5. Maintain the modern UI design from the original code
6. Make it functional (real login/register, real chat messages stored in DB)
7. Should be deployable on a web host

Since I need to provide a single HTML file as per system instructions, but the user is asking for PHP/MySQL backend, I need to provide:
1. The complete PHP code structure
2. SQL schema
3. Instructions on how to set it up
4. But since I can only provide one file, I should provide a comprehensive solution that includes all PHP files concatenated or clearly separated with comments, plus the SQL setup.

Wait, the system says "ALWAYS GIVE THE RESPONSE INTO A SINGLE HTML FILE" but the user is asking for PHP. This is a conflict. However, looking at the instructions carefully: "Generate complete, working HTML code that can be run immediately."

But PHP cannot run in a single HTML file in the browser. I need to interpret this as: provide the complete source code for the application, which happens to be PHP files. Since I must output a single file, I'll provide a comprehensive solution with clear file separators (like comments indicating different files) containing all the PHP, SQL, and frontend code needed.

Actually, looking at the system prompt again: "Generate complete, working HTML code that can be run immediately." This suggests the user wants code that works immediately. But PHP requires a server. 

Given the constraints, I should:
1. Provide the complete PHP application code with multiple files indicated
2. Provide the SQL schema
3. Provide instructions
4. But keep it as one text block/file with clear separators

Or, I could create a single-file PHP solution that handles everything (routing, database setup, frontend) in one index.php file. This would technically be a single file that can run on a PHP host.

Yes, that's the best approach for this constraint. I'll create a single PHP file (index.php) that:
- Sets up the database on first run
- Handles all backend logic (auth, chat CRUD)
- Serves the frontend HTML/CSS/JS
- Uses AJAX/Fetch for real-time-like updates (polling)

Features to implement:
1. User registration/login with PHP sessions
2. MySQL database for users, rooms, messages
3. Real chat functionality (messages stored in DB)
4. Multiple rooms support
5. Online status tracking
6. Responsive design (maintain the original beautiful UI)
7. Security: Prepared statements, password hashing, XSS protection

Database schema:
- users (id, username, phone, password, avatar, status, last_active)
- rooms (id, name, type, created_by)
- messages (id, room_id, user_id, message, created_at)
- room_members (id, room_id, user_id, joined_at)

Since it's one file, I'll use a "setup mode" - if tables don't exist, create them.

For real-time feel without WebSockets (which require separate server), I'll use polling every 3 seconds.

Structure of the single PHP file:
1. PHP Backend Logic (session start, db connection, request handlers)
2. Database setup (create tables if not exist)
3. API endpoints (handled via GET/POST parameters)
4. HTML/CSS/JS Frontend (the beautiful UI from original, adapted for real backend)

Security considerations:
- Use PDO with prepared statements
- Password_hash() for passwords
- htmlspecialchars() for output
- CSRF tokens
- Input validation

Let's build this step by step:

Database connection config (at top):
- Define DB credentials (user will change these)
- Try to connect, if fail show setup instructions

Routing:
- If $_GET['action'] exists, handle API call
- Else show the app interface

API Endpoints:
- login
- register  
- get_messages
- send_message
- get_rooms
- create_room
- logout

Frontend:
- Same beautiful Persian UI as original
- But now AJAX calls to the same file with ?action=...
- Poll for new messages
- Show real user data from session

I'll maintain the exact styling from the user's provided code but adapt the JavaScript to work with the PHP backend.

Since it's one file, I need to be careful about output buffering and headers.

Let me write the code:

File: index.php (all-in-one)

Sections:
1. PHP Logic (top)
   - Session start
   - DB config
   - Helper functions
   - Request routing
   
2. Database Setup
   - Create tables if not exist
   
3. API Handlers
   - JSON responses for AJAX
   
4. HTML Output (if not API call)
   - Same structure as original but with PHP session integration
   
The UI should look almost identical to what the user provided, but functional.

Key adaptations:
- Login form submits to ?action=login via fetch
- Register form submits to ?action=register  
- Messages load from ?action=get_messages
- Send message to ?action=send_message
- Auto-refresh messages every 2-3 seconds

I'll include the "Built with anycoder" link as required.

Let's code this comprehensive solution. </think> Here is the complete **real chat application** in a single PHP file (`index.php`). This includes the database setup, backend API, and the beautiful Persian UI you provided.

**Instructions:**
1. Save this as `index.php`
2. Update the database credentials at the top (host, dbname, user, pass)
3. Upload to your PHP host (PHP 7.4+ with MySQL/MariaDB)
4. Visit the page - it will auto-create the database tables on first run

```php
<?php
// ============================================
// چت روم واقعی - Real Chat Room
// Built with anycoder: https://huggingface.co/spaces/akhaliq/anycoder
// ============================================

session_start();

// Database Configuration - تنظیمات دیتابیس
define('DB_HOST', 'localhost');
define('DB_NAME', 'chatroom_db');
define('DB_USER', 'root');
define('DB_PASS', '');

// Connect to Database
try {
    $pdo = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8mb4", DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Initialize Database Tables (Auto-setup on first run)
function initDB($pdo) {
    $pdo->exec("CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(100) NOT NULL,
        phone VARCHAR(20) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        avatar VARCHAR(10) DEFAULT '👤',
        status ENUM('online', 'offline') DEFAULT 'offline',
        last_active TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci");

    $pdo->exec("CREATE TABLE IF NOT EXISTS rooms (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        type ENUM('public', 'private') DEFAULT 'public',
        created_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci");

    $pdo->exec("CREATE TABLE IF NOT EXISTS messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        room_id INT NOT NULL,
        user_id INT NOT NULL,
        message TEXT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (room_id) REFERENCES rooms(id) ON DELETE CASCADE,
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci");

    $pdo->exec("CREATE TABLE IF NOT EXISTS room_members (
        id INT AUTO_INCREMENT PRIMARY KEY,
        room_id INT NOT NULL,
        user_id INT NOT NULL,
        joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_membership (room_id, user_id),
        FOREIGN KEY (room_id) REFERENCES rooms(id) ON DELETE CASCADE,
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci");

    // Insert default public room if empty
    $stmt = $pdo->query("SELECT COUNT(*) FROM rooms");
    if ($stmt->fetchColumn() == 0) {
        $pdo->prepare("INSERT INTO rooms (name, type) VALUES (?, ?)")
            ->execute(['عمومی', 'public']);
        $pdo->prepare("INSERT INTO rooms (name, type) VALUES (?, ?)")
            ->execute(['خصوصی', 'private']);
    }
}

// Initialize on first run
initDB($pdo);

// API Handler
if (isset($_GET['action'])) {
    header('Content-Type: application/json; charset=utf-8');
    $action = $_GET['action'];
    
    switch($action) {
        case 'register':
            handleRegister($pdo);
            break;
        case 'login':
            handleLogin($pdo);
            break;
        case 'logout':
            handleLogout();
            break;
        case 'get_rooms':
            getRooms($pdo);
            break;
        case 'get_messages':
            getMessages($pdo);
            break;
        case 'send_message':
            sendMessage($pdo);
            break;
        case 'create_room':
            createRoom($pdo);
            break;
        case 'get_online_users':
            getOnlineUsers($pdo);
            break;
    }
    exit;
}

// Backend Functions
function handleRegister($pdo) {
    $data = json_decode(file_get_contents('php://input'), true);
    $username = trim($data['username'] ?? '');
    $phone = trim($data['phone'] ?? '');
    $password = $data['password'] ?? '';
    
    if (empty($username) || empty($phone) || empty($password)) {
        echo json_encode(['success' => false, 'error' => 'تمام فیلدها الزامی است']);
        return;
    }
    
    if (!preg_match('/^09[0-9]{9}$/', $phone)) {
        echo json_encode(['success' => false, 'error' => 'شماره موبایل نامعتبر است']);
        return;
    }
    
    $hash = password_hash($password, PASSWORD_BCRYPT);
    $avatar = mb_substr($username, 0, 1);
    
    try {
        $stmt = $pdo->prepare("INSERT INTO users (username, phone, password, avatar) VALUES (?, ?, ?, ?)");
        $stmt->execute([$username, $phone, $hash, $avatar]);
        
        $userId = $pdo->lastInsertId();
        
        // Auto-join public rooms
        $rooms = $pdo->query("SELECT id FROM rooms WHERE type = 'public'")->fetchAll();
        $stmt = $pdo->prepare("INSERT INTO room_members (room_id, user_id) VALUES (?, ?)");
        foreach ($rooms as $room) {
            $stmt->execute([$room['id'], $userId]);
        }
        
        $_SESSION['user_id'] = $userId;
        $_SESSION['username'] = $username;
        $_SESSION['avatar'] = $avatar;
        
        echo json_encode(['success' => true, 'user' => ['id' => $userId, 'username' => $username, 'avatar' => $avatar]]);
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) {
            echo json_encode(['success' => false, 'error' => 'این شماره موبایل قبلاً ثبت شده است']);
        } else {
            echo json_encode(['success' => false, 'error' => 'خطا در ثبت‌نام']);
        }
    }
}

function handleLogin($pdo) {
    $data = json_decode(file_get_contents('php://input'), true);
    $phone = trim($data['phone'] ?? '');
    $password = $data['password'] ?? '';
    
    $stmt = $pdo->prepare("SELECT * FROM users WHERE phone = ?");
    $stmt->execute([$phone]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['avatar'] = $user['avatar'];
        
        // Update status
        $pdo->prepare("UPDATE users SET status = 'online' WHERE id = ?")->execute([$user['id']]);
        
        echo json_encode(['success' => true, 'user' => ['id' => $user['id'], 'username' => $user['username'], 'avatar' => $user['avatar']]]);
    } else {
        echo json_encode(['success' => false, 'error' => 'شماره موبایل یا رمز عبور اشتباه است']);
    }
}

function handleLogout() {
    if (isset($_SESSION['user_id'])) {
        global $pdo;
        $pdo->prepare("UPDATE users SET status = 'offline' WHERE id = ?")->execute([$_SESSION['user_id']]);
    }
    session_destroy();
    echo json_encode(['success' => true]);
}

function getRooms($pdo) {
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false]);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT r.*, 
               (SELECT COUNT(*) FROM room_members WHERE room_id = r.id) as member_count,
               (SELECT COUNT(*) FROM users u 
                JOIN room_members rm ON u.id = rm.user_id 
                WHERE rm.room_id = r.id AND u.status = 'online') as online_count
        FROM rooms r
        JOIN room_members rm ON r.id = rm.room_id
        WHERE rm.user_id = ?
        ORDER BY r.id ASC
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $rooms = $stmt->fetchAll();
    
    echo json_encode(['success' => true, 'rooms' => $rooms]);
}

function getMessages($pdo) {
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false]);
        return;
    }
    
    $roomId = intval($_GET['room_id'] ?? 0);
    $lastId = intval($_GET['last_id'] ?? 0);
    
    // Verify membership
    $check = $pdo->prepare("SELECT id FROM room_members WHERE room_id = ? AND user_id = ?");
    $check->execute([$roomId, $_SESSION['user_id']]);
    if (!$check->fetch()) {
        echo json_encode(['success' => false, 'error' => 'Access denied']);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT m.*, u.username, u.avatar 
        FROM messages m
        JOIN users u ON m.user_id = u.id
        WHERE m.room_id = ? AND m.id > ?
        ORDER BY m.id ASC
        LIMIT 50
    ");
    $stmt->execute([$roomId, $lastId]);
    $messages = $stmt->fetchAll();
    
    // Update last active
    $pdo->prepare("UPDATE users SET last_active = NOW() WHERE id = ?")->execute([$_SESSION['user_id']]);
    
    echo json_encode(['success' => true, 'messages' => $messages]);
}

function sendMessage($pdo) {
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false]);
        return;
    }
    
    $data = json_decode(file_get_contents('php://input'), true);
    $roomId = intval($data['room_id'] ?? 0);
    $message = trim($data['message'] ?? '');
    
    if (empty($message)) {
        echo json_encode(['success' => false]);
        return;
    }
    
    // Verify membership
    $check = $pdo->prepare("SELECT id FROM room_members WHERE room_id = ? AND user_id = ?");
    $check->execute([$roomId, $_SESSION['user_id']]);
    if (!$check->fetch()) {
        echo json_encode(['success' => false, 'error' => 'Access denied']);
        return;
    }
    
    $stmt = $pdo->prepare("INSERT INTO messages (room_id, user_id, message) VALUES (?, ?, ?)");
    $stmt->execute([$roomId, $_SESSION['user_id'], $message]);
    
    echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]);
}

function createRoom($pdo) {
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false]);
        return;
    }
    
    $data = json_decode(file_get_contents('php://input'), true);
    $name = trim($data['name'] ?? '');
    $type = $data['type'] ?? 'public';
    
    if (empty($name)) {
        echo json_encode(['success' => false, 'error' => 'نام اتاق الزامی است']);
        return;
    }
    
    // Check room limit (max 3 per user)
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM rooms WHERE created_by = ?");
    $stmt->execute([$_SESSION['user_id']]);
    if ($stmt->fetchColumn() >= 3) {
        echo json_encode(['success' => false, 'error' => 'حداکثر ۳ اتاق می‌توانید بسازید']);
        return;
    }
    
    $stmt = $pdo->prepare("INSERT INTO rooms (name, type, created_by) VALUES (?, ?, ?)");
    $stmt->execute([$name, $type, $_SESSION['user_id']]);
    $roomId = $pdo->lastInsertId();
    
    // Creator joins automatically
    $pdo->prepare("INSERT INTO room_members (room_id, user_id) VALUES (?, ?)")
        ->execute([$roomId, $_SESSION['user_id']]);
    
    echo json_encode(['success' => true, 'room' => ['id' => $roomId, 'name' => $name, 'type' => $type]]);
}

function getOnlineUsers($pdo) {
    $roomId = intval($_GET['room_id'] ?? 0);
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count 
        FROM users u
        JOIN room_members rm ON u.id = rm.user_id
        WHERE rm.room_id = ? AND u.status = 'online' 
        AND u.last_active > DATE_SUB(NOW(), INTERVAL 5 MINUTE)
    ");
    $stmt->execute([$roomId]);
    $result = $stmt->fetch();
    echo json_encode(['success' => true, 'count' => $result['count']]);
}

// Check if user is logged in
$isLoggedIn = isset($_SESSION['user_id']);
$currentUser = $isLoggedIn ? [
    'id' => $_SESSION['user_id'],
    'username' => $_SESSION['username'],
    'avatar' => $_SESSION['avatar']
] : null;
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>چت روم واقعی | گفتگوی آنلاین</title>
    
    <!-- Persian Font: Vazirmatn -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@100;300;400;500;700;900&display=swap" rel="stylesheet">
    
    <!-- Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        :root {
            --primary: #6366f1;
            --primary-dark: #4f46e5;
            --secondary: #ec4899;
            --background: #0f172a;
            --surface: rgba(30, 41, 59, 0.7);
            --text: #f8fafc;
            --text-muted: #94a3b8;
            --border: rgba(148, 163, 184, 0.1);
            --success: #10b981;
            --warning: #f59e0b;
            --glass: rgba(255, 255, 255, 0.05);
            --shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
        }

        [data-theme="light"] {
            --background: #f1f5f9;
            --surface: rgba(255, 255, 255, 0.8);
            --text: #1e293b;
            --text-muted: #64748b;
            --border: rgba(148, 163, 184, 0.2);
            --glass: rgba(255, 255, 255, 0.6);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            font-family: 'Vazirmatn', sans-serif;
            background: var(--background);
            color: var(--text);
            min-height: 100vh;
            overflow-x: hidden;
            transition: background 0.3s ease, color 0.3s ease;
        }

        /* Animated Background */
        .bg-animation {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            overflow: hidden;
        }

        .bg-animation .circle {
            position: absolute;
            border-radius: 50%;
            filter: blur(80px);
            opacity: 0.4;
            animation: float 20s infinite ease-in-out;
        }

        .circle:nth-child(1) {
            width: 400px;
            height: 400px;
            background: var(--primary);
            top: -100px;
            right: -100px;
            animation-delay: 0s;
        }

        .circle:nth-child(2) {
            width: 300px;
            height: 300px;
            background: var(--secondary);
            bottom: -50px;
            left: -50px;
            animation-delay: 5s;
        }

        .circle:nth-child(3) {
            width: 250px;
            height: 250px;
            background: var(--success);
            top: 50%;
            left: 50%;
            animation-delay: 10s;
        }

        @keyframes float {
            0%, 100% { transform: translate(0, 0) scale(1); }
            33% { transform: translate(30px, -50px) scale(1.1); }
            66% { transform: translate(-20px, 20px) scale(0.9); }
        }

        /* Header */
        header {
            position: fixed;
            top: 0;
            width: 100%;
            padding: 1rem 2rem;
            background: var(--glass);
            backdrop-filter: blur(12px);
            border-bottom: 1px solid var(--border);
            z-index: 1000;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            font-size: 1.5rem;
            font-weight: 900;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .header-actions {
            display: flex;
            gap: 1rem;
            align-items: center;
        }

        .built-with {
            font-size: 0.75rem;
            color: var(--text-muted);
            text-decoration: none;
            padding: 0.5rem 1rem;
            border-radius: 2rem;
            background: var(--glass);
            border: 1px solid var(--border);
            transition: all 0.3s ease;
        }

        .built-with:hover {
            background: var(--primary);
            color: white;
            transform: translateY(-2px);
        }

        .theme-toggle {
            background: var(--glass);
            border: 1px solid var(--border);
            color: var(--text);
            width: 40px;
            height: 40px;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        .theme-toggle:hover {
            transform: rotate(180deg);
            background: var(--primary);
        }

        /* Main Container */
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 6rem 2rem 2rem;
        }

        /* Hero Section */
        .hero {
            text-align: center;
            padding: 4rem 0;
            animation: fadeInUp 1s ease;
        }

        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .hero h1 {
            font-size: clamp(2rem, 5vw, 4rem);
            font-weight: 900;
            margin-bottom: 1rem;
            line-height: 1.2;
        }

        .hero h1 .emoji {
            display: inline-block;
            animation: bounce 2s infinite;
        }

        @keyframes bounce {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-10px); }
        }

        .subtitle {
            font-size: 1.25rem;
            color: var(--text-muted);
            margin-bottom: 2rem;
            font-weight: 300;
        }

        /* Features Grid */
        .features {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 2rem;
            margin: 4rem 0;
            perspective: 1000px;
        }

        .feature {
            background: var(--surface);
            backdrop-filter: blur(10px);
            border: 1px solid var(--border);
            border-radius: 1.5rem;
            padding: 2rem;
            text-align: center;
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            position: relative;
            overflow: hidden;
            cursor: pointer;
        }

        .feature::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, transparent, rgba(255, 255, 255, 0.05));
            opacity: 0;
            transition: opacity 0.3s;
        }

        .feature:hover {
            transform: translateY(-10px) rotateX(5deg);
            box-shadow: var(--shadow);
            border-color: var(--primary);
        }

        .feature:hover::before {
            opacity: 1;
        }

        .icon {
            font-size: 3rem;
            margin-bottom: 1rem;
            display: inline-block;
            transition: transform 0.3s;
        }

        .feature:hover .icon {
            transform: scale(1.2) rotate(10deg);
        }

        .feature h3 {
            font-size: 1.25rem;
            margin-bottom: 0.5rem;
            color: var(--text);
        }

        .feature p {
            color: var(--text-muted);
            font-size: 0.95rem;
            line-height: 1.6;
        }

        /* CTA Section */
        .cta {
            display: flex;
            gap: 1rem;
            justify-content: center;
            flex-wrap: wrap;
            margin: 3rem 0;
        }

        .btn {
            padding: 1rem 2.5rem;
            border-radius: 2rem;
            font-family: inherit;
            font-size: 1rem;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            border: none;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            position: relative;
            overflow: hidden;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: white;
            box-shadow: 0 4px 15px rgba(99, 102, 241, 0.4);
        }

        .btn-secondary {
            background: var(--glass);
            color: var(--text);
            border: 2px solid var(--border);
            backdrop-filter: blur(10px);
        }

        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
        }

        .btn:active {
            transform: translateY(-1px);
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            backdrop-filter: blur(5px);
            z-index: 2000;
            justify-content: center;
            align-items: center;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .modal.active {
            display: flex;
            opacity: 1;
        }

        .modal-content {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: 2rem;
            padding: 2.5rem;
            width: 90%;
            max-width: 450px;
            position: relative;
            transform: scale(0.9);
            transition: transform 0.3s;
            box-shadow: var(--shadow);
        }

        .modal.active .modal-content {
            transform: scale(1);
        }

        .close-modal {
            position: absolute;
            top: 1rem;
            left: 1rem;
            background: none;
            border: none;
            color: var(--text-muted);
            font-size: 1.5rem;
            cursor: pointer;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s;
        }

        .close-modal:hover {
            background: var(--glass);
            color: var(--text);
            transform: rotate(90deg);
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--text);
            font-weight: 500;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 2px solid var(--border);
            border-radius: 1rem;
            background: var(--glass);
            color: var(--text);
            font-family: inherit;
            font-size: 1rem;
            transition: all 0.3s;
        }

        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }

        .form-submit {
            width: 100%;
            margin-top: 1rem;
        }

        .error-msg {
            color: var(--secondary);
            font-size: 0.875rem;
            margin-top: 0.5rem;
            display: none;
        }

        /* Chat Application Interface */
        #chat-app {
            display: none;
            height: calc(100vh - 80px);
            margin-top: 80px;
        }

        .chat-container {
            display: grid;
            grid-template-columns: 300px 1fr;
            height: 100%;
            gap: 1rem;
            padding: 1rem;
        }

        .sidebar {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: 1.5rem;
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
            backdrop-filter: blur(10px);
            overflow-y: auto;
        }

        .user-profile {
            text-align: center;
            padding-bottom: 1rem;
            border-bottom: 1px solid var(--border);
        }

        .avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            margin: 0 auto 0.5rem;
            border: 3px solid var(--border);
            cursor: pointer;
            transition: transform 0.3s;
        }

        .avatar:hover {
            transform: scale(1.1);
        }

        .rooms-list {
            flex: 1;
            overflow-y: auto;
        }

        .room-item {
            padding: 1rem;
            margin-bottom: 0.5rem;
            border-radius: 1rem;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            border: 1px solid transparent;
        }

        .room-item:hover, .room-item.active {
            background: var(--glass);
            border-color: var(--primary);
        }

        .room-item.active {
            background: rgba(99, 102, 241, 0.1);
        }

        .chat-area {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: 1.5rem;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            backdrop-filter: blur(10px);
        }

        .chat-header {
            padding: 1.5rem;
            border-bottom: 1px solid var(--border);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .message {
            max-width: 70%;
            padding: 1rem 1.25rem;
            border-radius: 1.25rem;
            position: relative;
            animation: messageSlide 0.3s ease;
            word-wrap: break-word;
        }

        @keyframes messageSlide {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .message.sent {
            align-self: flex-start;
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: white;
            border-bottom-right-radius: 0.25rem;
        }

        .message.received {
            align-self: flex-end;
            background: var(--glass);
            border: 1px solid var(--border);
            border-bottom-left-radius: 0.25rem;
        }

        .message-author {
            font-size: 0.75rem;
            opacity: 0.8;
            margin-bottom: 0.25rem;
            font-weight: 700;
        }

        .message-time {
            font-size: 0.7rem;
            opacity: 0.6;
            margin-top: 0.5rem;
            display: block;
            text-align: left;
        }

        .chat-input {
            padding: 1.5rem;
            border-top: 1px solid var(--border);
            display: flex;
            gap: 1rem;
        }

        .chat-input input {
            flex: 1;
            padding: 0.75rem 1.25rem;
            border: 2px solid var(--border);
            border-radius: 2rem;
            background: var(--glass);
            color: var(--text);
            font-family: inherit;
            font-size: 1rem;
        }

        .chat-input input:focus {
            outline: none;
            border-color: var(--primary);
        }

        .send-btn {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: var(--primary);
            color: white;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s;
            font-size: 1.25rem;
        }

        .send-btn:hover {
            background: var(--primary-dark);
            transform: scale(1.1);
        }

        .send-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .chat-container {
                grid-template-columns: 1fr;
                position: relative;
            }

            .sidebar {
                position: absolute;
                right: -100%;
                top: 0;
                height: 100%;
                width: 280px;
                z-index: 100;
                transition: right 0.3s;
                box-shadow: var(--shadow);
            }

            .sidebar.open {
                right: 0;
            }

            .mobile-menu-btn {
                display: block !important;
            }

            .features {
                grid-template-columns: 1fr;
            }
        }

        .mobile-menu-btn {
            display: none;
            background: var(--glass);
            border: 1px solid var(--border);
            color: var(--text);
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            cursor: pointer;
        }

        /* Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: transparent;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--border);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--primary);
        }

        /* Loading Animation */
        .typing-indicator {
            display: none;
            align-self: flex-start;
            background: var(--glass);
            padding: 1rem 1.5rem;
            border-radius: 1.25rem;
            border-bottom-right-radius: 0.25rem;
            margin-bottom: 1rem;
        }

        .typing-indicator.active {
            display: flex;
            gap: 0.25rem;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            background: var(--text-muted);
            border-radius: 50%;
            animation: typing 1.4s infinite;
        }

        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typing {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-10px); }
        }

        .toast {
            position: fixed;
            bottom: 2rem;
            left: 50%;
            transform: translateX(-50%) translateY(100px);
            background: var(--surface);
            color: var(--text);
            padding: 1rem 2rem;
            border-radius: 1rem;
            border: 1px solid var(--border);
            box-shadow: var(--shadow);
            z-index: 3000;
            opacity: 0;
            transition: all 0.3s;
        }

        .toast.show {
            transform: translateX(-50%) translateY(0);
            opacity: 1;
        }

        .toast.error {
            border-color: var(--secondary);
            background: rgba(236, 72, 153, 0.1);
        }

        .toast.success {
            border-color: var(--success);
            background: rgba(16, 185, 129, 0.1);
        }
    </style>
</head>
<body>
    <!-- Animated Background -->
    <div class="bg-animation">
        <div class="circle"></div>
        <div class="circle"></div>
        <div class="circle"></div>
    </div>

    <!-- Header -->
    <header>
        <div class="logo">
            <i class="fas fa-comments"></i>
            <span>چت روم</span>
        </div>
        <div class="header-actions">
            <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" class="built-with">
                <i class="fas fa-code"></i> Built with anycoder
            </a>
            <button class="theme-toggle" onclick="toggleTheme()" title="تغییر تم">
                <i class="fas fa-moon"></i>
            </button>
        </div>
    </header>

    <?php if (!$isLoggedIn): ?>
    <!-- Landing Page -->
    <div id="landing" class="container">
        <div class="hero">
            <h1><span class="emoji">💬</span> چت روم واقعی</h1>
            <p class="subtitle">محلی امن و سریع برای گفتگو با دوستان و همکاران</p>
        </div>

        <div class="features">
            <div class="feature" onclick="showRegister()">
                <div class="icon">🔐</div>
                <h3>ثبت‌نام واقعی</h3>
                <p>با شماره موبایل و رمز عبور امن ثبت‌نام کنید. اطلاعات در دیتابیس ذخیره می‌شود</p>
            </div>

            <div class="feature" onclick="showRegister()">
                <div class="icon">👥</div>
                <h3>اتاق‌های چند نفره</h3>
                <p>تا ۳ اتاق بسازید و با کاربران واقعی چت کنید. پیام‌ها لحظه‌ای ذخیره و نمایش داده می‌شوند</p>
            </div>

            <div class="feature" onclick="showRegister()">
                <div class="icon"></div>
                <h3>چت زنده</h3>
                <p>بروزرسانی خودکار هر ۳ ثانیه. مشاهده وضعیت آنلاین بودن کاربران</p>
            </div>
        </div>

        <div class="cta">
            <button onclick="showRegister()" class="btn btn-primary">
                <i class="fas fa-rocket"></i>
                شروع کنید
            </button>
            <button onclick="showLogin()" class="btn btn-secondary">
                <i class="fas fa-sign-in-alt"></i>
                ورود
            </button>
        </div>
    </div>

    <!-- Auth Modals -->
    <div id="login-modal" class="modal">
        <div class="modal-content">
            <button class="close-modal" onclick="closeModals()">
                <i class="fas fa-times"></i>
            </button>
            <h2 style="margin-bottom: 1.5rem; text-align: center;">
                <i class="fas fa-sign-in-alt" style="color: var(--primary);"></i>
                ورود به حساب
            </h2>
            <form id="login-form" onsubmit="handleLogin(event)">
                <div class="form-group">
                    <label>شماره موبایل</label>
                    <input type="tel" name="phone" placeholder="09*********" required pattern="09[0-9]{9}">
                </div>
                <div class="form-group">
                    <label>رمز عبور</label>
                    <input type="password" name="password" placeholder="••••••••" required>
                </div>
                <div class="error-msg" id="login-error"></div>
                <button type="submit" class="btn btn-primary form-submit">