File size: 59,181 Bytes
53d6109
edee679
16c32c6
3b0afe1
 
 
91794fe
 
 
3fd2450
7c3aff0
 
0ebc988
e49ac3e
 
 
91794fe
e3d9e7e
9ea317e
7cffc90
 
 
 
 
a0eaf13
e3d9e7e
3d2d738
 
9ea317e
e3d9e7e
9ea317e
 
655a8ab
 
92675a4
e3d9e7e
9ea317e
 
9835398
4ea10fb
e3d9e7e
6fe9705
 
 
56c2d00
d333e20
6fe9705
4ea10fb
1959ad7
35f076f
56c6c1d
25be7b9
 
 
1959ad7
9ea317e
 
 
9f74cf3
58cae0c
3b0afe1
 
d20ecb3
3b0afe1
 
40c4f6f
568706e
 
2a6271f
3b0afe1
 
 
2a6271f
 
 
 
 
 
 
 
 
 
 
 
f256744
2a6271f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5f2117
 
 
 
 
 
2a6271f
3b0afe1
 
 
40c4f6f
3b0afe1
2a6271f
91794fe
261716e
17c1a79
31a51a9
 
 
 
 
 
 
02ab734
 
31a51a9
 
03acddb
2819cf3
 
 
 
 
 
 
 
 
 
 
 
03acddb
 
 
 
 
91794fe
 
533735e
b01b551
 
fc0a8f9
b01b551
fc0a8f9
b01b551
fc0a8f9
 
b01b551
fc0a8f9
b639d39
626e138
 
 
 
 
 
 
 
 
 
 
ff2f4f2
b01b551
ff2f4f2
b01b551
b639d39
 
 
 
 
 
fc0a8f9
b639d39
f6d0e5e
b639d39
626e138
 
 
 
 
 
 
 
66c7169
b54c0ac
 
fc0a8f9
b639d39
 
b54c0ac
9a54d5a
11adb51
6fe9705
 
 
e0e0f15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddea1fb
 
 
 
 
 
dae356e
 
 
 
 
 
 
 
 
 
 
c5fc451
dae356e
c2d4a11
 
 
 
 
11adb51
dae356e
 
 
 
 
 
 
 
 
 
 
 
 
4f9454d
 
 
 
 
 
ebf171c
dae356e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be1b174
babe67f
be1b174
23b94e7
be1b174
 
dae356e
0511987
dae356e
 
0511987
 
6c60c6b
11adb51
e3d9e7e
 
 
 
 
c5fc451
9565f93
 
 
c5fc451
9565f93
 
 
 
 
 
dae356e
9565f93
 
dae356e
9565f93
 
 
 
 
 
dae356e
9565f93
 
 
 
c5fc451
c60c13e
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
655a8ab
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
14af27b
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40c4f6f
3b0afe1
 
40c4f6f
3b0afe1
 
40c4f6f
3b0afe1
40c4f6f
69c75b8
3b0afe1
 
 
 
 
04d4d7b
 
 
 
 
 
6540fed
04d4d7b
 
 
 
 
fba775c
 
 
04d4d7b
 
fba775c
 
 
 
 
 
 
 
3d04d09
 
 
04d4d7b
 
 
 
 
 
 
 
3d04d09
 
 
 
 
 
04d4d7b
 
 
 
 
 
 
 
a154208
 
3d04d09
 
04d4d7b
 
3d04d09
 
04d4d7b
 
 
a154208
 
3d04d09
04d4d7b
3d04d09
04d4d7b
 
 
 
 
 
 
 
0c977bc
61688b6
547dedc
adb7cc4
 
 
 
 
3b0afe1
adb7cc4
e0c01fb
61688b6
 
 
 
 
3b0afe1
 
 
6be9f95
 
adb7cc4
6be9f95
adb7cc4
 
 
6be9f95
 
 
 
 
 
6d66942
3d04d09
 
 
3b0afe1
 
 
 
adb7cc4
3b0dddb
 
 
3d04d09
 
 
 
 
 
3b0afe1
e0c01fb
6be9f95
 
 
 
 
 
a154208
 
3d04d09
 
6be9f95
7b699a2
3d04d09
 
6be9f95
 
 
a154208
a0ca8e3
3d04d09
7b699a2
3d04d09
6be9f95
e0c01fb
 
3b0afe1
6be9f95
e0c01fb
6be9f95
3b0afe1
0a3e3b6
6be9f95
 
adb7cc4
8578d73
 
 
adb7cc4
6be9f95
 
 
 
 
37857fc
 
3b0afe1
 
 
 
c9f3409
3b0afe1
 
 
 
 
ca6c5ee
3b0afe1
 
 
 
 
ba7ecbd
3b0afe1
 
 
37857fc
 
 
 
 
 
 
 
 
 
 
 
ca6c5ee
37857fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b0afe1
 
d6502ff
 
40f4dc8
 
 
 
 
 
e4f605f
d6502ff
 
832db13
 
 
 
2f1eeaa
 
 
 
d6502ff
2f1eeaa
 
 
 
 
3f56d68
b5f4679
 
3a7861c
3f56d68
 
2f1eeaa
 
 
3f56d68
 
d2639d2
b5f4679
 
 
 
 
3a7861c
 
3f56d68
2f1eeaa
 
e4c74f9
 
 
d6502ff
 
 
 
ba7ecbd
d6502ff
 
6723e97
 
 
 
 
 
5fa984e
 
 
 
2ff4383
 
 
 
 
 
 
 
 
 
 
 
ce55078
 
fdf506b
2ff4383
d0512c7
 
 
 
 
 
52128d4
6bda9b5
 
 
 
 
 
2116dff
4d79d7b
 
2116dff
ce55078
4d79d7b
 
 
 
2116dff
ce55078
 
 
97fdaad
4d79d7b
ce55078
2116dff
ce55078
 
4d79d7b
ce55078
97fdaad
 
ce55078
 
 
97fdaad
ce55078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d48703d
ce55078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2116dff
4d79d7b
 
 
ce55078
 
 
4d79d7b
ce55078
4d79d7b
 
842bd8b
0e2036e
6bda9b5
fdf506b
 
 
2dc0711
a471f43
 
 
 
 
 
fdf506b
a471f43
 
 
 
f9bb068
ce55078
2a22887
aed6774
4bb0fc3
2116dff
4bb0fc3
ce55078
 
2116dff
9ac14d9
 
 
4d79d7b
ce55078
9ac14d9
 
 
 
ce55078
 
 
9ac14d9
 
 
 
ce55078
 
 
 
 
 
 
 
 
 
 
 
43306ab
2116dff
4d79d7b
b441424
454005f
 
4bb0fc3
454005f
888e945
 
b010f8d
4bb0fc3
9ac14d9
 
 
b010f8d
 
97fdaad
6bda9b5
a7500b0
a5d5813
a7500b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b010f8d
43306ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b010f8d
 
2ff4383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa984e
e16ded1
3b0afe1
 
 
5fa984e
 
6cadefe
 
3b0afe1
 
 
6cadefe
51209a6
21416a0
 
3b0afe1
 
 
21416a0
51209a6
93e28e6
 
3b0afe1
 
 
93e28e6
 
2409275
 
3b0afe1
 
 
2409275
51209a6
d0a921f
 
3b0afe1
 
 
d0a921f
40c4f6f
dfeb4d9
 
3b0afe1
 
 
dfeb4d9
40c4f6f
093826a
 
3b0afe1
 
 
093826a
40c4f6f
bd7bcf1
 
3b0afe1
 
 
bd7bcf1
40c4f6f
4f15ddd
 
3b0afe1
 
 
4f15ddd
40c4f6f
30d9d78
 
3b0afe1
 
 
30d9d78
40c4f6f
2844e4a
 
3b0afe1
 
 
2844e4a
3b0afe1
9ed0eaa
13a3385
3b0afe1
 
 
 
4f15ddd
b9757a6
 
3b0afe1
 
 
b9757a6
1d05f9c
fafa910
 
 
 
 
 
5fa984e
 
 
 
 
 
f2e150a
 
 
c469556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea96e06
d45745f
 
3b0afe1
 
 
 
c469556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b0afe1
 
2dca593
3b0afe1
 
e0c01fb
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e5ec17
9368cf0
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0c01fb
3b0afe1
 
e0c01fb
9368cf0
3b0afe1
e0c01fb
3b0afe1
e0c01fb
edee679
3b0afe1
 
 
 
e0c01fb
3b0afe1
 
 
 
 
69c75b8
e0c01fb
afbd53b
e0c01fb
 
4818e9b
3b0afe1
e0c01fb
3b0afe1
e0c01fb
4595fee
e976dab
 
 
3b0afe1
e976dab
3b0afe1
 
 
 
e976dab
3b0afe1
 
e976dab
3b0afe1
 
 
 
 
 
e976dab
3b0afe1
 
 
 
 
 
 
e976dab
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
668afb7
3b0afe1
 
 
885c383
3b0afe1
 
 
 
 
 
e976dab
3b0afe1
 
e976dab
3b0afe1
 
 
 
e976dab
3b0afe1
 
 
e976dab
 
 
 
 
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e976dab
3b0afe1
 
e976dab
3b0afe1
 
 
 
 
 
 
 
df9fd6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a02406
 
54b1fd5
 
 
30313ba
 
 
df9fd6c
 
 
 
 
 
 
2d340c5
 
 
df9fd6c
 
 
 
 
 
54b1fd5
 
30313ba
 
 
 
df9fd6c
 
0d2f037
 
2a02406
 
0d2f037
df9fd6c
 
 
 
 
 
 
 
 
 
 
 
 
 
2df192a
df9fd6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25be7b9
df9fd6c
 
 
6aa8aac
cfe2ab7
6aa8aac
734412b
76864cc
 
 
6aa8aac
462deca
734412b
 
 
 
392516a
734412b
 
 
 
 
 
392516a
734412b
 
 
 
 
 
392516a
734412b
 
2ecd482
734412b
 
 
392516a
734412b
 
d913fc1
2e2a9b4
6aa8aac
49408bd
6aa8aac
a653449
49408bd
 
 
a653449
 
49408bd
a653449
 
49408bd
a653449
 
 
49408bd
6696607
49408bd
9142d0c
2e7a805
 
9142d0c
 
 
 
2e7a805
9142d0c
 
 
 
 
 
 
 
 
 
 
f9e8343
2e7a805
49408bd
9142d0c
2e7a805
9142d0c
 
 
 
 
 
2e7a805
 
 
 
6aa8aac
 
8f688ea
1deb654
9353292
 
 
734412b
2ecd482
734412b
49408bd
2e7a805
9353292
 
 
 
 
 
 
7e0b45c
6aa8aac
49408bd
9353292
 
 
6aa8aac
 
 
7e0b45c
 
d3fb63f
 
95f2e24
 
2d1c81c
 
 
 
 
 
 
 
57634f3
2d1c81c
7bcc53e
b05d0d1
 
 
 
 
 
 
7bcc53e
b05d0d1
7bcc53e
483b169
 
 
 
 
 
 
 
 
b05d0d1
7bcc53e
 
2d1c81c
 
 
3797008
 
 
8e67709
7bcc53e
483b169
 
 
 
3797008
483b169
 
b05d0d1
7bcc53e
 
b05d0d1
 
7bcc53e
b05d0d1
7bcc53e
b05d0d1
 
7bcc53e
3797008
b05d0d1
2d1c81c
3797008
 
2d1c81c
 
 
 
 
 
 
3797008
2d1c81c
3797008
 
2d1c81c
 
 
3797008
 
483b169
2d1c81c
 
 
 
 
 
 
 
 
 
 
483b169
b05d0d1
 
 
 
 
2d1c81c
 
 
 
 
 
 
 
d48703d
 
 
 
 
 
 
 
 
2d1c81c
 
 
 
 
 
 
 
 
 
 
 
95f2e24
 
 
 
 
 
 
 
 
 
 
 
 
 
0cebab8
 
 
95f2e24
0cebab8
 
95f2e24
0cebab8
 
95f2e24
0cebab8
95f2e24
0cebab8
 
95f2e24
0cebab8
 
 
 
95f2e24
 
 
0cebab8
 
 
95f2e24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eecafb7
 
 
95f2e24
 
f761278
ccfc7a3
2b4491d
eecafb7
1287b71
f761278
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1287b71
f761278
 
 
 
 
 
 
 
 
1b865a1
977c3ab
9ea317e
 
33de58e
1b865a1
9ea317e
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
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
from flask import Flask, request, render_template_string, render_template, jsonify, Response
import sqlite3
import os
import random
import requests
import time
import re
import json
import base64
import logging
import csv
import io

from datetime import datetime
import pytz

from unidecode import unidecode

api_key_sys = os.getenv('api_key_sys')  
# Ваш API-ключ
gc_url_gru = os.getenv('gc_url_gru')

gc_url_export = os.getenv('gc_url_export')  # URL для экспорта данных

start_up = os.getenv('start_up')   

gc_url = os.getenv('gc_url') 
gc_url_form = os.getenv('gc_url_form')  
gc_api = os.getenv('gc_api')  

wa_url = os.getenv('wa_url') 
wa_api_key = os.getenv('wa_api_key') 
wa_ak = os.getenv('ws_ak') 
ws_url_mes = "/sendMessage/"
ws_url_ver = "/checkWhatsapp/"

up_db = os.getenv('up_db') 

id_gru = os.getenv('id_gru') 
date_from = "2022-01-01"


export_id = ""  

code_executed = False


status = "active"



current_curator_index = 0
verifikation_start = "1"  # Глобальная переменная для управления верификацией
curator_on_off = "0"  # Глобальная переменная для управления назначением куратора





app = Flask(__name__, template_folder="./")
app.config['DEBUG'] = True
UPLOAD_FOLDER = 'static'
logging.basicConfig(level=logging.DEBUG)
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

DATABASES = ['data_gc.db', 'data1.db', 'data2.db', 'data3.db', 'data4.db', 'data5.db']

def init_db(db_name):
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS contacts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            phone TEXT NOT NULL,
            email TEXT NOT NULL,
            vk_id TEXT,
            chat_id TEXT,
            ws_st TEXT,
            ws_stop TEXT,
            web_st INTEGER,
            fin_prog INTEGER,
            b_city TEXT,
            b_fin TEXT NOT NULL, 
            b_ban TEXT,
            b_ign TEXT,
            b_baners TEXT,
            b_butt TEXT,
            b_mess TEXT,           
            shop_st TEXT,
            curator TEXT,
            pr1 TEXT,
            pr2 TEXT,
            pr3 TEXT,
            pr4 TEXT,
            pr5 TEXT,
            ad_url TEXT,
            key_pr TEXT,
            n_con TEXT,
            canal TEXT,
            data_t TEXT,
            utm_source TEXT,
            utm_medium TEXT,
            utm_campaign TEXT,
            utm_term TEXT,
            utm_content TEXT
        )
    ''')
    conn.commit()
    conn.close()

for db in DATABASES:
    init_db(db)


template = {
    "username": "name",
    "phone": "phone",
    "email": "email",
    "city": "b_city",
    "finished": "b_fin",
    "ban": "b_ban",
    "ignore": "b_ign",
    "banners": "b_baners",  
    "buttons": "b_butt",    
    "messages": "b_mess"
}

mapping_template = {
    "username": "name",
    "phone": "phone",
    "email": "email",
    "city": "b_city",
    "finished": "b_fin",
    "ban": "b_ban",
    "ignore": "b_ign",
    "banners": "b_baners",  
    "buttons": "b_butt",    
    "messages": "b_mess"
}








# Функция для выполнения HTTP запросов
def fetch(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        print(f"GET запрос к {url} выполнен успешно.")
        return response.json()
    except requests.RequestException as e:
        print(f"Ошибка при выполнении GET запроса к {url}: {e}")
        return None

# Функция для отправки оповещения на другой сервер
def send_notification(url, data):
    try:
        response = requests.post(url, json=data)
        response.raise_for_status()
        print(f"POST запрос к {url} выполнен успешно.")
        return response.json()
    except requests.RequestException as e:
        print(f"Ошибка при выполнении POST запроса к {url}: {e}")
        return None

# Основная функция для отправки запросов
def initialize_requests():
    global code_executed, export_id
    print(f"Функция initialize_requests вызвана. start_up: {start_up}, code_executed: {code_executed}")

    if start_up == '1' and not code_executed:
        try:
            # Первый запрос
            url_template = f"{gc_url_gru}/{id_gru}/users?key={gc_api}&created_at[from]={date_from}&status={status}"
            data = fetch(url_template)
            if data and data.get("success"):
                export_id = data.get("info", {}).get("export_id", "")
                print("Export ID:", export_id)  # Отладочное сообщение

                # Отправка оповещения на другой сервер
                notification_url = "https://skyauto.me/cllbck/217669590/29245685/bGZuMDRZZUpLZ3VJR2oxcC9CQmh0UT0?api=1&uid=535939344"
                notification_data = {
                    "message": "Первый запрос был выполнен",
                    "export_id": export_id
                }
                notification_response = send_notification(notification_url, notification_data)
                print("Ответ от сервера оповещения:", notification_response)

                code_executed = True  # Устанавливаем флаг выполнения кода
            else:
                raise Exception(f"Ошибка в ответе от сервера: {data.get('error_message') if data else 'Нет данных'}")
        except Exception as e:
            print(f"Ошибка: {e}")
    else:
        print("Системная переменная start_up не равна '1' или код уже выполнялся.")





















# Маршрут для экспорта пользователя
@app.route('/export_user', methods=['GET'])
def export_user():
    try:
        export_id = request.args.get('export_id')
        if not export_id:
            raise Exception("export_id не найден в параметрах запроса")

        print(f"Получен export_id: {export_id}")  # Отладочное сообщение

        # Отправка третьего запроса для выгрузки базы данных
        third_url_template = f"{gc_url_export}/{export_id}?key={gc_api}"
        response = fetch(third_url_template)
        if response and response.get("success"):
            print("Ответ сервера:")
            print(response)  # Вывод ответа сервера в консоль сервера
            return jsonify(response), 200
        else:
            raise Exception(f"Ошибка в ответе от сервера: {response.get('error_message') if response else 'Нет данных'}")
    except Exception as e:
        print(f"Ошибка: {e}")  # Вывод ошибки в консоль сервера
        return jsonify({"error": str(e)}), 500


















def send_second_request(export_id):
    if export_id is None:
        raise Exception("export_id is None")
    # Формирование URL для второго запроса
    export_url_template = f"https://school.riverpsy.com/pl/api/account/exports/{export_id}?key=jqgxSMUnHWoKUcxF3MHSb77VUMk7HpFbO9SHnfVYwHtwqe1S81lqeKxrLPoSPWCephtYQuJwMFsCXEFmyByXdruDpDFgf6L7ij66K9ji0Kf2qAIwbTqEyJGB5MOHwyHl"
    try:
        response = requests.get(export_url_template)
        response.raise_for_status()
        return response.json()  # Возвращаем JSON-ответ сервера
    except requests.RequestException as e:
        raise Exception(f"Ошибка при выполнении запроса: {e}")

def load_data_from_json(json_data):
    if 'info' not in json_data or 'items' not in json_data['info'] or 'fields' not in json_data['info']:
        raise ValueError("Invalid JSON structure")

    items = json_data['info']['items']
    fields = json_data['info']['fields']

    db = 'data_gc.db'  # Указываем конкретную базу данных
    conn = sqlite3.connect(db)
    cursor = conn.cursor()

    for item in items:
        user_data = dict(zip(fields, item))
        # Проверяем наличие значений для полей и устанавливаем значения по умолчанию, если они отсутствуют
        user_data.setdefault('vk_id', '')
        user_data.setdefault('chat_id', '')
        user_data.setdefault('ws_st', '')
        user_data.setdefault('ws_stop', '')
        user_data.setdefault('web_st', '')
        user_data.setdefault('fin_prog', '')
        user_data.setdefault('b_city', '')
        user_data.setdefault('b_fin', '')
        user_data.setdefault('b_ban', '')
        user_data.setdefault('b_ign', '')
        user_data.setdefault('b_baners', '')  
        user_data.setdefault('b_butt', '')
        user_data.setdefault('b_mess', '')
        user_data.setdefault('shop_st', '')
        user_data.setdefault('curator', '')
        user_data.setdefault('pr1', '')
        user_data.setdefault('pr2', '')
        user_data.setdefault('pr3', '')
        user_data.setdefault('pr4', '')
        user_data.setdefault('pr5', '')
        user_data.setdefault('ad_url', '')
        user_data.setdefault('key_pr', '')
        user_data.setdefault('n_con', '')        
        user_data.setdefault('canal', '')
        user_data.setdefault('data_t', '')
        # Убираем плюс в начале телефона, если он присутствует
        if 'Телефон' in user_data and user_data['Телефон'].startswith('+'):
            user_data['Телефон'] = user_data['Телефон'][1:]

        query = '''
            INSERT INTO contacts (
                name, phone, email, vk_id, chat_id, ws_st, ws_stop, web_st, fin_prog, b_city, b_fin, b_ban, b_ign, b_baners, b_butt, b_mess, shop_st, pr1, pr2, pr3, pr4, pr5, ad_url, curator, key_pr, n_con, canal, data_t
            ) VALUES (
                :Имя, :Телефон, :Email, :vk_id, :chat_id, :ws_st, :ws_stop, :web_st, :fin_prog, :b_city, :b_fin, :b_ban, :b_ign, :b_baners, :b_butt, :b_mess, :shop_st, :pr1, :pr2, :pr3, :pr4, :pr5, :ad_url, :curator, :key_pr, :n_con, :canal, :data_t
            )
            '''
        cursor.execute(query, user_data)

    conn.commit()
    conn.close()














@app.route('/start', methods=['GET'])
def start():
    export_id = request.args.get('export_id')
    api_key_sys_control = request.args.get('api_sys')

    if export_id is None:
        return json.dumps({"error": "export_id is required"}), 400

    if api_key_sys_control != api_key_sys:
        return json.dumps({"error": "Unauthorized access"}), 403

    try:
        json_data = send_second_request(export_id)
        load_data_from_json(json_data)
        return "Data loaded successfully", 200
    except Exception as e:
        return json.dumps({"error": str(e)}), 500





    
def randomize_message(template):
    def replace_placeholder(match):
        options = match.group(1).split('|')
        return random.choice(options)

    return re.sub(r'\{([^}]+)\}', replace_placeholder, template)

def clean_phone_number(phone):
    if phone.startswith('+'):
        return phone[1:]
    return phone

def send_message(chat_id, message):
    #base_url = os.getenv('wa_url')
    #api_key = os.getenv('wa_api_key')
    full_url = f"{wa_url}{wa_ak}{ws_url_mes}{wa_api_key}"
    payload = {
        "chatId": chat_id,
        "message": message
    }
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.request("POST", full_url, headers=headers, json=payload)
    try:
        response_json = response.json()
    except ValueError:
        response_json = {"error": "Invalid JSON response"}
    return response_json

def check_and_send_mailings(mesage_db1, clean_db):
    try:
        results = []
        for database in DATABASES:
            conn = sqlite3.connect(database)
            cursor = conn.cursor()
            cursor.execute('SELECT name, phone FROM contacts')
            contacts = cursor.fetchall()
            conn.close()

            for contact in contacts:
                name = contact[0]
                chat_id = f"{clean_phone_number(contact[1])}@c.us"
                message = randomize_message(mesage_db1)
                message = message.replace('[[nemes]]', name)  # Подстановка имени
                send_result = send_message(chat_id, message)
                results.append({
                    "chat_id": chat_id,
                    "message": message,
                    "result": send_result
                })

            if clean_db == '1':
                conn = sqlite3.connect(database)
                cursor = conn.cursor()
                cursor.execute('DELETE FROM contacts')
                conn.commit()
                conn.close()

        return jsonify({"status": "success", "results": results}), 200
    except Exception as e:
        print(f"Error sending mailings: {e}")
        return jsonify({"status": "error", "message": str(e)}), 500

#С проверкой sys
@app.route('/start_db', methods=['GET'])
def start_mailings():
    mesage_db1 = request.args.get('mesage')
    clean_db = request.args.get('clean_db')
    api_sys_control = request.args.get('api_sys')
    

    if not mesage_db1:
        return "Parameter 'mesage' is required.", 400

    if api_sys_control != api_key_sys:
        return "EUR 22", 200

    return check_and_send_mailings(mesage_db1, clean_db)




        


@app.route('/add_data_gc', methods=['GET'])
def add_data_gc():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "err api key", 200

        name = request.args.get('name')
        phone = request.args.get('phone')
        email = request.args.get('email')
        vk_id = request.args.get('vk_id', '')
        chat_id = request.args.get('chat_id')
        ws_statys = request.args.get('ws_st')
        ws_stop = request.args.get('ws_stop')
        web_statys = request.args.get('web_st', 0, type=int)
        fin_progress = request.args.get('fin_prog', 0, type=int)
        shop_statys_full = request.args.get('shop_st')
        pr1 = request.args.get('pr1')
        pr2 = request.args.get('pr2')
        pr3 = request.args.get('pr3')
        pr4 = request.args.get('pr4')
        pr5 = request.args.get('pr5')
        ad_url = request.args.get('ad_url')
        curator = request.args.get('curator')
        key_pr = request.args.get('key_pr', '')
        n_con = request.args.get('n_con', '')
        canal = request.args.get('canal', '')

        if not name or not phone or not email:
            return "Parameters 'name', 'phone', and 'email' are required.", 400

        # Clean up phone number by removing any leading plus sign
        if phone.startswith('+'):
            phone = phone[1:]

        # Получение текущего времени в московском часовом поясе
        utc_now = datetime.utcnow()
        msk_tz = pytz.timezone('Europe/Moscow')
        msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
        data_t = msk_now.strftime('%Y-%m-%d %H:%M:%S')

        conn = sqlite3.connect('data_gc.db')
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM contacts WHERE phone = ? OR email = ?', (phone, email))
        existing_contact = cursor.fetchone()

        if existing_contact:
            cursor.execute('''
                UPDATE contacts SET
                    name = ?, email = ?, vk_id = ?, chat_id = ?, ws_st = ?, ws_stop = ?, 
                    web_st = ?, fin_prog = ?, shop_st = ?, pr1 = ?, pr2 = ?, 
                    pr3 = ?, pr4 = ?, pr5 = ?, ad_url = ?, curator = ?, key_pr = ?, n_con = ?, 
                    canal = ?, data_t = ?
                WHERE phone = ? OR email = ?
            ''', (name, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, 
                  shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator, key_pr, n_con, 
                  canal, data_t, phone, email))
        else:
            cursor.execute('''
                INSERT INTO contacts (
                    name, phone, email, vk_id, chat_id, ws_st, ws_stop, web_st, fin_prog, 
                    shop_st, pr1, pr2, pr3, pr4, pr5, ad_url, curator, key_pr, n_con, canal, data_t
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (name, phone, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, 
                  shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator, key_pr, n_con, canal, data_t))

        conn.commit()
        conn.close()

        return f"Contact updated/added: {name} - {phone} - {email}", 200
    except Exception as e:
        print(f"Error adding/updating contact: {e}")
        return "Internal Server Error", 500








@app.route('/add_data_ras', methods=['GET'])
def add_data_ras():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        name = request.args.get('name')
        phone = request.args.get('phone')
        email = request.args.get('email')
        vk_id = request.args.get('vk_id', '')
        chat_id = request.args.get('chat_id', '')
        ws_statys = request.args.get('ws_st', '')
        ws_stop = request.args.get('ws_stop', '')
        web_statys = request.args.get('web_st', 0, type=int)
        fin_progress = request.args.get('fin_prog', 0, type=int)
        shop_statys_full = request.args.get('shop_st', '')
        pr1 = request.args.get('pr1', '')
        pr2 = request.args.get('pr2', '')
        pr3 = request.args.get('pr3', '')
        pr4 = request.args.get('pr4', '')
        pr5 = request.args.get('pr5', '')
        ad_url = request.args.get('ad_url', '')
        curator = request.args.get('curator', '')
        key_pr = request.args.get('key_pr', '')
        n_con = request.args.get('n_con', '')
        canal = request.args.get('canal', '')

        if not name or not phone or not email:
            return "Parameters 'name', 'phone', and 'email' are required.", 400

        # Clean up phone number by removing any leading plus sign
        if phone.startswith('+'):
            phone = phone[1:]

        # Получение текущего времени в московском часовом поясе
        utc_now = datetime.utcnow()
        msk_tz = pytz.timezone('Europe/Moscow')
        msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
        data_t = msk_now.strftime('%Y-%m-%d %H:%M:%S')

        conn = sqlite3.connect('data1.db')
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM contacts WHERE phone = ? OR email = ?', (phone, email))
        existing_contact = cursor.fetchone()

        if existing_contact:
            cursor.execute('''
                UPDATE contacts SET
                    name = ?, email = ?, vk_id = ?, chat_id = ?, ws_st = ?, ws_stop = ?, 
                    web_st = ?, fin_prog = ?, shop_st = ?, pr1 = ?, pr2 = ?, 
                    pr3 = ?, pr4 = ?, pr5 = ?, ad_url = ?, curator = ?, key_pr = ?, n_con = ?, 
                    canal = ?, data_t = ?
                WHERE phone = ? OR email = ?
            ''', (name, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, 
                  shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator, key_pr, n_con, 
                  canal, data_t, phone, email))
        else:
            cursor.execute('''
                INSERT INTO contacts (
                    name, phone, email, vk_id, chat_id, ws_st, ws_stop, web_st, fin_prog, 
                    shop_st, pr1, pr2, pr3, pr4, pr5, ad_url, curator, key_pr, n_con, canal, data_t
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (name, phone, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, 
                  shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator, key_pr, n_con, canal, data_t))

        conn.commit()
        conn.close()

        return f"Contact updated/added: {name} - {phone} - {email}", 200
    except Exception as e:
        print(f"Error adding/updating contact: {e}")
        return "Internal Server Error", 500



    


       




        



@app.route('/data_gc')
def show_data_gc():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        conn = sqlite3.connect('data_gc.db')
        cursor = conn.cursor()
        cursor.execute('SELECT name, phone, email FROM contacts')
        contacts = cursor.fetchall()
        cursor.execute('SELECT COUNT(*) FROM contacts')
        total_users = cursor.fetchone()[0]
        conn.close()

        return render_template('data_gc.html', contacts=contacts, total_users=total_users)
    except Exception as e:
        print(f"Error showing contacts: {e}")
        return "Internal Server Error", 500


@app.route('/data_ras')
def show_data_ras():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        conn = sqlite3.connect('data1.db')
        cursor = conn.cursor()
        cursor.execute('SELECT name, phone, email FROM contacts')
        contacts = cursor.fetchall()
        cursor.execute('SELECT COUNT(*) FROM contacts')
        total_users = cursor.fetchone()[0]
        conn.close()

        return render_template('data_ras.html', contacts=contacts, total_users=total_users)
    except Exception as e:
        print(f"Error showing contacts: {e}")
        return "Internal Server Error", 500

































@app.route('/data_gc_tab', methods=['GET'])
def data_gc_tab():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('data_gc_tab.html')







@app.route('/data_gc_tab_out', methods=['GET'])
def data_gc_tab_out():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        conn = sqlite3.connect('data_gc.db')
        cursor = conn.cursor()
        cursor.execute('''
            SELECT id, name, phone, email, vk_id, chat_id, ws_st, ws_stop, web_st, fin_prog,
            b_city, b_fin, b_ban, b_ign, b_baners, b_butt, b_mess, shop_st, curator,
            pr1, pr2, pr3, pr4, pr5, ad_url, key_pr, n_con, canal, data_t, utm_source, utm_medium, utm_campaign, utm_term, utm_content
            FROM contacts
        ''')
        contacts = cursor.fetchall()
        conn.close()

        contacts_json = [{
            'id': contact[0], 'name': contact[1], 'phone': contact[2], 'email': contact[3],
            'vk_id': contact[4], 'chat_id': contact[5], 'ws_st': contact[6], 'ws_stop': contact[7],
            'web_st': contact[8], 'fin_prog': contact[9], 'b_city': contact[10], 'b_fin': contact[11],
            'b_ban': contact[12], 'b_ign': contact[13], 'b_baners': contact[14], 'b_butt': contact[15],
            'b_mess': contact[16], 'shop_st': contact[17], 'curator': contact[18], 'pr1': contact[19],
            'pr2': contact[20], 'pr3': contact[21], 'pr4': contact[22], 'pr5': contact[23],
            'ad_url': contact[24], 'key_pr': contact[25], 'n_con': contact[26], 'canal': contact[27],
            'data_t': contact[28],'utm_source': contact[29], 'utm_medium': contact[30], 'utm_campaign': contact[31],
            'utm_term': contact[32], 'utm_content': contact[33]
        } for contact in contacts]
        return jsonify(contacts_json), 200
    except Exception as e:
        error_message = f"Error getting data from data_gc: {e}"
        print(error_message)
        return error_message, 500



        
        


































DATABASE_NAME = 'data_gc.db'






def update_or_insert_user(db_name, user_data, mapping_template):
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()

    # Получение email пользователя из данных
    email = user_data.get('email')
    if not email:
        logging.error(f"User data missing email: {user_data}")
        return

    logging.debug(f"Processing user with email: {email}")
    
    # Проверка существования пользователя в базе данных по email
    cursor.execute("SELECT web_st FROM contacts WHERE email = ?", (email,))
    user = cursor.fetchone()
    logging.debug(f"User found: {user}")

    # Вынесение увеличения значения web_st в отдельный блок
    web_st_value = 1  # Инициализация значения web_st
    if user:
        # Проверка текущего значения web_st и его инкрементация
        current_web_st = user[0] if user[0] is not None and user[0] != "" else 0
        web_st_value = int(current_web_st) + 1
        logging.debug(f"Calculated web_st_value: {web_st_value}")

        # Обновление значения web_st
        cursor.execute("UPDATE contacts SET web_st = ? WHERE email = ?", (web_st_value, email))
        conn.commit()
        conn.close()
        logging.debug(f"User {email} web_st updated to {web_st_value}")
    else:
        conn.close()
        logging.debug(f"User {email} not found, proceeding with insert")

    # Открываем соединение снова для остальных операций
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()

    # Преобразование данных пользователя на основе шаблона сопоставления
    transformed_data = {}
    for json_key, db_column in mapping_template.items():
        value = user_data.get(json_key, "")
        
        if isinstance(value, list):
            # Проверяем тип элементов списка
            if all(isinstance(item, str) for item in value):
                transformed_data[db_column] = "; ".join(value)  # Сохраняем сообщения в строку
            else:
                logging.error(f"Expected list of strings for key {json_key}, but got: {value}")
                transformed_data[db_column] = ""
        else:
            transformed_data[db_column] = str(value)
    logging.debug(f"Transformed data: {transformed_data}")

    # Заполнение обязательных полей значениями по умолчанию
    required_fields = [
        "vk_id", "chat_id", "ws_st", "ws_stop", "web_st", "fin_prog",
        "b_city", "b_fin", "b_ban", "b_ign", "b_baners", "b_butt", "b_mess",
        "shop_st", "curator", "pr1", "pr2", "pr3", "pr4", "pr5", "ad_url",
        "key_pr", "n_con", "canal", "data_t", 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'
    ]
    for field in required_fields:
        if field not in transformed_data:
            transformed_data[field] = ""
    logging.debug(f"Transformed data after adding required fields: {transformed_data}")

    # Обработка номера телефона, если он есть
    if 'phone' in user_data:
        phone = user_data['phone']
        if phone.startswith('+'):
            phone = phone[1:]
        transformed_data['phone'] = phone
    logging.debug(f"Transformed data after phone processing: {transformed_data}")

    # Добавление значения web_st в данные для вставки
    transformed_data['web_st'] = web_st_value

    # Обновление данных пользователя в базе данных
    if user:
        update_query = "UPDATE contacts SET "
        update_values = []
        for column, value in transformed_data.items():
            update_query += f"{column} = ?, "
            update_values.append(value)
        update_query = update_query.rstrip(", ") + " WHERE email = ?"
        update_values.append(email)
        logging.debug(f"Update query: {update_query} with values: {update_values}")
        cursor.execute(update_query, update_values)
    else:
        columns = ', '.join(transformed_data.keys())
        placeholders = ', '.join('?' for _ in transformed_data)
        insert_query = f"INSERT INTO contacts ({columns}) VALUES ({placeholders})"
        insert_values = list(transformed_data.values())
        logging.debug(f"Insert query: {insert_query} with values: {insert_values}")
        cursor.execute(insert_query, insert_values)

    # Подтверждение изменений и закрытие соединения
    conn.commit()
    conn.close()
    logging.debug(f"User with email {email} processed successfully")


@app.route('/send_request', methods=['POST'])
def send_request():
    token = request.form.get('token')
    min_date = request.form.get('minDate')
    type = request.form.get('type')
    url = f'https://online.bizon365.ru/api/v1/webinars/reports/getlist?minDate={min_date}&type={type}'
    
    response = requests.get(url, headers={'X-Token': token})
    
    if response.status_code == 200:
        data = response.json()
        webinar_ids = [item['webinarId'] for item in data['list']]
        return jsonify(webinar_ids)
    else:
        return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code




@app.route('/send_get_request', methods=['GET'])
def send_get_request():
    token = request.args.get('token')
    webinarId = request.args.get('webinarId')
    url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinarId}'

    try:
        response = requests.get(url, headers={'X-Token': token})
        response.raise_for_status()  # Проверка на ошибки HTTP
        data = response.json()

        # Убедитесь, что report существует в данных
        if data is None or 'report' not in data:
            return jsonify({'error': 'No report data found'}), 500

        report = data.get('report', {})
        messages = data.get('messages', {})

        # Проверка на None перед использованием
        if report is None:
            return jsonify({'error': 'No report data found in the response'}), 500

        report_json_str = report.get('report', '{}')
        try:
            report_json = json.loads(report_json_str)
        except json.JSONDecodeError:
            report_json = {}

        messages_json_str = report.get('messages', '{}')
        try:
            messages_json = json.loads(messages_json_str)
        except json.JSONDecodeError:
            messages_json = {}

        users_meta = report_json.get('usersMeta', {})

        processed_emails = set()
        for user_id, user_data in users_meta.items():
            user_messages = messages_json.get(user_id, [])
            user_data['messages'] = user_messages
            email = user_data.get('email')
            if email and email not in processed_emails:
                update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
                processed_emails.add(email)

        return jsonify({'status': 'User data saved successfully'})
    
    except requests.exceptions.RequestException as e:
        return jsonify({'error': f'API request failed: {str(e)}'}), 500




@app.route('/webhookbz', methods=['POST'])
def webhookbz():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200

    data = request.json
    webinar_id = data.get('webinarId')

    if not webinar_id:
        return jsonify({'error': 'webinarId is required'}), 400

    url = f'https://online.bizon365.ru/api/v1/webinars/reports/get?webinarId={webinar_id}'
    response = requests.get(url, headers={'X-Token': api_key_sys})

    if response.status_code == 200:
        data = response.json()

        report = data.get('report', {})
        messages = data.get('messages', {})

        report_json_str = report.get('report', '{}')
        try:
            report_json = json.loads(report_json_str)
        except json.JSONDecodeError:
            report_json = {}

        messages_json_str = report.get('messages', '{}')
        try:
            messages_json = json.loads(messages_json_str)
        except json.JSONDecodeError:
            messages_json = {}

        users_meta = report_json.get('usersMeta', {})

        processed_emails = set()
        for user_id, user_data in users_meta.items():
            user_messages = messages_json.get(user_id, [])
            user_data['messages'] = user_messages
            email = user_data.get('email')
            if email and email not in processed_emails:
                update_or_insert_user(DATABASE_NAME, user_data, mapping_template)
                processed_emails.add(email)

        return jsonify({'status': 'User data saved successfully'})
    else:
        return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code



















@app.route('/biz_v', methods=['GET'])
def biz_v():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('biz_v.html')























@app.route('/ver', methods=['GET'])
def veref():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('ver.html')

@app.route('/se_mes', methods=['GET'])
def se_mes():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes.html')

@app.route('/se_mes_im', methods=['GET'])
def se_mes_im():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_im.html')

@app.route('/se_mes_ran', methods=['GET'])
def se_mes_ran():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_ran.html')

@app.route('/se_mes_im_ran', methods=['GET'])
def se_mes_im_ran():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_im_ran.html')

@app.route('/se_mes_im2', methods=['GET'])
def se_mes_im2():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_im2.html')

@app.route('/se_mes_f', methods=['GET'])
def se_mes_f():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_f.html')

@app.route('/up_gr', methods=['GET'])
def up_gr():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('up_gr.html')

@app.route('/up_user_gp', methods=['GET'])
def up_user_gp():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('up_user_gp.html')

@app.route('/del_user_gp', methods=['GET'])
def del_user_gp():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('del_user_gp.html')

@app.route('/up_ad', methods=['GET'])
def up_ad():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('up_ad.html')

@app.route('/del_ad', methods=['GET'])
def del_ad():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('del_ad.html')

@app.route('/se_opr', methods=['GET'])
def se_opr():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_opr.html')

@app.route('/online', methods=['GET'])
def online():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('online.html')

@app.route('/se_mes_f_gc', methods=['GET'])
def se_mes_f_gc():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_f_gc.html')





















































@app.route('/total_users', methods=['GET'])
def total_users():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        total_users_gc = 0
        total_users_ras = 0

        conn_gc = sqlite3.connect('data_gc.db')
        cursor_gc = conn_gc.cursor()
        cursor_gc.execute('SELECT COUNT(*) FROM contacts')
        total_users_gc = cursor_gc.fetchone()[0]
        conn_gc.close()

        conn_ras = sqlite3.connect('data1.db')
        cursor_ras = conn_ras.cursor()
        cursor_ras.execute('SELECT COUNT(*) FROM contacts')
        total_users_ras = cursor_ras.fetchone()[0]
        conn_ras.close()

        return jsonify({
            "total_users_gc": total_users_gc,
            "total_users_ras": total_users_ras
        }), 200
    except Exception as e:
        print(f"Error getting total users: {e}")
        return "Internal Server Error", 500








@app.route('/all_users_gc', methods=['GET'])
def all_users_gc():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        conn = sqlite3.connect('data_gc.db')
        cursor = conn.cursor()
        cursor.execute('SELECT name, phone, email FROM contacts')
        contacts = cursor.fetchall()
        conn.close()

        return jsonify(contacts), 200
    except Exception as e:
        print(f"Error getting all users from data_gc: {e}")
        return "Internal Server Error", 500



@app.route('/all_users_ras', methods=['GET'])
def all_users_ras():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        conn = sqlite3.connect('data1.db')
        cursor = conn.cursor()
        cursor.execute('SELECT name, phone, email FROM contacts')
        contacts = cursor.fetchall()
        conn.close()

        return jsonify(contacts), 200
    except Exception as e:
        print(f"Error getting all users from data_ras: {e}")
        return "Internal Server Error", 500




        

@app.route('/gc_db_no_email', methods=['GET'])
def gc_db_no_email():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        # Чтение параметров из GET-запроса
        name_d = request.args.get('name', '')
        phone_d = request.args.get('phone', '')
        pr1_d = request.args.get('pr1', '')
        pr2_d = request.args.get('pr2', '')
        pr3_d = request.args.get('pr3', '')

        # Проверка базы данных на наличие email по номеру телефона
        conn = sqlite3.connect('data_gc.db')
        cursor = conn.cursor()
        cursor.execute('SELECT email FROM contacts WHERE phone = ?', (phone_d,))
        result = cursor.fetchone()
        email_d = result[0] if result else ''
        conn.close()

        # Формирование JSON
        json_data = {
            "user": {
                "email": email_d,
                "phone": phone_d,
                "first_name": name_d,
                "addfields": {
                    "pr1": pr1_d,
                    "pr2": pr2_d,
                    "pr3": pr3_d
                }
            },
            "system": {
                "refresh_if_exists": 1
            },
            "session": {
                "utm_source": "",
                "utm_medium": "",
                "utm_content": "",
                "utm_campaign": "",
                "utm_group": "",
                "gcpc": "",
                "gcao": "",
                "referer": ""
            }
        }

        # Конвертация JSON в Base64
        json_str = json.dumps(json_data)
        params_d = base64.b64encode(json_str.encode('utf-8')).decode('utf-8')

        # Данные для отправки в теле запроса
        data = {
            'key': gc_api,
            'action': 'add',
            'params': params_d
        }

        # Отправка POST-запроса с данными в формате "form-data"
        response = requests.post(gc_url, data=data)

        # Возвращаем ответ от тестового адреса
        return {
            'status_code': response.status_code,
            'response_body': response.text
        }
    except Exception as e:
        print(f"Error in gc_db_no_email: {e}")
        return "Internal Server Error", 500





@app.route('/gc_db_email', methods=['GET'])
def gc_db_email():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        # Чтение параметров из GET-запроса
        name_d = request.args.get('name', '')
        email_d = request.args.get('email', '')
        phone_d = request.args.get('phone', '')
        pr1_d = request.args.get('pr1', '')
        pr2_d = request.args.get('pr2', '')
        pr3_d = request.args.get('pr3', '')

        # Формирование JSON
        json_data = {
            "user": {
                "email": email_d,
                "phone": phone_d,
                "first_name": name_d,
                "addfields": {
                    "pr1": pr1_d,
                    "pr2": pr2_d,
                    "pr3": pr3_d
                }
            },
            "system": {
                "refresh_if_exists": 1
            },
            "session": {
                "utm_source": "",
                "utm_medium": "",
                "utm_content": "",
                "utm_campaign": "",
                "utm_group": "",
                "gcpc": "",
                "gcao": "",
                "referer": ""
            }
        }

        # Конвертация JSON в Base64
        json_str = json.dumps(json_data)
        params_d = base64.b64encode(json_str.encode('utf-8')).decode('utf-8')

        # Данные для отправки в теле запроса
        data = {
            'key': gc_api,
            'action': action_d,
            'params': params_d
        }

        # Отправка POST-запроса с данными в формате "form-data"
        response = requests.post(gc_url, data=data)

        # Возвращаем ответ от тестового адреса
        return {
            'status_code': response.status_code,
            'response_body': response.text
        }
    except Exception as e:
        print(f"Error in gc_db_email: {e}")
        return "Internal Server Error", 500













@app.route('/gc_forms', methods=['GET'])
def gc_forms():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        # Чтение параметров из GET-запроса
        name_d = request.args.get('name', '')
        email_d = request.args.get('email', '')
        phone_d = request.args.get('phone', '')
        cod_pred = request.args.get('cod_pred', '')
        price = request.args.get('price', '')        
        utm_source = request.args.get('utm_source', '')
        utm_medium = request.args.get('utm_medium', '')
        utm_content = request.args.get('utm_content', '')
        utm_campaign = request.args.get('utm_campaign', '')
        utm_group = request.args.get('utm_group', '')
        gcpc = request.args.get('gcpc', '')
        # Формирование JSON
        json_data = {
            "user": {
                "email": email_d,
                "phone": phone_d,
                "first_name": name_d,
                "addfields": {
                    "pr1": "",
                    "pr2": "",
                    "pr3": ""
                }
            },
            "system": {
                "refresh_if_exists": 1
            },
            "session": {
                "utm_source": utm_source,
                "utm_medium": utm_medium,
                "utm_content": utm_content,
                "utm_campaign": utm_campaign,
                "utm_group": utm_group,
                "gcpc": gcpc,
                "gcao": "",
                "referer": ""
            },
        "deal":{
            "offer_code": cod_pred,
            "deal_cost": price
        }
        }

        # Конвертация JSON в Base64
        json_str = json.dumps(json_data)
        params_d = base64.b64encode(json_str.encode('utf-8')).decode('utf-8')

        # Данные для отправки в теле запроса
        data = {
            'key': gc_api,
            'action': action_d,
            'params': params_d
        }

        # Отправка POST-запроса с данными в формате "form-data"
        response = requests.post(gc_url_form, data=data)

        # Возвращаем ответ от тестового адреса
        return {
            'status_code': response.status_code,
            'response_body': response.text
        }
    except Exception as e:
        print(f"Error in gc_db_email: {e}")
        return "Internal Server Error", 500














curators = ["Anna", "Ekaterina", "Ivan", "Maria", "Sergey", "Olga", "Alex", "Natalia", "Dmitry", "Elena"]


mt_avp = {
    'name': 'Name',
    'phone': 'Phone',
    'email': 'Email'
}

mt_bhelp = {
    'name': 'name',
    'phone': 'phone',
    'email': 'email',
    'ad': 'ws_stop'
}

mt_gc = {
    'name': 'name',
    'phone': 'phone',
    'email': 'email',
    'ad': 'web_st'
}

mt_tl = {
    'name': 'name',
    'phone': 'phone',
    'email': 'email',
    'ad': 'ad_url'
}

mapp_templates = {
    'avp': mt_avp,
    'bhelp': mt_bhelp,
    'gc': mt_gc,
    'ad': mt_tl
}

DATABASE_NAME3 = 'data_gc.db'


def verify_phone_number(phone_number):
    if verifikation_start == "1":
        full_url_ver = f"{wa_url}{wa_ak}{ws_url_ver}{wa_api_key}"
        
        payload = json.dumps({"phoneNumber": phone_number})
        headers = {'Content-Type': 'application/json'}

        response = requests.post(full_url_ver, headers=headers, data=payload)
        
        if response.status_code == 200:
            response_body = response.json()
            return response_body.get('existsWhatsapp', 'false')
        else:
            return "Error"
    else:
        return "false"

def add_or_update_contact(contact_data):
    conn = sqlite3.connect(DATABASE_NAME3)
    cursor = conn.cursor()

    email = contact_data.get('email')
    if not email:
        logging.error(f"Missing email in contact data: {contact_data}")
        return

    utc_now = datetime.utcnow()
    msk_tz = pytz.timezone('Europe/Moscow')
    msk_now = utc_now.replace(tzinfo=pytz.utc).astimezone(msk_tz)
    contact_data['data_t'] = msk_now.strftime('%Y-%m-%d %H:%M:%S')

    cursor.execute("SELECT id FROM contacts WHERE email = ?", (email,))
    contact = cursor.fetchone()

    fields = [
        'name', 'phone', 'email', 'vk_id', 'chat_id', 'ws_st', 'ws_stop', 'web_st', 'fin_prog',
        'b_city', 'b_fin', 'b_ban', 'b_ign', 'b_baners', 'b_butt', 'b_mess', 'shop_st', 'curator',
        'pr1', 'pr2', 'pr3', 'pr4', 'pr5', 'ad_url', 'key_pr', 'n_con', 'canal', 'data_t', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'
    ]

    placeholders = ", ".join([f"{field} = ?" for field in fields])

    if contact:
        update_query = f"UPDATE contacts SET {placeholders} WHERE id = ?"
        cursor.execute(update_query, (*[contact_data.get(field, '') for field in fields], contact[0]))
    else:
        insert_query = f"INSERT INTO contacts ({', '.join(fields)}) VALUES ({', '.join(['?' for _ in fields])})"
        cursor.execute(insert_query, tuple(contact_data.get(field, '') for field in fields))

    conn.commit()
    conn.close()

@app.route('/add_data_ver_cur', methods=['GET'])
def add_data_ver_cur():
    global current_curator_index

    veref_on_off = request.args.get('ver', '0')  # Включает "1" и выключает "0" верификацию номера вместо verifikation_start
    curator_on_off = request.args.get('cur', '0')  # Включает "1" и выключает "0" назначение куратора
    
    template_key = request.args.get('template_key', 'avp')
    mapping_template_cur = mapp_templates.get(template_key, mt_avp)

    user_data = {mapping_template_cur[key]: request.args.get(key, "") for key in mapping_template_cur}

    if curator_on_off == "1":
        user_data['curator'] = curators[current_curator_index]

    if veref_on_off == "1":
        phone_verification_response = verify_phone_number(user_data.get('phone', ''))
        if phone_verification_response is not None:
            user_data['ws_st'] = phone_verification_response

    try:
        add_or_update_contact(user_data)
        if curator_on_off == "1":
            current_curator_index = (current_curator_index + 1) % len(curators)
        return jsonify({'status': 'success', 'message': f'User added with curator {user_data.get("curator", "not assigned")}'})
    except Exception as e:
        logging.error(f"Error adding user: {e}")
        return jsonify({'status': 'error', 'message': str(e)}), 500














DATABASE2 = 'data_gc.db'

def verify_phone_number(phone_number):
    full_url_ver = f"{wa_url}{wa_ak}{ws_url_ver}{wa_api_key}"
    payload = {"phoneNumber": phone_number}
    headers = {'Content-Type': 'application/json'}
    response = requests.post(full_url_ver, headers=headers, json=payload)
    if response.status_code == 200:
        response_body = response.json()
        return response_body.get('existsWhatsapp', 'false')
    else:
        return "Error"

def parse_csv_data(data):
    parsed_data = []
    for item in data:
        for key, value in item.items():
            headers = key.split(';')
            row = value.split(';')
            parsed_data.append(dict(zip(headers, row)))
    return parsed_data

def insert_data(data, verify_phone, add_curator):
    global current_curator_index
    conn = sqlite3.connect(DATABASE2)
    cursor = conn.cursor()

    for row in data:
        name = row.get('Name', '')
        phone = row.get('Phone', '').lstrip('+')
        email = row.get('Email', '')
        data_t = row.get('Date', '').strip('"')

        cursor.execute("SELECT 1 FROM contacts WHERE email = ? OR phone = ?", (email, phone))
        user_exists = cursor.fetchone()

        if user_exists:
            print(f"User with email {email} or phone {phone} already exists. Skipping insert.")
            continue

        if add_curator == "1":
            curator = curators[current_curator_index]
            current_curator_index = (current_curator_index + 1) % len(curators)
        else:
            curator = row.get('curator', '')

        if verify_phone == "1":
            ws_st = verify_phone_number(phone)
        else:
            ws_st = row.get('ws_st', '')

        columns = ['name', 'phone', 'email', 'vk_id', 'chat_id', 'ws_st', 'ws_stop', 'web_st', 'fin_prog', 'b_city', 'b_fin', 'b_ban', 'b_ign', 'b_baners', 'b_butt', 'b_mess', 'shop_st', 'curator', 'pr1', 'pr2', 'pr3', 'pr4', 'pr5', 'ad_url', 'key_pr', 'n_con', 'canal', 'data_t', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']
        values = [name, phone, email, row.get('vk_id', ''), row.get('chat_id', ''), ws_st, row.get('ws_stop', ''), row.get('web_st', 0), row.get('fin_prog', 0), row.get('b_city', ''), row.get('b_fin', ''), row.get('b_ban', ''), row.get('b_ign', ''), row.get('b_baners', ''), row.get('b_butt', ''), row.get('b_mess', ''), row.get('shop_st', ''), curator, row.get('pr1', ''), row.get('pr2', ''), row.get('pr3', ''), row.get('pr4', ''), row.get('pr5', ''), row.get('ad_url', ''), row.get('key_pr', ''), row.get('n_con', ''), row.get('canal', ''), data_t, row.get('utm_source', ''), row.get('utm_medium', ''), row.get('utm_campaign', ''), row.get('utm_term', ''), row.get('utm_content', '')]

        placeholders = ', '.join(['?' for _ in columns])
        columns_str = ', '.join(columns)

        query = f'''
            INSERT INTO contacts ({columns_str})
            VALUES ({placeholders})
        '''

        try:
            cursor.execute(query, values)
        except Exception as e:
            print(f"Error inserting row: {row}")
            print(f"Error message: {str(e)}")
            conn.rollback()
            raise

    conn.commit()
    conn.close()

@app.route('/upload_csv', methods=['POST'])
def upload_csv():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400
    if file and file.filename.endswith('.csv'):
        stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
        csv_input = csv.DictReader(stream)
        data = [row for row in csv_input]
        parsed_data = parse_csv_data(data)
        verify_phone = request.form.get('verify_phone', '0')
        add_curator = request.form.get('add_curator', '0')
        print(f"Verify Phone: {verify_phone}")
        print(f"Add Curator: {add_curator}")
        insert_data(parsed_data, verify_phone, add_curator)
        return jsonify({"message": "Data uploaded and inserted successfully"})
    return jsonify({"error": "Invalid file format"}), 400






@app.route('/upl_csv', methods=['GET'])
def se_upl_csv():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('upl_csv.html')





























@app.route('/gc_in', methods=['GET'])
def add_data_gc_in():
    global current_curator_index

    veref_on_off = request.args.get('ver', '0')  # Включает "1" и выключает "0" верификацию номера вместо verifikation_start
    curator_on_off = request.args.get('cur', '0')  # Включает "1" и выключает "0" назначение куратора
    
    template_key = request.args.get('template_key', 'avp')
    mapping_template_cur = mapp_templates.get(template_key, mt_avp)

    user_data = {mapping_template_cur[key]: request.args.get(key, "") for key in mapping_template_cur}

    if curator_on_off == "1":
        user_data['curator'] = curators[current_curator_index]

    if veref_on_off == "1":
        phone_verification_response = verify_phone_number(user_data.get('phone', ''))
        if phone_verification_response is not None:
            user_data['ws_st'] = phone_verification_response

    try:
        add_or_update_contact(user_data)
        if curator_on_off == "1":
            current_curator_index = (current_curator_index + 1) % len(curators)
        return jsonify({'status': 'success', 'message': f'User added with curator {user_data.get("curator", "not assigned")}'})
    except Exception as e:
        logging.error(f"Error adding user: {e}")
        return jsonify({'status': 'error', 'message': str(e)}), 500

























@app.route('/tl_help.js')
def serve_vk_bridge():
    script_content = """
function mySuccessFunction(form) {
    if (!form) return;
    if (form instanceof jQuery) {
        form = form.get(0);
    }

 
    var obj = {};
    var inputs = form.elements;
    Array.prototype.forEach.call(inputs, function(input) {
        if (input.type === 'radio') {
            if (input.checked) obj[input.name] = input.value;
        } else {
            obj[input.name] = input.value;
        }
    });

  
    var email = obj["Email"] || "";
    var phone = obj["Phone"] || "";
    var name = obj["Name"] || "";

    console.log("name:", name);
    console.log("email:", email);
    console.log("phone:", phone);

  
    var urlParams = new URLSearchParams(window.location.search);
    var utm_source = urlParams.get('utm_source') || "0";
    var utm_medium = urlParams.get('utm_medium') || "0";
    var utm_campaign = urlParams.get('utm_campaign') || "0";
    var utm_content = urlParams.get('utm_content') || "0";
    var utm_term = urlParams.get('utm_term') || "0";
    var gcpc = urlParams.get('gcpc') || "0";



    var redirectUrl;
    if (form.id === formId1) {
        redirectUrl = new URL(redirectUrl1);
    } else if (form.id === formId2) {
        redirectUrl = new URL(redirectUrl2);
    } else if (form.id === formId3) {
        redirectUrl = new URL(redirectUrl3);
    } else {
        console.error('Неизвестный ID формы:', form.id);
        return;
    }


    var queryString = '?ups=' + encodeURIComponent(ups);
    queryString += '&name=' + encodeURIComponent(name);
    queryString += '&email=' + encodeURIComponent(email);
    queryString += '&phone=' + encodeURIComponent(phone);
    queryString += '&utm_source=' + encodeURIComponent(utm_source);
    queryString += '&utm_medium=' + encodeURIComponent(utm_medium);
    queryString += '&utm_campaign=' + encodeURIComponent(utm_campaign);
    queryString += '&utm_content=' + encodeURIComponent(utm_content);
    queryString += '&utm_term=' + encodeURIComponent(utm_term);
    queryString += '&gcpc=' + encodeURIComponent(gcpc);


    console.log('Сформированный URL:', redirectUrl.toString() + queryString);


    window.open(redirectUrl.toString() + queryString, '_blank');
}

if (document.readyState !== 'loading') {
    us_sendFormAfterSuccess();
} else {
    document.addEventListener('DOMContentLoaded', us_sendFormAfterSuccess);
}

function us_sendFormAfterSuccess() {
    var forms = document.querySelectorAll('.js-form-proccess');
    Array.prototype.forEach.call(forms, function(form) {
        form.addEventListener('tildaform:aftersuccess', function(e) {
            e.preventDefault(); 
            mySuccessFunction(form);
        });
    });
}
    """
    return Response(script_content, mimetype='application/javascript')








initialize_requests()



if __name__ == '__main__':
    
    app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))