File size: 124,405 Bytes
cc7b121
c712630
a304bca
c712630
 
 
7ea0e3b
c712630
00530ba
1673126
c712630
793bf62
46cb469
 
96fde15
c712630
 
 
9a92d35
c712630
 
7ea0e3b
c712630
9a92d35
7ea0e3b
c712630
 
 
2ae3775
f734017
c712630
1673126
a304bca
c712630
 
46cb469
0a96f08
cb79533
57a6639
 
f734017
57a6639
 
96fde15
 
 
 
 
c712630
96fde15
1673126
 
96fde15
1673126
96fde15
1673126
 
 
 
 
96fde15
 
 
 
 
 
 
 
 
1673126
 
96fde15
cc7b121
f734017
96fde15
cc7b121
9b6ae69
cb79533
f734017
c712630
46cb469
9b6ae69
 
f734017
 
1673126
f734017
cc7b121
1673126
f734017
cc7b121
f734017
 
cc7b121
96fde15
 
 
 
93cc53b
 
 
 
 
 
 
7823b59
cc7b121
 
 
 
 
 
 
f734017
96fde15
 
 
 
 
 
 
cb79533
96fde15
 
 
cc7b121
96fde15
 
 
 
 
 
 
 
 
 
2ae3775
96fde15
 
 
 
 
 
 
 
1673126
f734017
96fde15
 
 
 
 
 
 
c712630
 
 
 
 
1673126
c712630
 
1673126
cc7b121
1673126
 
c712630
 
1673126
c712630
1673126
cc7b121
 
c712630
1673126
cc7b121
1673126
f734017
 
c712630
 
a304bca
c712630
 
 
 
 
d6a8eff
c712630
1673126
 
b7b4894
c712630
1673126
2ae3775
 
 
 
 
 
1673126
46cb469
93cc53b
2ae3775
 
1673126
 
 
 
a304bca
84ffafd
 
a304bca
2ae3775
1673126
2ae3775
a304bca
1673126
 
 
 
 
 
84ffafd
2ae3775
 
 
84ffafd
96fde15
84ffafd
 
2ae3775
 
84ffafd
96fde15
 
84ffafd
2ae3775
 
84ffafd
46cb469
2ae3775
 
46cb469
84ffafd
 
 
 
 
 
 
cb79533
84ffafd
 
 
 
 
 
 
 
 
 
 
 
 
cb79533
c1770d9
84ffafd
c1770d9
84ffafd
c1770d9
84ffafd
c1770d9
 
568e5ba
c1770d9
84ffafd
 
 
 
 
cb79533
46cb469
84ffafd
 
 
f734017
2ae3775
84ffafd
2ae3775
 
84ffafd
2ae3775
 
f734017
2ae3775
84ffafd
cb79533
f734017
84ffafd
 
2ae3775
 
 
 
 
 
 
 
 
 
 
 
 
84ffafd
2ae3775
 
 
84ffafd
 
 
2ae3775
 
 
84ffafd
96fde15
84ffafd
 
2ae3775
96fde15
2ae3775
f734017
2ae3775
 
 
cb79533
f734017
2ae3775
 
 
 
cb79533
c1770d9
2ae3775
 
 
cb79533
2ae3775
 
c1770d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84ffafd
2ae3775
 
 
 
 
46cb469
2ae3775
3ab8a08
2ae3775
 
46cb469
3ab8a08
c1770d9
46cb469
c712630
 
 
a304bca
 
 
 
 
96fde15
 
 
 
 
 
84ffafd
 
 
 
93cc53b
84ffafd
 
 
 
 
 
 
 
 
f734017
2ae3775
84ffafd
3ab8a08
c1770d9
 
 
 
 
3ab8a08
2ae3775
 
84ffafd
 
 
 
 
46cb469
96fde15
84ffafd
96fde15
 
 
84ffafd
2ae3775
96fde15
 
84ffafd
96fde15
 
2ae3775
84ffafd
2ae3775
 
 
 
 
 
96fde15
 
 
2ae3775
 
 
 
 
 
 
 
93cc53b
 
 
2ae3775
 
 
 
 
 
 
3ab8a08
568e5ba
96fde15
 
 
 
 
 
2ae3775
96fde15
 
 
 
2ae3775
 
96fde15
 
 
 
84ffafd
2ae3775
 
96fde15
 
 
 
 
 
 
 
 
2ae3775
96fde15
 
 
 
2ae3775
 
 
 
96fde15
 
2ae3775
96fde15
2ae3775
 
96fde15
 
2ae3775
 
 
 
 
 
 
 
 
 
96fde15
2ae3775
 
96fde15
 
2ae3775
96fde15
2ae3775
 
96fde15
 
 
2ae3775
96fde15
 
2ae3775
 
96fde15
 
 
2ae3775
96fde15
 
2ae3775
96fde15
2ae3775
96fde15
 
f734017
 
 
 
c1770d9
96fde15
46cb469
c1770d9
f734017
fdd1b2c
46cb469
c1770d9
46cb469
 
2ae3775
 
 
 
 
 
46cb469
 
 
 
9b6ae69
 
46cb469
84ffafd
1673126
9b6ae69
2ae3775
 
 
 
 
 
 
 
d420ce5
1673126
 
a304bca
f734017
a304bca
2ae3775
a304bca
 
 
1673126
 
84ffafd
d420ce5
2ae3775
84ffafd
 
 
 
d420ce5
a304bca
 
c5aa395
a304bca
1673126
 
 
 
 
 
 
 
f734017
1673126
f734017
 
1673126
 
 
f734017
 
1673126
a304bca
f734017
a304bca
 
 
 
 
 
 
 
1673126
a304bca
 
1673126
f734017
46cb469
96fde15
46cb469
96fde15
 
f734017
c1770d9
 
f734017
 
2ae3775
96fde15
 
 
 
 
46cb469
96fde15
 
3ab8a08
c1770d9
 
 
91d3e20
 
 
 
 
 
 
c1770d9
 
568e5ba
91d3e20
c1770d9
3ab8a08
c1770d9
568e5ba
c1770d9
3ab8a08
96fde15
 
46cb469
84ffafd
46cb469
 
84ffafd
 
 
 
46cb469
 
 
 
84ffafd
 
 
 
 
 
 
 
 
 
 
 
 
46cb469
 
 
 
2ae3775
46cb469
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734017
96fde15
 
46cb469
96fde15
 
84ffafd
 
 
 
 
96fde15
f734017
96fde15
 
 
 
 
 
 
2ae3775
96fde15
 
 
c712630
 
 
 
 
00530ba
c712630
 
 
 
00530ba
 
1673126
 
00530ba
c712630
1673126
46cb469
 
 
 
 
a304bca
00530ba
 
 
 
 
 
 
 
 
93cc53b
00530ba
 
 
 
 
ca44ea6
 
00530ba
 
 
 
 
 
 
 
 
ca44ea6
46cb469
 
93cc53b
00530ba
93cc53b
 
 
 
cb79533
00530ba
 
 
 
 
 
 
 
 
 
 
 
cb79533
00530ba
 
cb79533
 
 
 
 
 
 
 
 
 
 
3ab8a08
 
00530ba
 
 
cb79533
46cb469
 
 
 
 
ca44ea6
 
 
 
 
 
 
 
 
 
2ae3775
 
46cb469
 
 
 
 
 
 
93cc53b
 
 
 
 
2ae3775
 
 
 
 
 
c1770d9
 
ca44ea6
c1770d9
a304bca
 
 
 
cb79533
 
 
 
 
 
 
 
 
a304bca
cb79533
 
 
 
 
93cc53b
 
a304bca
cb79533
 
 
 
96fde15
93cc53b
cb79533
 
 
 
 
00530ba
 
 
 
 
 
 
46cb469
 
 
 
 
 
00530ba
cb79533
 
 
 
 
 
 
 
93cc53b
 
 
 
00530ba
 
 
cb79533
 
 
00530ba
 
cb79533
a304bca
cb79533
 
 
00530ba
cb79533
 
00530ba
cb79533
 
 
 
00530ba
96fde15
568e5ba
96fde15
c1770d9
96fde15
 
3ab8a08
568e5ba
96fde15
c1770d9
 
 
 
 
 
 
 
568e5ba
 
c1770d9
568e5ba
c1770d9
 
 
 
 
 
 
 
 
 
a304bca
96fde15
 
 
c1770d9
 
 
 
 
 
 
 
cb79533
00530ba
96fde15
 
 
00530ba
 
96fde15
 
 
ca44ea6
 
 
 
 
 
 
 
96fde15
2ae3775
 
c1770d9
 
 
 
568e5ba
 
2ae3775
c1770d9
2ae3775
 
c1770d9
 
 
2ae3775
96fde15
 
 
 
3ab8a08
96fde15
 
 
cb79533
c1770d9
93cc53b
568e5ba
 
93cc53b
 
cb79533
 
 
 
00530ba
c1770d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb79533
 
96fde15
f734017
96fde15
c1770d9
 
 
93cc53b
c1770d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96fde15
 
93cc53b
 
 
 
c1770d9
 
 
93cc53b
c1770d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93cc53b
 
96fde15
 
 
 
c1770d9
 
 
46cb469
3ab8a08
00530ba
cb79533
a304bca
00530ba
 
96fde15
93cc53b
96fde15
00530ba
96fde15
a304bca
00530ba
 
46cb469
 
00530ba
7ea0e3b
1673126
e49e88d
c5aa395
7ea0e3b
9b6ae69
96fde15
c1770d9
46cb469
c1770d9
 
96fde15
 
46cb469
96fde15
 
 
 
 
1673126
 
96fde15
 
93cc53b
 
1673126
 
cb79533
 
 
c1770d9
cb79533
 
93cc53b
3ab8a08
 
93cc53b
568e5ba
 
cb79533
93cc53b
46cb469
1673126
 
cb79533
 
 
c1770d9
96fde15
 
 
 
 
 
46cb469
96fde15
 
 
 
 
9b6ae69
323b301
cb79533
502f979
cb79533
 
502f979
96fde15
 
 
 
c1770d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96fde15
 
93cc53b
c1770d9
 
 
 
 
 
 
 
 
 
 
 
 
 
93cc53b
 
96fde15
 
46cb469
7ea0e3b
cb79533
96fde15
46cb469
96fde15
46cb469
96fde15
 
 
 
46cb469
96fde15
 
9b6ae69
c5aa395
e49e88d
cb79533
1673126
cb79533
c1770d9
cb79533
7ea0e3b
 
93cc53b
7ea0e3b
c1770d9
568e5ba
d6a8eff
 
7ea0e3b
46cb469
c1770d9
cb79533
 
 
1673126
c1770d9
 
 
1673126
cb79533
c1770d9
cb79533
46cb469
 
cb79533
c1770d9
cb79533
 
d420ce5
cb79533
1673126
cb79533
c1770d9
cb79533
 
 
 
 
 
c1770d9
cb79533
 
 
1673126
c1770d9
 
 
1673126
cb79533
c1770d9
cb79533
46cb469
 
cb79533
c1770d9
cb79533
 
1673126
cb79533
96fde15
 
c1770d9
96fde15
 
 
 
46cb469
96fde15
 
 
 
 
c1770d9
 
 
96fde15
 
c1770d9
96fde15
93cc53b
 
 
c1770d9
93cc53b
 
 
 
 
 
c1770d9
93cc53b
 
 
 
 
 
 
c1770d9
 
 
93cc53b
 
c1770d9
93cc53b
 
46cb469
96fde15
c1770d9
96fde15
 
 
 
f734017
46cb469
00530ba
c1770d9
 
 
00530ba
46cb469
 
 
f734017
 
96fde15
2ae3775
568e5ba
96fde15
 
 
91d3e20
 
 
 
 
 
ca44ea6
 
 
 
cb79533
91d3e20
1673126
3ab8a08
 
 
 
 
2ae3775
96fde15
ca44ea6
 
96fde15
ca44ea6
 
91d3e20
ca44ea6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96fde15
 
c5aa395
 
2ae3775
c1770d9
 
 
 
 
2ae3775
 
 
 
 
 
 
91d3e20
 
 
2ae3775
 
 
 
 
 
96fde15
 
c1770d9
3ab8a08
96fde15
c1770d9
96fde15
00530ba
a304bca
91d3e20
96fde15
c1770d9
3ab8a08
96fde15
 
 
2ae3775
c1770d9
 
2ae3775
 
 
 
568e5ba
c1770d9
2ae3775
00530ba
c1770d9
 
 
00530ba
cb79533
c1770d9
cb79533
46cb469
 
00530ba
c1770d9
c5aa395
00530ba
e49e88d
cb79533
96fde15
 
c1770d9
 
96fde15
 
 
46cb469
c1770d9
96fde15
2ae3775
 
 
 
 
c1770d9
 
3ab8a08
2ae3775
c1770d9
 
2ae3775
 
46cb469
cb79533
 
96fde15
46cb469
cb79533
c1770d9
 
 
cb79533
46cb469
 
 
cb79533
 
c5aa395
c1770d9
 
 
 
 
e49e88d
96fde15
46cb469
c712630
 
 
 
 
 
 
7ea0e3b
 
46cb469
7ea0e3b
c1770d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
568e5ba
c712630
 
cb79533
c712630
 
 
 
 
 
 
1673126
 
 
cc7b121
f734017
 
46cb469
1673126
 
 
2ae3775
cc7b121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93cc53b
 
cc7b121
 
 
 
 
 
1673126
502f979
46cb469
c712630
1673126
f734017
 
c712630
 
46cb469
 
 
 
 
 
 
cc7b121
 
 
46cb469
cc7b121
 
 
46cb469
cc7b121
93cc53b
 
46cb469
cc7b121
3ab8a08
cc7b121
3ab8a08
cc7b121
3ab8a08
cc7b121
c1770d9
3ab8a08
c1770d9
cc7b121
 
93cc53b
 
 
2ae3775
c1770d9
 
 
 
93cc53b
 
46cb469
7823b59
cc7b121
 
46cb469
 
 
 
 
c712630
 
1673126
93cc53b
46cb469
cc7b121
93cc53b
cc7b121
 
 
 
 
 
cb79533
 
 
 
93cc53b
a304bca
c1770d9
 
 
 
f734017
d420ce5
502f979
 
 
 
9b6ae69
 
b7b4894
502f979
1673126
cc7b121
93cc53b
cc7b121
 
2ae3775
cc7b121
 
c1770d9
 
 
 
 
93cc53b
cc7b121
 
 
1673126
502f979
f734017
502f979
 
7ea0e3b
 
c712630
7ea0e3b
46cb469
93cc53b
1673126
c1770d9
568e5ba
1673126
 
3ab8a08
46cb469
cb79533
cc7b121
 
 
2ae3775
cc7b121
3ab8a08
c1770d9
568e5ba
c1770d9
cc7b121
 
568e5ba
cc7b121
c1770d9
 
 
 
 
 
 
 
 
 
 
 
cc7b121
 
568e5ba
fdd1b2c
c1770d9
00530ba
1673126
cb79533
 
00530ba
 
46cb469
96fde15
 
2ae3775
c1770d9
2ae3775
46cb469
 
cb79533
cc7b121
 
 
2ae3775
c1770d9
 
2ae3775
 
 
cc7b121
 
2ae3775
cc7b121
2ae3775
 
 
 
568e5ba
c1770d9
2ae3775
cc7b121
 
93cc53b
2ae3775
c1770d9
3ab8a08
 
 
c1770d9
 
 
 
 
93cc53b
 
84ffafd
 
c1770d9
93cc53b
 
 
 
 
 
 
 
 
 
 
 
c1770d9
93cc53b
 
 
c1770d9
 
 
 
 
 
cc7b121
96fde15
00530ba
f734017
00530ba
1673126
96fde15
 
 
 
46cb469
 
96fde15
cc7b121
 
 
 
 
 
 
 
96fde15
 
 
 
 
cb79533
 
00530ba
46cb469
cc7b121
cb79533
cc7b121
 
 
 
 
 
 
 
 
 
 
 
 
cb79533
ccd7872
f734017
 
 
96fde15
 
 
cc7b121
96fde15
 
 
f734017
96fde15
 
f734017
 
cc7b121
 
 
 
 
 
 
96fde15
f734017
96fde15
ccd7872
 
93cc53b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c712630
f734017
 
c1770d9
cc7b121
7823b59
 
93cc53b
cc7b121
 
 
 
 
 
 
7823b59
93cc53b
cc7b121
7823b59
f734017
cc7b121
c712630
e49e88d
 
f734017
cc7b121
 
7823b59
f734017
ca44ea6
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
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047

import os
from flask import Flask, request, Response, render_template_string, jsonify, redirect, url_for
import hmac
import hashlib
import json
from urllib.parse import unquote, parse_qs, quote
import time
from datetime import datetime
import logging
import threading
import random
import pytz
import uuid

from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError

BOT_TOKEN = os.getenv("BOT_TOKEN", "7835463659:AAGNePbelZIAOeaglyQi1qulOqnjs4BGQn4")
HOST = '0.0.0.0'
PORT = 7860
DATA_FILE = 'data.json'

REPO_ID = "flpolprojects/examplebonus"
HF_DATA_FILE_PATH = "data.json"
HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE")
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")

ALMATY_TZ = pytz.timezone('Asia/Almaty')

app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
app.secret_key = os.urandom(24)

_data_lock = threading.Lock()
visitor_data_cache = {}

def generate_unique_id(all_data):
    while True:
        new_id = str(random.randint(10000, 99999))
        if new_id not in all_data:
            return new_id

def download_data_from_hf():
    global visitor_data_cache
    if not HF_TOKEN_READ:
        logging.warning("HF_TOKEN_READ not set. Skipping Hugging Face download.")
        return False
    try:
        logging.info(f"Attempting to download {HF_DATA_FILE_PATH} from {REPO_ID}...")
        hf_hub_download(
            repo_id=REPO_ID,
            filename=HF_DATA_FILE_PATH,
            repo_type="dataset",
            token=HF_TOKEN_READ,
            local_dir=".",
            local_dir_use_symlinks=False,
            force_download=True,
            etag_timeout=10
        )
        logging.info("Data file successfully downloaded from Hugging Face.")
        with _data_lock:
            try:
                with open(DATA_FILE, 'r', encoding='utf-8') as f:
                    visitor_data_cache = json.load(f)
                logging.info("Successfully loaded downloaded data into cache.")
            except (FileNotFoundError, json.JSONDecodeError) as e:
                 logging.error(f"Error reading downloaded data file: {e}. Starting with empty cache.")
                 visitor_data_cache = {}
        return True
    except RepositoryNotFoundError:
        logging.error(f"Hugging Face repository '{REPO_ID}' not found. Cannot download data.")
        return False
    except Exception as e:
        logging.error(f"Error downloading data from Hugging Face: {e}")
        return False

def load_visitor_data():
    global visitor_data_cache
    with _data_lock:
        if not visitor_data_cache:
            try:
                with open(DATA_FILE, 'r', encoding='utf-8') as f:
                    visitor_data_cache = json.load(f)
                logging.info("Visitor data loaded from local JSON.")
            except FileNotFoundError:
                logging.warning(f"{DATA_FILE} not found locally. Starting with empty data.")
                visitor_data_cache = {}
            except json.JSONDecodeError:
                logging.error(f"Error decoding {DATA_FILE}. Starting with empty data.")
                visitor_data_cache = {}
            except Exception as e:
                logging.error(f"Unexpected error loading visitor data: {e}")
                visitor_data_cache = {}
        
        if "organization_details" not in visitor_data_cache:
            visitor_data_cache["organization_details"] = {}

        if "bonus_program_settings" not in visitor_data_cache:
            visitor_data_cache["bonus_program_settings"] = {
                "invoice_bonus_percentage": 2,
                "referral_promo_bonus": 50,
                "referrer_first_purchase_percentage": 5
            }

def save_visitor_data():
    try:
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4)
        logging.info(f"Visitor data successfully saved to {DATA_FILE}.")
        upload_data_to_hf_async()
    except Exception as e:
        logging.error(f"Error saving visitor data: {e}")

def upload_data_to_hf():
    if not HF_TOKEN_WRITE:
        logging.warning("HF_TOKEN_WRITE not set. Skipping Hugging Face upload.")
        return
    if not os.path.exists(DATA_FILE):
        logging.warning(f"{DATA_FILE} does not exist. Skipping upload.")
        return

    try:
        api = HfApi()
        with _data_lock:
             if not os.path.getsize(DATA_FILE) > 0:
                 logging.warning(f"{DATA_FILE} is empty. Skipping upload.")
                 return

             logging.info(f"Attempting to upload {DATA_FILE} to {REPO_ID}/{HF_DATA_FILE_PATH}...")
             api.upload_file(
                 path_or_fileobj=DATA_FILE,
                 path_in_repo=HF_DATA_FILE_PATH,
                 repo_id=REPO_ID,
                 repo_type="dataset",
                 token=HF_TOKEN_WRITE,
                 commit_message=f"Update bonus data {datetime.now(ALMATY_TZ).strftime('%Y-%m-%d %H:%M:%S')}"
             )
        logging.info("Bonus data successfully uploaded to Hugging Face.")
    except Exception as e:
        logging.error(f"Error uploading data to Hugging Face: {e}")

def upload_data_to_hf_async():
     upload_thread = threading.Thread(target=upload_data_to_hf, daemon=True)
     upload_thread.start()

def periodic_backup():
     if not HF_TOKEN_WRITE:
         logging.info("Periodic backup disabled: HF_TOKEN_WRITE not set.")
         return
     while True:
         time.sleep(3600)
         logging.info("Initiating periodic backup...")
         upload_data_to_hf()

def verify_telegram_data(init_data_str):
    try:
        parsed_data = parse_qs(init_data_str)
        received_hash = parsed_data.pop('hash', [None])[0]

        if not received_hash:
            return None, False

        data_check_list = [f"{key}={value[0]}" for key, value in sorted(parsed_data.items())]
        data_check_string = "\n".join(data_check_list)

        secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest()
        calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()

        if calculated_hash == received_hash:
            auth_date = int(parsed_data.get('auth_date', [0])[0])
            if (int(time.time()) - auth_date) > 86400:
                 logging.warning(f"Telegram InitData is older than 24 hours.")
            return parsed_data, True
        else:
            logging.warning(f"Data verification failed.")
            return parsed_data, False
    except Exception as e:
        logging.error(f"Error verifying Telegram data: {e}")
        return None, False

TEMPLATE = """
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no, viewport-fit=cover">
    <title>Bonus</title>
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <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=Manrope:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --tg-theme-bg-color: var(--tg-bg-color, #181818);
            --tg-theme-text-color: var(--tg-text-color, #ffffff);
            --tg-theme-hint-color: var(--tg-hint-color, #aaaaaa);
            --tg-theme-button-color: var(--tg-button-color, #FFC107);
            --tg-theme-button-text-color: var(--tg-button-text-color, #000000);
            --tg-theme-secondary-bg-color: var(--tg-secondary-bg-color, #2c2c2e);
            --brand-red: #F44336;
            --brand-green: #4CAF50;
            --brand-blue: #2196F3;
            --border-radius-l: 24px;
            --border-radius-m: 16px;
            --padding-m: 16px;
            --font-family: 'Manrope', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            --shadow-color: rgba(255, 193, 7, 0.15);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        html, body {
            background-color: var(--tg-theme-bg-color);
            font-family: var(--font-family);
            color: var(--tg-theme-text-color);
            padding: var(--padding-m);
            overscroll-behavior-y: none;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            visibility: hidden;
            min-height: 100vh;
        }
        .container { max-width: 600px; margin: 0 auto; display: flex; flex-direction: column; gap: calc(var(--padding-m) + 4px); animation: fadeIn 0.5s ease-out forwards; }
        .header { text-align: left; padding: 8px 0; }
        .logo { font-size: 2.5em; font-weight: 800; letter-spacing: -1px; }
        .logo span { color: var(--tg-theme-button-color); }
        .welcome-text { font-size: 1.05em; color: var(--tg-theme-hint-color); margin-top: 4px; }
        .nav-buttons {
            display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
            background-color: var(--tg-theme-secondary-bg-color);
            border-radius: 50px; padding: 6px; position: sticky; top: var(--padding-m); z-index: 100;
            backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
        }
        .nav-btn {
            padding: 12px 15px; border: none; border-radius: 50px;
            background-color: transparent; color: var(--tg-theme-hint-color);
            font-family: var(--font-family); font-weight: 700; font-size: 1em;
            cursor: pointer; transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        }
        .nav-btn.active { background-color: var(--tg-theme-button-color); color: var(--tg-theme-button-text-color); box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .content-section { display: none; flex-direction: column; gap: calc(var(--padding-m) + 4px); }
        .content-section.active { display: flex; }
        .financial-summary-card {
            background: linear-gradient(135deg, var(--tg-secondary-bg-color) 0%, #3a3a3c 100%);
            border-radius: var(--border-radius-l);
            padding: 24px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.25);
            border: 1px solid rgba(255, 255, 255, 0.1);
            animation: slideUp 0.6s ease-out forwards;
        }
        .main-balance-section { text-align: center; border-bottom: 1px solid rgba(255, 255, 255, 0.1); padding-bottom: 20px; margin-bottom: 20px; }
        .main-balance-section .card-label { font-size: 1.2em; font-weight: 600; color: var(--tg-theme-hint-color); margin-bottom: 8px; }
        .main-balance-section .bonus-amount { font-size: 4em; font-weight: 800; letter-spacing: -2px; line-height: 1; color: var(--tg-theme-button-color); }
        .sub-balances-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--padding-m); }
        .sub-balance-item { text-align: center; }
        .sub-balance-item .card-label { font-size: 1em; font-weight: 500; color: var(--tg-theme-hint-color); margin-bottom: 8px; }
        .sub-balance-item .amount { font-size: 1.8em; font-weight: 700; }
        .sub-balance-item .amount.debt { color: var(--brand-red); }
        .sub-balance-item .amount.referral { color: var(--brand-blue); }
        .animated-card { animation: slideUp 0.6s ease-out 0.2s forwards; opacity: 0; }
        .section-card {
            background-color: var(--tg-theme-secondary-bg-color); border-radius: var(--border-radius-m);
            padding: 20px; border: 1px solid rgba(255, 255, 255, 0.05);
        }
        .promo-card .card-label { display: flex; align-items: center; justify-content: center; gap: 8px; font-size: 1em; font-weight: 500; color: var(--tg-theme-hint-color); margin-bottom: 12px; }
        .promo-info-icon { cursor: pointer; position: relative; display: flex; align-items: center; }
        .promo-info-icon .tooltip {
            visibility: hidden; opacity: 0; position: absolute; bottom: 140%; left: 50%;
            transform: translateX(-50%); background-color: #333; color: #fff; text-align: left;
            border-radius: 8px; padding: 12px; z-index: 10; width: 280px;
            font-size: 0.9em; font-weight: 400; line-height: 1.4;
            box-shadow: 0 4px 10px rgba(0,0,0,0.3); transition: opacity 0.2s, visibility 0.2s;
        }
        .promo-info-icon:hover .tooltip { visibility: visible; opacity: 1; }
        .promo-code-display { display: flex; align-items: stretch; justify-content: center; gap: 2px; }
        .promo-code-value {
            font-size: 1.5em; font-weight: 700; color: var(--tg-theme-button-color); letter-spacing: 2px;
            background-color: rgba(0,0,0,0.2); padding: 12px 18px;
            border-radius: 10px 0 0 10px; flex-grow: 1; text-align: center;
        }
        .copy-btn {
            padding: 0 18px; color: var(--tg-theme-button-text-color);
            background-color: var(--tg-theme-button-color); border: none; border-radius: 0 10px 10px 0; cursor: pointer;
            transition: all 0.2s ease; display: flex; align-items: center; justify-content: center;
        }
        .copy-btn:active { transform: scale(0.95); }
        .copy-btn .icon { width: 22px; height: 22px; }
        .client-id-card { display: flex; justify-content: space-between; align-items: center; }
        .client-id-label { font-weight: 500; color: var(--tg-theme-hint-color); }
        .client-id-value { font-size: 1.3em; font-weight: 700; }
        .section-title { font-size: 1.4em; font-weight: 700; margin-bottom: 16px; }
        .history-list, .invoices-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; }
        .history-item, .invoice-item {
            display: flex; align-items: center; padding: 14px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08); transition: background-color 0.2s ease; border-radius: 12px;
        }
        .history-item:last-child, .invoice-item:last-child { border-bottom: none; }
        .history-item:hover, .invoice-item:hover { background-color: rgba(255,255,255,0.05); }
        .history-icon { margin-right: 16px; width: 42px; height: 42px; display: flex; align-items: center; justify-content: center; border-radius: 50%; }
        .history-icon svg { width: 22px; height: 22px; }
        .icon-bonus-accrual { background-color: rgba(76, 175, 80, 0.15); color: var(--brand-green); }
        .icon-bonus-deduction { background-color: rgba(244, 67, 54, 0.15); color: var(--brand-red); }
        .icon-debt-accrual { background-color: rgba(244, 67, 54, 0.15); color: var(--brand-red); }
        .icon-debt-payment { background-color: rgba(76, 175, 80, 0.15); color: var(--brand-green); }
        .icon-referral { background-color: rgba(33, 150, 243, 0.15); color: var(--brand-blue); }
        .history-details { flex-grow: 1; }
        .history-description { font-size: 1em; font-weight: 600; }
        .history-date { font-size: 0.8em; color: var(--tg-theme-hint-color); margin-top: 4px; }
        .history-amount { font-size: 1.1em; font-weight: 700; white-space: nowrap; }
        .history-amount.positive { color: var(--brand-green); }
        .history-amount.negative { color: var(--brand-red); }
        .history-amount.referral { color: var(--brand-blue); }
        .invoice-item { cursor: pointer; }
        .invoice-details { flex-grow: 1; }
        .invoice-description, .invoice-date { margin-left: 16px; }
        .invoice-amount { font-size: 1.1em; font-weight: 700; color: var(--tg-theme-button-color); }
        .no-data { text-align: center; color: var(--tg-theme-hint-color); padding: 3rem 0; font-size: 1.1em; }
        .business-card-item { margin-bottom: 20px; }
        .business-card-label { font-weight: 500; color: var(--tg-theme-hint-color); margin-bottom: 8px; font-size: 0.9em; }
        .business-card-value { font-size: 1.1em; font-weight: 600; }
        .business-card-value a { color: var(--tg-theme-button-color); text-decoration: none; word-break: break-all; transition: opacity 0.2s; }
        .business-card-value a:hover { opacity: 0.8; }
        .business-card-phone-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; }
        .business-card-phone-item a {
            display: inline-flex; align-items: center; gap: 12px; color: var(--tg-theme-text-color);
            text-decoration: none; background-color: rgba(255,255,255,0.08); padding: 12px 16px;
            border-radius: 12px; transition: background-color 0.2s;
        }
        .business-card-phone-item a:hover { background-color: rgba(255,255,255,0.12); }
        .modal {
            display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%;
            background-color: rgba(0,0,0,0.7); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
            align-items: flex-end; justify-content: center;
        }
        .modal-content {
            background-color: var(--tg-theme-secondary-bg-color); width: 100%;
            border-top-left-radius: var(--border-radius-l); border-top-right-radius: var(--border-radius-l);
            box-shadow: 0 -5px 25px rgba(0,0,0,0.3); padding: var(--padding-m); padding-top: 40px; position: relative;
            max-height: 90vh; overflow-y: auto; animation: slideUp 0.3s ease-out;
        }
        .modal-close {
            position: absolute; top: 12px; left: 50%; transform: translateX(-50%);
            width: 40px; height: 5px; background-color: var(--tg-theme-hint-color);
            border-radius: 3px; cursor: pointer;
        }
        .modal-title { font-size: 1.5em; font-weight: 700; margin-bottom: 20px; text-align: center; color: var(--tg-theme-button-color); }
        .invoice-detail-list { list-style: none; padding: 0; margin: 0; }
        .invoice-detail-item {
            display: grid; grid-template-columns: 1fr auto; gap: 4px 16px; padding: 12px 0; border-bottom: 1px dashed rgba(255,255,255,0.1);
        }
        .item-name { font-weight: 500; grid-column: 1; }
        .item-qty-price { font-size: 0.9em; color: var(--tg-theme-hint-color); grid-column: 1; }
        .item-total { font-weight: 700; grid-column: 2; grid-row: 1 / 3; align-self: center; color: var(--tg-theme-button-color); }
        .invoice-total-section {
            padding-top: var(--padding-m); border-top: 1px solid rgba(255,255,255,0.2); margin-top: var(--padding-m);
            display: flex; flex-direction: column; gap: 8px; font-size: 1.1em;
        }
        .total-row { display: flex; justify-content: space-between; }
        .total-row.final { font-weight: 700; font-size: 1.2em; margin-top: 8px; }
        .total-row .deduction { color: var(--brand-red); }
        #promoCodeModal .modal-content { align-items: center; text-align: center; padding: 40px 24px 24px; }
        #promoCodeModal h2 { margin-bottom: 12px; }
        #promoCodeModal p { color: var(--tg-theme-hint-color); margin-bottom: 20px; max-width: 300px; }
        #promoCodeModal input {
            width: 100%; padding: 16px; margin-bottom: 16px; font-size: 1.2em;
            background-color: var(--tg-theme-bg-color); border: 1px solid rgba(255,255,255,0.1);
            border-radius: var(--border-radius-m); color: var(--tg-theme-text-color);
            text-align: center; letter-spacing: 2px;
        }
        #promoCodeModal .promo-modal-actions { display: flex; gap: 1rem; width: 100%; }
        #promoCodeModal button {
            flex-grow: 1; padding: 16px; font-size: 1em; font-weight: 700; border: none;
            border-radius: var(--border-radius-m); cursor: pointer; transition: all 0.2s;
        }
        .btn-apply-promo { background-color: var(--tg-theme-button-color); color: var(--tg-theme-button-text-color); }
        .btn-skip-promo { background-color: var(--tg-theme-secondary-bg-color); color: var(--tg-theme-text-color); }
        #promoStatus { margin-top: 1rem; font-weight: 500; min-height: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <header class="header">
            <div class="logo">BONUS<span>.</span></div>
            <p id="greeting" class="welcome-text">Добро пожаловать!</p>
        </header>
        <nav class="nav-buttons">
            <button class="nav-btn active" data-target="dashboard-section">Главная</button>
            <button class="nav-btn" data-target="invoices-section">Накладные</button>
            <button class="nav-btn" data-target="business-card-section">Визитка</button>
        </nav>
        <div id="dashboard-section" class="content-section active">
            <section class="financial-summary-card">
                <div class="main-balance-section">
                    <p class="card-label">Ваши бонусы</p>
                    <p class="bonus-amount" id="bonus-amount-display">0.00</p>
                </div>
                <div class="sub-balances-grid">
                    <div class="sub-balance-item">
                        <p class="card-label">Ваш долг</p>
                        <p class="amount debt">{{ "%.2f"|format(user.debts|float) }}</p>
                    </div>
                    <div class="sub-balance-item">
                        <p class="card-label">Бонусы с друзей</p>
                        <p class="amount referral">{{ "%.2f"|format(user.referral_bonuses|float) }}</p>
                    </div>
                </div>
            </section>
            <section class="section-card promo-card animated-card">
                <p class="card-label">
                    Ваш промокод для друзей
                    <span class="promo-info-icon">
                        <svg xmlns="http://www.w3.org/2000/svg" height="20px" viewBox="0 0 24 24" width="20px" fill="currentColor"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg>
                        <span class="tooltip">Передай этот промокод другу. При активации он получит <strong>{{ "%.0f"|format(bonus_settings.referral_promo_bonus|float) }}</strong> бонусов, а ты получишь <strong>{{ "%.1f"|format(bonus_settings.referrer_first_purchase_percentage|float) }}%</strong> на свой счет "от друзей" с его первой покупки.</span>
                    </span>
                </p>
                <div class="promo-code-display">
                    <span class="promo-code-value" id="userPromoCode">{{ user.referral_code }}</span>
                    <button class="copy-btn" onclick="copyPromoCode(this)">
                        <span id="copy-icon-wrapper">
                            <svg class="icon" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="currentColor"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>
                        </span>
                    </button>
                </div>
            </section>
            <section class="section-card client-id-card animated-card">
                <p class="client-id-label">Ваш ID клиента</p>
                <p class="client-id-value">{{ user.id }}</p>
            </section>
            <section class="section-card animated-card">
                <h2 class="section-title">История операций</h2>
                {% if user.combined_history %}
                    <ul class="history-list">
                        {% for item in user.combined_history[:10] %}
                            <li class="history-item">
                                {% if item.transaction_type == 'bonus' %}
                                    <div class="history-icon {{ 'icon-bonus-accrual' if item.type == 'accrual' else 'icon-bonus-deduction' }}">
                                        <svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24" fill="currentColor"><g><rect fill="none" height="24" width="24"/></g><g><path d="M12,2C6.48,2,2,6.48,2,12s4.48,10,10,10s10-4.48,10-10S17.52,2,12,2z M17,13h-4v4h-2v-4H7v-2h4V7h2v4h4V13z"/></g></svg>
                                    </div>
                                    <div class="history-details">
                                        <span class="history-description">{{ item.description }}</span>
                                        <span class="history-date">{{ item.date_str }}</span>
                                    </div>
                                    <span class="history-amount {{ 'positive' if item.type == 'accrual' else 'negative' }}">
                                        {{ '+' if item.type == 'accrual' else '-' }}{{ "%.2f"|format(item.amount|float) }}
                                    </span>
                                {% elif item.transaction_type == 'debt' %}
                                    <div class="history-icon {{ 'icon-debt-payment' if item.type == 'payment' else 'icon-debt-accrual' }}">
                                       <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm-1-5h2v2h-2zm0-8h2v6h-2z"/></svg>
                                    </div>
                                    <div class="history-details">
                                        <span class="history-description">{{ item.description }}</span>
                                        <span class="history-date">{{ item.date_str }}</span>
                                    </div>
                                    <span class="history-amount {{ 'positive' if item.type == 'payment' else 'negative' }}">
                                        {{ '-' if item.type == 'payment' else '+' }}{{ "%.2f"|format(item.amount|float) }}
                                    </span>
                                {% elif item.transaction_type == 'referral' %}
                                     <div class="history-icon icon-referral">
                                         <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/></svg>
                                     </div>
                                    <div class="history-details">
                                        <span class="history-description">{{ item.description }}</span>
                                        <span class="history-date">{{ item.date_str }}</span>
                                    </div>
                                    <span class="history-amount referral">
                                        {{ '+' if item.type == 'accrual' else '-' }}{{ "%.2f"|format(item.amount|float) }}
                                    </span>
                                {% endif %}
                            </li>
                        {% endfor %}
                    </ul>
                {% else %}
                    <p class="no-data">Операций пока не было.</p>
                {% endif %}
            </section>
        </div>
        <div id="invoices-section" class="content-section">
            <section class="section-card">
                <h2 class="section-title">Мои накладные</h2>
                {% if user.invoices %}
                    <ul class="invoices-list">
                        {% for invoice in user.invoices|sort(attribute='date', reverse=true) %}
                            <li class="invoice-item" onclick='openInvoiceDetailModal({{ invoice|tojson }})'>
                                <div class="history-icon" style="background-color: rgba(255, 193, 7, 0.15); color: var(--tg-theme-button-color);">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"/></svg>
                                </div>
                                <div class="invoice-details">
                                    <span class="invoice-description">Накладная #{{ invoice.invoice_id }}</span>
                                    <span class="invoice-date">{{ invoice.date_str }}</span>
                                </div>
                                <span class="invoice-amount">{{ "%.2f"|format(invoice.total_amount|float) }}</span>
                            </li>
                        {% endfor %}
                    </ul>
                {% else %}
                    <p class="no-data">Накладных пока нет.</p>
                {% endif %}
            </section>
        </div>
        <div id="business-card-section" class="content-section">
            <section class="section-card">
                <h2 class="section-title">Визитка организации</h2>
                {% if org_details and (org_details.name or org_details.phone_numbers) %}
                    {% if org_details.name %}
                    <div class="business-card-item">
                        <div class="business-card-label">Название организации</div>
                        <div class="business-card-value">{{ org_details.name }}</div>
                    </div>
                    {% endif %}
                    {% if org_details.phone_numbers %}
                    <div class="business-card-item">
                        <div class="business-card-label">Номера телефонов</div>
                        <ul class="business-card-phone-list">
                            {% for phone in org_details.phone_numbers %}
                                <li class="business-card-phone-item">
                                    <a href="tel:{{ phone.replace(' ', '').replace('-', '') }}">
                                        <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="currentColor"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M6.54 5c.06.89.21 1.76.45 2.59l-1.2 1.2c-.41-1.2-.67-2.47-.76-3.79h1.51m10.92 0h1.51c-.09 1.32-.35 2.59-.76 3.79l-1.2-1.2c.24-.83.39-1.7.45-2.59M7.5 3H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.49c0-.55-.45-1-1-1-1.24 0-2.45-.2-3.57-.57-.1-.04-.21-.05-.31-.05-.26 0-.51.1-.71.29l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.2c.28-.28.36-.67.25-1.02C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1z"/></svg>
                                        {{ phone }}
                                    </a>
                                </li>
                            {% endfor %}
                        </ul>
                    </div>
                    {% endif %}
                    {% if org_details.address %}
                    <div class="business-card-item">
                        <div class="business-card-label">Адрес</div>
                        <div class="business-card-value">{{ org_details.address }}</div>
                    </div>
                    {% endif %}
                    {% if org_details.whatsapp_link %}
                    <div class="business-card-item">
                        <div class="business-card-label">WhatsApp</div>
                        <div class="business-card-value">
                            <a href="{{ org_details.whatsapp_link }}" target="_blank">Написать в WhatsApp</a>
                        </div>
                    </div>
                    {% endif %}
                    {% if org_details.telegram_link %}
                    <div class="business-card-item">
                        <div class="business-card-label">Telegram</div>
                        <div class="business-card-value">
                           <a href="{{ org_details.telegram_link }}" target="_blank">Написать в Telegram</a>
                        </div>
                    </div>
                    {% endif %}
                {% else %}
                    <p class="no-data">Данные организации не указаны.</p>
                {% endif %}
            </section>
        </div>
    </div>
    <div id="invoiceDetailModal" class="modal">
        <div class="modal-content">
            <div class="modal-close" onclick="closeModal('invoiceDetailModal')"></div>
            <h2 id="invoiceDetailTitle" class="modal-title"></h2>
            <ul id="invoiceDetailList" class="invoice-detail-list"></ul>
            <div id="invoiceTotalSection" class="invoice-total-section"></div>
        </div>
    </div>
    {% if is_first_visit %}
    <div id="promoCodeModal" class="modal" style="display: flex; align-items: center;">
        <div class="modal-content">
            <h2 class="modal-title">Есть промокод?</h2>
            <p>Если у вас есть промокод от друга, введите его, чтобы получить бонус.</p>
            <input type="text" id="promoCodeInput" placeholder="PROMO123">
            <div id="promoStatus"></div>
            <div class="promo-modal-actions">
                <button class="btn-skip-promo" onclick="submitPromoCode(false)">Нет, спасибо</button>
                <button class="btn-apply-promo" onclick="submitPromoCode(true)">Применить</button>
            </div>
        </div>
    </div>
    {% endif %}
    <script>
        const tg = window.Telegram.WebApp;
        const currentUserId = '{{ user.id }}';
        const initialBonusAmount = parseFloat('{{ user.bonuses|float }}');

        function applyTheme(themeParams) {
            if (!themeParams) return;
            const root = document.documentElement.style;
            root.setProperty('--tg-bg-color', themeParams.bg_color || '#181818');
            root.setProperty('--tg-text-color', themeParams.text_color || '#ffffff');
            root.setProperty('--tg-hint-color', themeParams.hint_color || '#aaaaaa');
            root.setProperty('--tg-button-color', themeParams.button_color || '#FFC107');
            root.setProperty('--tg-button-text-color', themeParams.button_text_color || '#000000');
            root.setProperty('--tg-secondary-bg-color', themeParams.secondary_bg_color || '#2c2c2e');
        }
        
        function setupTelegram() {
             if (!tg || !tg.initData) {
                 console.error("Telegram WebApp script not loaded or initData is missing.");
                 document.body.style.visibility = 'visible';
                 applyTheme({});
                 return;
             }
             
            tg.ready();
            tg.expand();
            tg.setHeaderColor(tg.themeParams.secondary_bg_color || '#2c2c2e');

            applyTheme(tg.themeParams);
            tg.onEvent('themeChanged', () => {
                applyTheme(tg.themeParams);
                tg.setHeaderColor(tg.themeParams.secondary_bg_color || '#2c2c2e');
            });

             const urlParams = new URLSearchParams(window.location.search);
             const userIdForTest = urlParams.get('user_id_for_test');

             if (!userIdForTest) {
                fetch('/verify', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                    body: JSON.stringify({ initData: tg.initData }),
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'ok' && data.verified && data.user_id) {
                        window.location.replace('/?user_id_for_test=' + data.user_id);
                    } else {
                        console.warn('Backend verification failed:', data.message);
                        document.body.style.visibility = 'visible';
                    }
                })
                .catch(error => {
                    console.error('Error sending initData for verification:', error);
                    document.body.style.visibility = 'visible';
                });
             } else {
                 document.body.style.visibility = 'visible';
             }

             const user = tg.initDataUnsafe?.user;
             const greetingElement = document.getElementById('greeting');
             if (user) {
                 const name = user.first_name || user.username || 'Гость';
                 greetingElement.textContent = `Привет, ${name}! 👋`;
             } else {
                greetingElement.textContent = `Привет, {{ user.first_name or 'Гость' }}! 👋`;
             }
         }

        function showSection(sectionId) {
            document.querySelectorAll('.content-section').forEach(section => section.classList.remove('active'));
            document.getElementById(sectionId).classList.add('active');
            document.querySelectorAll('.nav-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelector(`.nav-btn[data-target="${sectionId}"]`).classList.add('active');
        }

        function openModal(modalId) { document.getElementById(modalId).style.display = 'flex'; }
        function closeModal(modalId) { document.getElementById(modalId).style.display = 'none'; }

        function openInvoiceDetailModal(invoiceData) {
            document.getElementById('invoiceDetailTitle').textContent = `Накладная #${invoiceData.invoice_id}`;
            const invoiceDetailList = document.getElementById('invoiceDetailList');
            invoiceDetailList.innerHTML = '';
            invoiceData.items.forEach(item => {
                const li = document.createElement('li');
                li.className = 'invoice-detail-item';
                li.innerHTML = `<span class="item-name">${item.product_name}</span><span class="item-qty-price">${item.quantity} x ${parseFloat(item.unit_price).toFixed(2)}</span><span class="item-total">${parseFloat(item.item_total).toFixed(2)}</span>`;
                invoiceDetailList.appendChild(li);
            });
            
            const totalSection = document.getElementById('invoiceTotalSection');
            const totalAmount = parseFloat(invoiceData.total_amount);
            const bonusesDeducted = parseFloat(invoiceData.bonuses_deducted || 0);
            const bonusSource = invoiceData.bonus_source_used;
            let bonusSourceText = '';
            if (bonusSource === 'referral') {
                bonusSourceText = ' (от друзей)';
            } else if (bonusSource === 'main') {
                bonusSourceText = ' (основных)';
            }
            
            let html = `<div class="total-row"><span>Сумма</span> <span>${totalAmount.toFixed(2)}</span></div>`;
            if (bonusesDeducted > 0) {
                html += `<div class="total-row"><span>Списано бонусов${bonusSourceText}</span> <span class="deduction">- ${bonusesDeducted.toFixed(2)}</span></div>`;
                html += `<div class="total-row final"><span>К оплате</span> <span>${(totalAmount - bonusesDeducted).toFixed(2)}</span></div>`;
            } else {
                html += `<div class="total-row final"><span>К оплате</span> <span>${totalAmount.toFixed(2)}</span></div>`;
            }
            totalSection.innerHTML = html;
            
            openModal('invoiceDetailModal');
        }
        
        function copyPromoCode(button) {
            const promoCode = document.getElementById('userPromoCode').textContent;
            navigator.clipboard.writeText(promoCode).then(() => {
                const iconWrapper = document.getElementById('copy-icon-wrapper');
                const originalIcon = iconWrapper.innerHTML;
                iconWrapper.innerHTML = `<svg class="icon" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="var(--brand-green)"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/></svg>`;
                setTimeout(() => { iconWrapper.innerHTML = originalIcon; }, 2000);
            }).catch(err => {
                console.error('Failed to copy text: ', err);
            });
        }
        
        function animateValue(obj, start, end, duration) {
          let startTimestamp = null;
          const step = (timestamp) => {
            if (!startTimestamp) startTimestamp = timestamp;
            const progress = Math.min((timestamp - startTimestamp) / duration, 1);
            obj.innerHTML = parseFloat(progress * (end - start) + start).toFixed(2);
            if (progress < 1) {
              window.requestAnimationFrame(step);
            }
          };
          window.requestAnimationFrame(step);
        }

        async function submitPromoCode(withCode) {
            const promoCode = withCode ? document.getElementById('promoCodeInput').value.trim() : null;
            const statusEl = document.getElementById('promoStatus');
            statusEl.style.color = 'var(--tg-theme-hint-color)';
            statusEl.textContent = 'Проверяем...';
            
            try {
                const response = await fetch('/submit_referral', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ user_id: currentUserId, referral_code: promoCode })
                });
                const result = await response.json();
                if (response.ok) {
                    statusEl.style.color = 'var(--brand-green)';
                    statusEl.textContent = result.message;
                    setTimeout(() => { closeModal('promoCodeModal'); location.reload(); }, 1500);
                } else {
                    throw new Error(result.message || 'Произошла ошибка');
                }
            } catch (error) {
                statusEl.style.color = 'var(--brand-red)';
                statusEl.textContent = error.message;
            }
        }

        document.addEventListener('DOMContentLoaded', () => {
            document.querySelectorAll('.nav-btn').forEach(button => {
                button.addEventListener('click', () => showSection(button.dataset.target));
            });
            showSection('dashboard-section'); 
            
            const bonusAmountEl = document.getElementById('bonus-amount-display');
            if (bonusAmountEl) {
                animateValue(bonusAmountEl, 0, initialBonusAmount, 1000);
            }
        });

        if (window.Telegram && window.Telegram.WebApp) {
            setupTelegram();
        } else {
             window.addEventListener('load', setupTelegram, {once: true});
             setTimeout(() => {
                 if (document.body.style.visibility !== 'visible') {
                      document.body.style.visibility = 'visible';
                      applyTheme({});
                  }
             }, 3000);
        }
    </script>
</body>
</html>
"""

ADMIN_TEMPLATE = """
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bonus Admin</title>
    <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=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --admin-bg: #f8f9fa; --admin-text: #212529; --admin-card-bg: #ffffff;
            --admin-border: #dee2e6; --admin-shadow: rgba(0, 0, 0, 0.05);
            --admin-primary: #FFC107; --admin-primary-dark: #e0a800; --admin-secondary: #6c757d;
            --admin-success: #198754; --admin-danger: #dc3545; --admin-info: #0dcaf0;
            --border-radius: 12px; --padding: 1.5rem; --font-family: 'Inter', sans-serif;
        }
        body { font-family: var(--font-family); background-color: var(--admin-bg); color: var(--admin-text); margin: 0; padding: var(--padding); line-height: 1.6; }
        .container { max-width: 1200px; margin: 0 auto; }
        h1 { text-align: center; color: var(--admin-secondary); margin-bottom: var(--padding); font-weight: 600; }
        .summary-bar { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: var(--padding); margin-bottom: var(--padding); }
        .summary-card { background: var(--admin-card-bg); padding: var(--padding); border-radius: var(--border-radius); box-shadow: 0 4px 15px var(--admin-shadow); border: 1px solid var(--admin-border); text-align: center; }
        .summary-card .value { font-size: 2em; font-weight: 700; }
        .summary-card .label { font-size: 0.9em; color: var(--admin-secondary); margin-top: 0.5rem; }
        .summary-card .value.bonus { color: var(--admin-primary-dark); }
        .summary-card .value.debt { color: var(--admin-danger); }
        .summary-card .value.referral { color: var(--admin-info); }
        .controls-bar { display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; background: var(--admin-card-bg); padding: var(--padding); border-radius: var(--border-radius); box-shadow: 0 4px 15px var(--admin-shadow); border: 1px solid var(--admin-border); margin-bottom: var(--padding); }
        .controls-bar input[type="text"] { flex-grow: 1; padding: 12px 15px; font-size: 1.1em; border-radius: 8px; border: 1px solid var(--admin-border); box-sizing: border-box; min-width: 250px; }
        .btn { padding: 12px 20px; font-size: 1em; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: background-color 0.2s ease; }
        .btn-primary { background-color: var(--admin-primary); color: #000; }
        .btn-primary:hover { background-color: var(--admin-primary-dark); }
        .btn-secondary { background-color: var(--admin-secondary); color: white; }
        .btn-secondary:hover { background-color: #5a6268; }
        .btn-delete { background-color: var(--admin-danger); color: white; }
        .btn-delete:hover { background-color: #c82333; }
        .user-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: var(--padding); margin-top: var(--padding); }
        .user-card { background-color: var(--admin-card-bg); border-radius: var(--border-radius); padding: var(--padding); box-shadow: 0 4px 15px var(--admin-shadow); border: 1px solid var(--admin-border); display: flex; flex-direction: column; transition: transform 0.2s ease, box-shadow 0.2s ease; }
        .user-card:hover { transform: translateY(-5px); box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08); }
        .user-info { display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem; }
        .user-info img { width: 60px; height: 60px; border-radius: 50%; object-fit: cover; border: 3px solid var(--admin-border); background-color: #eee; }
        .user-details .name { font-weight: 600; font-size: 1.2em; }
        .user-details .username { color: var(--admin-secondary); font-size: 0.9em; }
        .referral-info { font-size: 0.85em; color: var(--admin-secondary); margin-top: 8px; padding: 8px; background-color: #f8f9fa; border-radius: 8px; border: 1px solid var(--admin-border); }
        .referral-info .ref-by { color: var(--admin-success); }
        .referral-info .ref-count { color: var(--admin-info); font-weight: 600; }
        .user-balances { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; text-align: center; margin-bottom: 1rem; margin-top: 1rem; }
        .user-balances .label { font-size: 0.9em; color: var(--admin-secondary); }
        .user-balances .amount { font-size: 1.5em; font-weight: 700; }
        .user-balances .amount.bonus { color: var(--admin-primary-dark); }
        .user-balances .amount.debt { color: var(--admin-danger); }
        .user-balances .amount.referral { color: var(--admin-info); }
        .user-actions { margin-top: auto; display: flex; flex-direction: column; gap: 0.5rem; }
        .btn-manage { display: block; width: 100%; padding: 10px; background-color: var(--admin-primary); color: #000; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: background-color 0.2s; }
        .btn-manage:hover { background-color: var(--admin-primary-dark); }
        .no-users { text-align: center; color: var(--admin-secondary); margin-top: 2rem; font-size: 1.1em; }
        .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.5); backdrop-filter: blur(5px); }
        .modal-content { background-color: var(--admin-bg); margin: 5% auto; padding: var(--padding); border: 1px solid var(--admin-border); width: 90%; max-width: 700px; border-radius: var(--border-radius); position: relative; box-shadow: 0 8px 30px rgba(0,0,0,0.15); }
        .modal-close { color: #aaa; position: absolute; top: 15px; right: 25px; font-size: 28px; font-weight: bold; cursor: pointer; }
        .modal-header { padding-bottom: 1rem; margin-bottom: 1.5rem; border-bottom: 1px solid var(--admin-border); }
        .modal-header h2 { margin: 0; font-size: 1.5rem; }
        .modal-header .username { font-size: 1rem; color: var(--admin-secondary); }
        .form-section { border: 1px solid var(--admin-border); border-radius: 8px; padding: 1rem; margin-bottom: 1.5rem; }
        .form-section h3 { margin-top: 0; margin-bottom: 1rem; font-size: 1.1em; }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; align-items: flex-end; }
        .form-group { display: flex; flex-direction: column; }
        .form-group label { margin-bottom: 0.5rem; font-weight: 500; font-size: 0.9em; }
        .form-group input, .form-group textarea { padding: 10px; font-size: 1rem; border: 1px solid var(--admin-border); border-radius: 8px; width: 100%; box-sizing: border-box; }
        .history-container { margin-top: 1.5rem; }
        .history-container h3 { font-size: 1.2rem; margin-bottom: 1rem; }
        .history-list { list-style: none; padding: 0; max-height: 200px; overflow-y: auto; border: 1px solid var(--admin-border); border-radius: 8px; }
        .history-item { display: flex; justify-content: space-between; padding: 8px 12px; border-bottom: 1px solid var(--admin-border); }
        .history-item:last-child { border-bottom: none; }
        .history-item .desc { font-size: 0.9em; }
        .history-item .date { font-size: 0.8em; color: var(--admin-secondary); }
        .history-item .amount.bonus-accrual { color: var(--admin-success); font-weight: 600; }
        .history-item .amount.bonus-deduction { color: var(--admin-danger); font-weight: 600; }
        .history-item .amount.debt-accrual { color: var(--admin-danger); font-weight: 600; }
        .history-item .amount.debt-payment { color: var(--admin-success); font-weight: 600; }
        .history-item .amount.referral-accrual { color: var(--admin-info); font-weight: 600; }
        .history-item .amount.referral-deduction { color: var(--admin-danger); font-weight: 600; }
        .modal-footer { margin-top: 1.5rem; display: flex; justify-content: flex-end; align-items: center; gap: 1rem;}
        .modal-footer button { padding: 12px 25px; font-size: 1.1em; border-radius: 8px; border: none; font-weight: 600; cursor: pointer; }
        .btn-submit { background-color: var(--admin-success); color: white; }
        .status-message { text-align: center; font-weight: 500; flex-grow: 1; text-align: left; }
        .tab-buttons { display: flex; margin-bottom: 1rem; border-bottom: 1px solid var(--admin-border); }
        .tab-btn { padding: 10px 15px; border: none; background-color: transparent; color: var(--admin-secondary); font-weight: 600; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.2s ease; }
        .tab-btn.active { color: var(--admin-primary-dark); border-bottom-color: var(--admin-primary); }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        #newInvoiceItemsList { display: flex; flex-direction: column; gap: 1rem; margin-bottom: 1rem; }
        .invoice-item-row { display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-end; padding-bottom: 10px; border-bottom: 1px solid var(--admin-border); }
        .invoice-item-row .form-group { margin-bottom: 0; }
        .form-group.item-name { flex: 3 1 200px; }
        .form-group.item-qty, .form-group.item-price { flex: 1 1 80px; }
        .item-total-group { flex: 1 1 90px; text-align: right; padding-bottom: 10px; }
        .item-total-group .item-total-display { font-weight: 700; font-size: 1.1em; }
        .invoice-item-row .action-btn { align-self: center; margin-bottom: 5px; background: none; border: none; color: var(--admin-danger); cursor: pointer; font-size: 1.2em; }
        .invoice-items-footer { display: flex; justify-content: space-between; align-items: center; margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--admin-border); }
        .invoice-items-total { font-size: 1.2em; font-weight: 700; }
        .invoice-section-summary { padding: 1rem; background-color: #e9ecef; border-radius: 8px; margin-top: 1rem; font-weight: 600; font-size: 1.1em; text-align: right; }
        .invoice-section-summary span { color: var(--admin-success); }
        .invoice-list-admin { list-style: none; padding: 0; max-height: 200px; overflow-y: auto; border: 1px solid var(--admin-border); border-radius: 8px; }
        .invoice-list-admin li { padding: 8px 12px; border-bottom: 1px solid var(--admin-border); display: flex; justify-content: space-between; align-items: center; }
        .invoice-list-admin li:last-child { border-bottom: none; }
        .invoice-list-admin .invoice-info { font-size: 0.9em; }
        .invoice-list-admin .invoice-amount { font-weight: 700; color: var(--admin-primary-dark); }
        .invoice-list-admin .view-btn { background: none; border: none; color: var(--admin-secondary); cursor: pointer; font-size: 0.9em; margin-left: 10px; }
        .invoice-list-admin .delete-btn { background: none; border: none; color: var(--admin-danger); cursor: pointer; font-size: 0.9em; margin-left: 5px; }
        .details-form { display: flex; flex-direction: column; gap: 1rem; }
        .details-form textarea { min-height: 80px; resize: vertical; }
        .form-group-horizontal { display: flex; align-items: center; gap: 10px; }
        .form-group-horizontal input { flex-grow: 1; }
        .form-group-horizontal span { font-weight: 500; }
        .invoice-detail-list { list-style: none; padding: 0; }
        .invoice-detail-item { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px dashed #ccc; }
        .invoice-detail-item:last-child { border-bottom: none; }
        .item-name { flex-basis: 60%; }
        .item-qty-price { flex-basis: 20%; text-align: right; color: #6c757d; }
        .item-total { flex-basis: 20%; text-align: right; font-weight: bold; }
        .invoice-total-display { margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #dee2e6; display: flex; flex-direction: column; gap: 0.5rem; font-size: 1.1em; }
        .invoice-total-display div { display: flex; justify-content: space-between; }
        .bonus-source-selector { display: flex; gap: 1rem; margin-bottom: 1rem; align-items: center; flex-wrap: wrap; }
        .bonus-source-selector label { display: flex; align-items: center; gap: 0.5rem; cursor: pointer; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Панель администратора Bonus</h1>
        <div class="summary-bar">
            <div class="summary-card">
                <div class="value">{{ summary.total_users }}</div>
                <div class="label">Всего клиентов</div>
            </div>
            <div class="summary-card">
                <div class="value bonus">{{ "%.2f"|format(summary.total_bonuses|float) }}</div>
                <div class="label">Всего бонусов</div>
            </div>
            <div class="summary-card">
                <div class="value debt">{{ "%.2f"|format(summary.total_debts|float) }}</div>
                <div class="label">Всего долгов</div>
             </div>
             <div class="summary-card">
                <div class="value referral">{{ "%.2f"|format(summary.total_referral_bonuses|float) }}</div>
                <div class="label">Бонусов с друзей</div>
            </div>
        </div>
        <div class="controls-bar">
            <input type="text" id="searchInput" onkeyup="searchUsers()" placeholder="Поиск по имени, ID, username, номеру...">
            <button class="btn btn-primary" onclick="openAddClientModal()">Добавить клиента</button>
            <button class="btn btn-primary" onclick="openOrgSettingsModal()">Настройки организации</button>
            <button class="btn btn-primary" onclick="openBonusSettingsModal()">Настройка бонусов</button>
        </div>
        {% if users %}
            <div class="user-grid" id="userGrid">
                {% for user in users|sort(attribute='visited_at', reverse=true) %}
                    <div class="user-card" data-user-id="{{ user.id }}" data-search-term="{{ user.first_name|lower }} {{ user.last_name|lower }} {{ user.username|lower }} {{ user.id }} {{ user.phone_number|lower if user.phone_number }}">
                        <div class="user-info">
                            <img src="{{ user.photo_url if user.photo_url else 'data:image/svg+xml;charset=UTF-8,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 100 100%27%3e%3crect width=%27100%27 height=%27100%27 fill=%27%23e9ecef%27/%3e%3ctext x=%2750%25%27 y=%2755%25%27 dominant-baseline=%27middle%27 text-anchor=%27middle%27 font-size=%2745%27 font-family=%27sans-serif%27 fill=%27%23adb5bd%27%3e?%3c/text%3e%3c/svg%3e' }}" alt="User Avatar">
                            <div class="user-details">
                                <div class="name">{{ user.first_name or '' }} {{ user.last_name or '' }}</div>
                                <div class="username">@{{ user.username if user.username else user.phone_number }} | ID: {{ user.id }}</div>
                            </div>
                        </div>
                        <div class="referral-info">
                            {% if user.referrer_info %}
                                <div class="ref-by">Приведен(а): <strong>{{ user.referrer_info }}</strong></div>
                            {% endif %}
                            <div class="ref-count">Привел(а) клиентов: <strong>{{ user.referrals_count }}</strong></div>
                        </div>
                        <div class="user-balances">
                            <div>
                               <div class="label">Бонусы</div>
                               <div class="amount bonus">{{ "%.2f"|format(user.bonuses|float) }}</div>
                            </div>
                            <div>
                               <div class="label">Долг</div>
                               <div class="amount debt">{{ "%.2f"|format(user.debts|float if user.debts else 0) }}</div>
                            </div>
                            <div>
                               <div class="label">От друзей</div>
                               <div class="amount referral">{{ "%.2f"|format(user.referral_bonuses|float if user.referral_bonuses else 0) }}</div>
                            </div>
                        </div>
                        <div class="user-actions">
                            <button class="btn-manage" onclick='openTransactionModal({{ user|tojson }})'>Управление счетом</button>
                            {% if user.telegram_id == None %}
                            <button class="btn btn-delete" onclick='deleteClient("{{ user.id }}")'>Удалить клиента</button>
                            {% endif %}
                        </div>
                    </div>
                {% endfor %}
            </div>
        {% else %}
            <p class="no-users">Пользователей пока нет.</p>
        {% endif %}
    </div>
    <div id="transactionModal" class="modal">
      <div class="modal-content">
        <span class="modal-close" onclick="closeModal('transactionModal')">×</span>
        <div class="modal-header">
            <h2 id="modalUserName"></h2>
            <div id="modalUserUsername" class="username"></div>
        </div>
        <input type="hidden" id="modalUserId">
        <div class="tab-buttons">
            <button class="tab-btn active" data-tab="bonus-debt-tab">Счета</button>
            <button class="tab-btn" data-tab="invoice-tab">Накладные</button>
            <button class="tab-btn" data-tab="referral-history-tab">История</button>
        </div>
        <div id="bonus-debt-tab" class="tab-content active">
            <div class="form-section">
                <h3>Основные бонусы</h3>
                <div class="form-row">
                    <div class="form-group">
                        <label for="accrueAmount">Начислить</label>
                        <input type="number" id="accrueAmount" placeholder="0" oninput="updateCalculations()">
                    </div>
                    <div class="form-group">
                        <label for="deductAmount">Списать</label>
                        <input type="number" id="deductAmount" placeholder="0" oninput="updateCalculations()">
                    </div>
                </div>
            </div>
             <div class="form-section">
                <h3>Бонусы от друзей</h3>
                 <div class="form-row">
                    <div class="form-group">
                        <label for="accrueReferralAmount">Начислить</label>
                        <input type="number" id="accrueReferralAmount" placeholder="0" oninput="updateCalculations()">
                    </div>
                    <div class="form-group">
                        <label for="deductReferralAmount">Списать</label>
                        <input type="number" id="deductReferralAmount" placeholder="0" oninput="updateCalculations()">
                    </div>
                 </div>
            </div>
            <div class="form-section">
                <h3>Долги</h3>
                <div class="form-row">
                     <div class="form-group">
                        <label for="addDebtAmount">Добавить долг</label>
                        <input type="number" id="addDebtAmount" placeholder="0" oninput="updateCalculations()">
                    </div>
                    <div class="form-group">
                        <label for="repayDebtAmount">Погасить долг</label>
                        <input type="number" id="repayDebtAmount" placeholder="0" oninput="updateCalculations()">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <div id="modalStatus" class="status-message"></div>
                <button class="btn-submit" onclick="submitTransaction()">Провести операцию</button>
            </div>
        </div>
        <div id="invoice-tab" class="tab-content">
            <div class="form-section">
                <h3>Добавить новую накладную</h3>
                <div id="newInvoiceItemsList"></div>
                <div class="invoice-items-footer">
                    <button class="btn btn-secondary" onclick="addNewInvoiceItemRow()">Добавить товар</button>
                    <div class="invoice-items-total">
                        <strong>Итого:</strong>
                        <span id="newInvoiceTotalAmount">0.00</span>
                    </div>
                </div>
            </div>
            <div class="form-section">
                <h3>Оплата бонусами</h3>
                <div class="bonus-source-selector">
                    <strong>Списать с:</strong>
                    <label><input type="radio" name="bonusSource" value="main" onchange="updateNewInvoiceTotal()" checked> Основного счета</label>
                    <label><input type="radio" name="bonusSource" value="referral" onchange="updateNewInvoiceTotal()"> Счета "от друзей"</label>
                </div>
                <p>Доступно для списания: <strong id="invoiceAvailableBonuses">0.00</strong></p>
                <div class="form-group">
                    <label for="invoiceDeductBonuses">Сумма списания</label>
                    <input type="number" id="invoiceDeductBonuses" oninput="updateNewInvoiceTotal()" placeholder="0.00" step="0.01">
                </div>
                <div class="invoice-section-summary">
                    К оплате: <span id="invoiceFinalAmount">0.00</span>
                </div>
            </div>
            <div class="modal-footer">
                <div id="invoiceStatus" class="status-message"></div>
                <button class="btn-submit" onclick="submitInvoice()">Сохранить накладную</button>
            </div>
            <div class="history-container">
                <h3>История накладных клиента</h3>
                <ul id="modalInvoiceList" class="invoice-list-admin"></ul>
            </div>
        </div>
        <div id="referral-history-tab" class="tab-content">
            <div class="history-container">
                <h3>Общая история операций</h3>
                <ul id="modalHistoryList" class="history-list"></ul>
            </div>
        </div>
      </div>
    </div>
    <div id="addClientModal" class="modal">
      <div class="modal-content">
        <span class="modal-close" onclick="closeModal('addClientModal')">×</span>
        <div class="modal-header">
            <h2>Добавить нового клиента</h2>
        </div>
        <div class="form-group" style="margin-bottom: 1rem;">
            <label for="newClientFirstName">Имя</label>
            <input type="text" id="newClientFirstName" placeholder="Иван">
        </div>
        <div class="form-group" style="margin-bottom: 1.5rem;">
            <label for="newClientPhone">Номер телефона (уникальный)</label>
            <input type="tel" id="newClientPhone" placeholder="+77001234567">
        </div>
        <div class="modal-footer">
            <div id="addClientStatus" class="status-message"></div>
            <button class="btn-submit" onclick="submitNewClient()">Сохранить клиента</button>
        </div>
      </div>
    </div>
    <div id="orgSettingsModal" class="modal">
        <div class="modal-content">
            <span class="modal-close" onclick="closeModal('orgSettingsModal')">×</span>
            <div class="modal-header">
                <h2>Настройки организации</h2>
            </div>
            <div class="details-form">
                <div class="form-group">
                    <label for="orgName">Название организации</label>
                    <input type="text" id="orgName" placeholder="Название вашей организации">
                </div>
                <div class="form-group">
                    <label for="orgPhoneNumbers">Номера телефонов (через запятую)</label>
                    <input type="text" id="orgPhoneNumbers" placeholder="+77001112233,+77004445566">
                </div>
                <div class="form-group">
                    <label for="orgAddress">Адрес</label>
                    <textarea id="orgAddress" placeholder="Город, улица, дом"></textarea>
                </div>
                <div class="form-group">
                    <label for="orgWhatsAppLink">Ссылка на WhatsApp</label>
                    <input type="url" id="orgWhatsAppLink" placeholder="https://wa.me/77001112233">
                </div>
                <div class="form-group">
                    <label for="orgTelegramLink">Ссылка на Telegram</label>
                    <input type="url" id="orgTelegramLink" placeholder="https://t.me/your_telegram_username">
                </div>
            </div>
            <div class="modal-footer">
                <div id="orgStatus" class="status-message"></div>
                <button class="btn-submit" onclick="saveOrgSettings()">Сохранить настройки</button>
            </div>
        </div>
    </div>
     <div id="bonusSettingsModal" class="modal">
        <div class="modal-content">
            <span class="modal-close" onclick="closeModal('bonusSettingsModal')">×</span>
            <div class="modal-header">
                <h2>Настройка бонусной программы</h2>
            </div>
            <div class="details-form">
                <div class="form-group">
                    <label for="settingInvoiceBonus">Процент бонусов с накладных</label>
                    <div class="form-group-horizontal">
                        <input type="number" step="0.1" id="settingInvoiceBonus" placeholder="2">
                        <span>%</span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="settingPromoBonus">Количество бонусов за ввод промокода</label>
                    <input type="number" id="settingPromoBonus" placeholder="50">
                </div>
                <div class="form-group">
                    <label for="settingReferrerBonus">Процент партнеру с первой покупки друга</label>
                    <div class="form-group-horizontal">
                        <input type="number" step="0.1" id="settingReferrerBonus" placeholder="5">
                         <span>%</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <div id="bonusSettingsStatus" class="status-message"></div>
                <button class="btn-submit" onclick="saveBonusSettings()">Сохранить настройки</button>
            </div>
        </div>
    </div>
    <div id="adminInvoiceDetailModal" class="modal">
        <div class="modal-content">
            <span class="modal-close" onclick="closeModal('adminInvoiceDetailModal')">×</span>
            <div class="modal-header">
                <h2 id="adminInvoiceDetailTitle"></h2>
            </div>
            <ul id="adminInvoiceDetailList" class="invoice-detail-list"></ul>
            <div id="adminInvoiceDetailTotal" class="invoice-total-display"></div>
        </div>
    </div>
    <script>
        const transactionModal = document.getElementById('transactionModal');
        const addClientModal = document.getElementById('addClientModal');
        const orgSettingsModal = document.getElementById('orgSettingsModal');
        const bonusSettingsModal = document.getElementById('bonusSettingsModal');
        const adminInvoiceDetailModal = document.getElementById('adminInvoiceDetailModal');
        let currentUserData = null;
        let newInvoiceItems = [];

        function searchUsers() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            document.querySelectorAll('.user-card').forEach(card => {
                card.style.display = card.getAttribute('data-search-term').includes(searchTerm) ? 'flex' : 'none';
            });
        }

        function openTransactionModal(userData) {
            currentUserData = userData;
            document.getElementById('modalUserId').value = userData.id;
            document.getElementById('modalUserName').textContent = `${userData.first_name || ''} ${userData.last_name || ''}`;
            document.getElementById('modalUserUsername').textContent = `@${userData.username || userData.phone_number || ''} | ID: ${userData.id}`;
            ['accrueAmount', 'deductAmount', 'addDebtAmount', 'repayDebtAmount', 'accrueReferralAmount', 'deductReferralAmount'].forEach(id => document.getElementById(id).value = '');
            ['modalStatus', 'invoiceStatus'].forEach(id => document.getElementById(id).textContent = '');
            document.getElementById('invoiceDeductBonuses').value = '';
            
            newInvoiceItems = [];
            renderNewInvoiceItems();
            loadUserHistoryAndInvoices();
            showTab('bonus-debt-tab');
            transactionModal.style.display = 'block';
        }

        function loadUserHistoryAndInvoices() {
            const historyList = document.getElementById('modalHistoryList');
            historyList.innerHTML = '';
            const bonusHistory = (currentUserData.history || []).map(h => ({...h, transaction_type: 'bonus'}));
            const debtHistory = (currentUserData.debt_history || []).map(h => ({...h, transaction_type: 'debt'}));
            const referralHistory = (currentUserData.referral_bonus_history || []).map(h => ({...h, transaction_type: 'referral'}));
            const combinedHistory = [...bonusHistory, ...debtHistory, ...referralHistory].sort((a, b) => new Date(b.date) - new Date(a.date));
            if (combinedHistory.length > 0) {
                combinedHistory.forEach(item => {
                    const li = document.createElement('li');
                    li.className = 'history-item';
                    let sign, amountClass, amountText;
                     if (item.transaction_type === 'bonus') {
                        sign = item.type === 'accrual' ? '+' : '-';
                        amountClass = item.type === 'accrual' ? 'bonus-accrual' : 'bonus-deduction';
                    } else if (item.transaction_type === 'debt') {
                        sign = item.type === 'accrual' ? '+' : '-';
                        amountClass = item.type === 'accrual' ? 'debt-accrual' : 'debt-payment';
                    } else if (item.transaction_type === 'referral') {
                        sign = item.type === 'accrual' ? '+' : '-';
                        amountClass = item.type === 'accrual' ? 'referral-accrual' : 'referral-deduction';
                    }
                    amountText = `${sign}${parseFloat(item.amount).toFixed(2)}`;
                    li.innerHTML = `<div><div class="desc">${item.description}</div><div class="date">${item.date_str}</div></div><div class="amount ${amountClass}">${amountText}</div>`;
                    historyList.appendChild(li);
                });
            } else {
                historyList.innerHTML = '<li style="text-align:center; padding: 1rem; color: var(--admin-secondary);">Нет истории</li>';
            }
            
            const modalInvoiceList = document.getElementById('modalInvoiceList');
            modalInvoiceList.innerHTML = '';
            const userInvoices = (currentUserData.invoices || []).sort((a, b) => new Date(b.date) - new Date(a.date));
            if (userInvoices.length > 0) {
                userInvoices.forEach(invoice => {
                    const li = document.createElement('li');
                    li.innerHTML = `<div class="invoice-info">Накладная #${invoice.invoice_id}<br>${invoice.date_str}</div><div style="display: flex; align-items: center;"><span class="invoice-amount">${parseFloat(invoice.total_amount).toFixed(2)}</span><button class="view-btn" onclick='openAdminInvoiceDetailModal(${JSON.stringify(invoice)})'>👁️</button><button class="delete-btn" onclick='deleteInvoice("${currentUserData.id}", "${invoice.invoice_id}")'>🗑️</button></div>`;
                    modalInvoiceList.appendChild(li);
                });
            } else {
                modalInvoiceList.innerHTML = '<li style="text-align:center; padding: 1rem; color: var(--admin-secondary);">Накладных пока нет.</li>';
            }
            updateCalculations();
        }

        function openAddClientModal() {
            document.getElementById('newClientFirstName').value = '';
            document.getElementById('newClientPhone').value = '';
            document.getElementById('addClientStatus').textContent = '';
            addClientModal.style.display = 'block';
        }

        function openOrgSettingsModal() {
            fetch('/admin/organization_details')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('orgName').value = data.name || '';
                    document.getElementById('orgPhoneNumbers').value = (data.phone_numbers || []).join(',') || '';
                    document.getElementById('orgAddress').value = data.address || '';
                    document.getElementById('orgWhatsAppLink').value = data.whatsapp_link || '';
                    document.getElementById('orgTelegramLink').value = data.telegram_link || '';
                    document.getElementById('orgStatus').textContent = '';
                    orgSettingsModal.style.display = 'block';
                })
                .catch(error => {
                    console.error('Error fetching organization details:', error);
                    const orgStatus = document.getElementById('orgStatus');
                    orgStatus.style.color = 'var(--admin-danger)';
                    orgStatus.textContent = 'Ошибка загрузки данных.';
                    orgSettingsModal.style.display = 'block';
                });
        }

        function openBonusSettingsModal() {
            fetch('/admin/bonus_settings')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('settingInvoiceBonus').value = data.invoice_bonus_percentage || 0;
                    document.getElementById('settingPromoBonus').value = data.referral_promo_bonus || 0;
                    document.getElementById('settingReferrerBonus').value = data.referrer_first_purchase_percentage || 0;
                    document.getElementById('bonusSettingsStatus').textContent = '';
                    bonusSettingsModal.style.display = 'block';
                })
                .catch(error => {
                    console.error('Error fetching bonus settings:', error);
                    document.getElementById('bonusSettingsStatus').textContent = 'Ошибка загрузки настроек.';
                    bonusSettingsModal.style.display = 'block';
                });
        }

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
            if (modalId === 'transactionModal') currentUserData = null;
        }

        function showTab(tabId) {
            document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
            document.getElementById(tabId).classList.add('active');
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelector(`.tab-btn[data-tab="${tabId}"]`).classList.add('active');
        }

        document.querySelectorAll('.tab-btn').forEach(button => {
            button.addEventListener('click', () => showTab(button.dataset.tab));
        });

        function updateCalculations() {
            if (!currentUserData) return;
        }

        async function submitTransaction() {
            const statusEl = document.getElementById('modalStatus');
            statusEl.style.color = 'var(--admin-secondary)';
            statusEl.textContent = 'Обработка...';
            const payload = {
                user_id: document.getElementById('modalUserId').value,
                accrue_amount: parseFloat(document.getElementById('accrueAmount').value) || 0,
                deduct_amount: parseFloat(document.getElementById('deductAmount').value) || 0,
                accrue_referral_amount: parseFloat(document.getElementById('accrueReferralAmount').value) || 0,
                deduct_referral_amount: parseFloat(document.getElementById('deductReferralAmount').value) || 0,
                add_debt_amount: parseFloat(document.getElementById('addDebtAmount').value) || 0,
                repay_debt_amount: parseFloat(document.getElementById('repayDebtAmount').value) || 0,
            };
            if (Object.values(payload).slice(1).every(v => v <= 0)) {
                statusEl.style.color = 'var(--admin-danger)';
                statusEl.textContent = 'Введите сумму для любой из операций.';
                return;
            }
            try {
                const response = await fetch('/admin/add_transaction', {
                    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload)
                });
                const result = await response.json();
                if (response.ok) {
                    statusEl.style.color = 'var(--admin-success)';
                    statusEl.textContent = 'Операция успешно проведена!';
                    setTimeout(() => location.reload(), 1500);
                } else { throw new Error(result.message || 'Произошла ошибка'); }
            } catch (error) {
                statusEl.style.color = 'var(--admin-danger)';
                statusEl.textContent = `Ошибка: ${error.message}`;
            }
        }
        
        async function submitNewClient() {
            const statusEl = document.getElementById('addClientStatus');
            statusEl.style.color = 'var(--admin-secondary)';
            statusEl.textContent = 'Сохранение...';
            const payload = {
                first_name: document.getElementById('newClientFirstName').value.trim(),
                phone_number: document.getElementById('newClientPhone').value.trim(),
            };
            if (!payload.first_name || !payload.phone_number) {
                statusEl.style.color = 'var(--admin-danger)';
                statusEl.textContent = 'Имя и номер телефона обязательны.';
                return;
            }
            try {
                const response = await fetch('/admin/add_client', {
                    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload)
                });
                const result = await response.json();
                if (response.ok) {
                    statusEl.style.color = 'var(--admin-success)';
                    statusEl.textContent = 'Клиент успешно добавлен!';
                    setTimeout(() => location.reload(), 1500);
                } else { throw new Error(result.message || 'Произошла ошибка'); }
            } catch (error) {
                statusEl.style.color = 'var(--admin-danger)';
                statusEl.textContent = `Ошибка: ${error.message}`;
            }
        }

        async function saveOrgSettings() {
            const statusEl = document.getElementById('orgStatus');
            statusEl.style.color = 'var(--admin-secondary)';
            statusEl.textContent = 'Сохранение...';
            const phoneNumbersRaw = document.getElementById('orgPhoneNumbers').value.trim();
            const payload = {
                name: document.getElementById('orgName').value.trim(),
                phone_numbers: phoneNumbersRaw ? phoneNumbersRaw.split(',').map(p => p.trim()) : [],
                address: document.getElementById('orgAddress').value.trim(),
                whatsapp_link: document.getElementById('orgWhatsAppLink').value.trim(),
                telegram_link: document.getElementById('orgTelegramLink').value.trim(),
            };
            try {
                const response = await fetch('/admin/organization_details', {
                    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload)
                });
                const result = await response.json();
                if (response.ok) {
                    statusEl.style.color = 'var(--admin-success)';
                    statusEl.textContent = 'Настройки организации успешно сохранены!';
                    setTimeout(() => closeModal('orgSettingsModal'), 1500);
                } else { throw new Error(result.message || 'Произошла ошибка'); }
            } catch (error) {
                statusEl.style.color = 'var(--admin-danger)';
                statusEl.textContent = `Ошибка: ${error.message}`;
            }
        }

        async function saveBonusSettings() {
            const statusEl = document.getElementById('bonusSettingsStatus');
            statusEl.style.color = 'var(--admin-secondary)';
            statusEl.textContent = 'Сохранение...';
            const payload = {
                invoice_bonus_percentage: parseFloat(document.getElementById('settingInvoiceBonus').value) || 0,
                referral_promo_bonus: parseFloat(document.getElementById('settingPromoBonus').value) || 0,
                referrer_first_purchase_percentage: parseFloat(document.getElementById('settingReferrerBonus').value) || 0,
            };
            try {
                const response = await fetch('/admin/bonus_settings', {
                    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload)
                });
                const result = await response.json();
                if (response.ok) {
                    statusEl.style.color = 'var(--admin-success)';
                    statusEl.textContent = 'Настройки бонусной программы сохранены!';
                    setTimeout(() => closeModal('bonusSettingsModal'), 1500);
                } else { throw new Error(result.message || 'Произошла ошибка'); }
            } catch (error) {
                statusEl.style.color = 'var(--admin-danger)';
                statusEl.textContent = `Ошибка: ${error.message}`;
            }
        }

        async function deleteClient(userId) {
            if (!confirm(`Вы уверены, что хотите удалить клиента с ID ${userId}? Это действие необратимо.`)) return;
            try {
                const response = await fetch('/admin/delete_client', {
                    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_id: userId })
                });
                const result = await response.json();
                if (response.ok) location.reload();
                else throw new Error(result.message || 'Не удалось удалить клиента.');
            } catch (error) { alert(`Ошибка: ${error.message}`); }
        }

        function addNewInvoiceItemRow() {
            newInvoiceItems.push({ product_name: '', quantity: 1, unit_price: 0, item_total: 0 });
            renderNewInvoiceItems();
        }

        function updateInvoiceItem(index, field, value) {
            if (!newInvoiceItems[index]) return;
            newInvoiceItems[index][field] = value;
            const qty = parseFloat(newInvoiceItems[index].quantity) || 0;
            const price = parseFloat(newInvoiceItems[index].unit_price) || 0;
            const itemTotal = qty * price;
            newInvoiceItems[index].item_total = itemTotal;
            const list = document.getElementById('newInvoiceItemsList');
            const itemRow = list.children[index];
            if (itemRow) {
                itemRow.querySelector('.item-total-display').textContent = itemTotal.toFixed(2);
            }
            updateNewInvoiceTotal();
        }

        function removeInvoiceItemRow(index) {
            newInvoiceItems.splice(index, 1);
            renderNewInvoiceItems();
        }
        
        function renderNewInvoiceItems() {
            const list = document.getElementById('newInvoiceItemsList');
            list.innerHTML = '';
            newInvoiceItems.forEach((item, index) => {
                const itemDiv = document.createElement('div');
                itemDiv.className = 'invoice-item-row';
                const productName = item.product_name ? String(item.product_name).replace(/"/g, '&quot;') : '';
                itemDiv.innerHTML = `
                    <div class="form-group item-name">
                        <label>Товар</label>
                        <input type="text" placeholder="Название товара" value="${productName}" oninput="updateInvoiceItem(${index}, 'product_name', this.value)">
                    </div>
                    <div class="form-group item-qty">
                        <label>Кол-во</label>
                        <input type="number" step="1" min="1" placeholder="1" value="${item.quantity || '1'}" oninput="updateInvoiceItem(${index}, 'quantity', this.value)">
                    </div>
                    <div class="form-group item-price">
                        <label>Цена</label>
                        <input type="number" step="0.01" min="0" placeholder="0.00" value="${item.unit_price || ''}" oninput="updateInvoiceItem(${index}, 'unit_price', this.value)">
                    </div>
                    <div class="item-total-group">
                         <label>Сумма</label>
                         <div class="item-total-display">${(item.item_total || 0).toFixed(2)}</div>
                    </div>
                    <button class="action-btn" onclick="removeInvoiceItemRow(${index})">🗑️</button>
                `;
                list.appendChild(itemDiv);
            });
            updateNewInvoiceTotal();
        }

        function updateNewInvoiceTotal() {
            if (!currentUserData) return;
            const bonusSource = document.querySelector('input[name="bonusSource"]:checked').value;
            const availableBonuses = bonusSource === 'main' ? (parseFloat(currentUserData.bonuses) || 0) : (parseFloat(currentUserData.referral_bonuses) || 0);
            document.getElementById('invoiceAvailableBonuses').textContent = availableBonuses.toFixed(2);
            
            let total = newInvoiceItems.reduce((sum, item) => sum + (parseFloat(item.item_total) || 0), 0);
            document.getElementById('newInvoiceTotalAmount').textContent = total.toFixed(2);
            
            const deductBonusesInput = document.getElementById('invoiceDeductBonuses');
            let deductAmount = parseFloat(deductBonusesInput.value) || 0;

            let cappedDeductAmount = Math.max(0, Math.min(deductAmount, availableBonuses, total));
            
            if (deductAmount > cappedDeductAmount) {
                 deductBonusesInput.value = cappedDeductAmount > 0 ? cappedDeductAmount.toFixed(2) : '';
            }
            
            let finalAmount = total - cappedDeductAmount;
            document.getElementById('invoiceFinalAmount').textContent = finalAmount.toFixed(2);
        }

        async function submitInvoice() {
            const statusEl = document.getElementById('invoiceStatus');
            statusEl.style.color = 'var(--admin-secondary)';
            statusEl.textContent = 'Сохранение...';
            if (!currentUserData) {
                statusEl.style.color = 'var(--admin-danger)';
                statusEl.textContent = 'Пользователь не выбран.';
                return;
            }
            const itemsToAdd = newInvoiceItems.filter(item => item.product_name && item.product_name.trim() !== '' && (item.quantity > 0 || item.unit_price > 0));
            if (itemsToAdd.length === 0) {
                statusEl.style.color = 'var(--admin-danger)';
                statusEl.textContent = 'Добавьте хотя бы один товар.';
                return;
            }
            const totalAmount = itemsToAdd.reduce((sum, item) => sum + item.item_total, 0);
            const deductBonuses = parseFloat(document.getElementById('invoiceDeductBonuses').value) || 0;
            const bonusSource = document.querySelector('input[name="bonusSource"]:checked').value;

            const payload = { 
                user_id: currentUserData.id, 
                total_amount: totalAmount, 
                items: itemsToAdd,
                deduct_bonuses: deductBonuses,
                bonus_source: bonusSource
            };
            try {
                const response = await fetch('/admin/add_invoice', {
                    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload)
                });
                const result = await response.json();
                if (response.ok) {
                    statusEl.style.color = 'var(--admin-success)';
                    statusEl.textContent = 'Накладная успешно сохранена!';
                    setTimeout(() => location.reload(), 1500);
                } else { throw new Error(result.message || 'Произошла ошибка'); }
            } catch (error) {
                statusEl.style.color = 'var(--admin-danger)';
                statusEl.textContent = `Ошибка: ${error.message}`;
            }
        }

        function openAdminInvoiceDetailModal(invoiceData) {
            document.getElementById('adminInvoiceDetailTitle').textContent = `Накладная #${invoiceData.invoice_id} от ${invoiceData.date_str}`;
            const invoiceDetailList = document.getElementById('adminInvoiceDetailList');
            invoiceDetailList.innerHTML = '';
            invoiceData.items.forEach(item => {
                const li = document.createElement('li');
                li.className = 'invoice-detail-item';
                li.innerHTML = `<span class="item-name">${item.product_name}</span><span class="item-qty-price">${item.quantity} x ${parseFloat(item.unit_price).toFixed(2)}</span><span class="item-total">${parseFloat(item.item_total).toFixed(2)}</span>`;
                invoiceDetailList.appendChild(li);
            });

            const totalDisplay = document.getElementById('adminInvoiceDetailTotal');
            let bonusesDeducted = parseFloat(invoiceData.bonuses_deducted || 0);
            let totalAmount = parseFloat(invoiceData.total_amount);
            let finalAmount = totalAmount - bonusesDeducted;
            let bonusSourceText = invoiceData.bonus_source_used === 'referral' ? ' (от друзей)' : ' (основных)';

            let totalHTML = `<div><span>Итого:</span><span>${totalAmount.toFixed(2)}</span></div>`;
            if (bonusesDeducted > 0) {
                totalHTML += `<div><span>Списано бонусов${bonusSourceText}:</span><span style="color: var(--admin-danger);">- ${bonusesDeducted.toFixed(2)}</span></div>`;
                totalHTML += `<hr style="border: none; border-top: 1px solid #dee2e6; margin: 5px 0;"><div><strong style="font-size: 1.1em;">К оплате:</strong><strong style="font-size: 1.1em; color: var(--admin-success);">${finalAmount.toFixed(2)}</strong></div>`;
            }
            totalDisplay.innerHTML = totalHTML;
            adminInvoiceDetailModal.style.display = 'block';
        }

        async function deleteInvoice(userId, invoiceId) {
            if (!confirm(`Вы уверены, что хотите удалить накладную #${invoiceId} для клиента ID ${userId}?`)) return;
            try {
                const response = await fetch('/admin/delete_invoice', {
                    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_id: userId, invoice_id: invoiceId })
                });
                const result = await response.json();
                if (response.ok) location.reload();
                else throw new Error(result.message || 'Не удалось удалить накладную.');
            } catch (error) { alert(`Ошибка: ${error.message}`); }
        }

        window.onclick = function(event) {
            if (event.target == transactionModal) closeModal('transactionModal');
            if (event.target == addClientModal) closeModal('addClientModal');
            if (event.target == orgSettingsModal) closeModal('orgSettingsModal');
            if (event.target == bonusSettingsModal) closeModal('bonusSettingsModal');
            if (event.target == adminInvoiceDetailModal) closeModal('adminInvoiceDetailModal');
        }

        document.addEventListener('DOMContentLoaded', () => { addNewInvoiceItemRow(); });
    </script>
</body>
</html>
"""

@app.route('/')
def index():
    user_id_str = request.args.get('user_id_for_test')
    user_data = {}
    is_first_visit = False

    with _data_lock:
        if user_id_str and user_id_str in visitor_data_cache:
            user_data = visitor_data_cache[user_id_str]
            user_data['id'] = user_id_str
            is_first_visit = not user_data.get('has_been_welcomed', False)
            bonus_history = user_data.get('history', [])
            debt_history = user_data.get('debt_history', [])
            referral_history = user_data.get('referral_bonus_history', [])
            for item in bonus_history: item['transaction_type'] = 'bonus'
            for item in debt_history: item['transaction_type'] = 'debt'
            for item in referral_history: item['transaction_type'] = 'referral'
            user_data['combined_history'] = sorted(bonus_history + debt_history + referral_history, key=lambda x: datetime.fromisoformat(x['date']), reverse=True)
            user_data['invoices'] = user_data.get('invoices', [])
        else:
            user_data = {"id": "N/A", "bonuses": 0, "debts": 0, "referral_bonuses": 0, "combined_history": [], "invoices": [], "referral_code": "N/A"}
        
        org_details = visitor_data_cache.get('organization_details', {})
        bonus_settings = visitor_data_cache.get('bonus_program_settings', {})
        
    return render_template_string(TEMPLATE, user=user_data, org_details=org_details, is_first_visit=is_first_visit, bonus_settings=bonus_settings)

@app.route('/verify', methods=['POST'])
def verify_data():
    try:
        req_data = request.get_json()
        init_data_str = req_data.get('initData')
        if not init_data_str:
            return jsonify({"status": "error", "message": "Missing initData"}), 400

        user_data_parsed, is_valid = verify_telegram_data(init_data_str)
        user_info_dict = {}
        if user_data_parsed and 'user' in user_data_parsed:
            try:
                user_info_dict = json.loads(unquote(user_data_parsed['user'][0]))
            except Exception as e:
                logging.error(f"Could not parse user JSON: {e}")
        
        if is_valid:
            tg_user_id = user_info_dict.get('id')
            if tg_user_id:
                now = datetime.now(ALMATY_TZ)
                user_id_to_save = None

                with _data_lock:
                    existing_user_key = next((k for k, u in visitor_data_cache.items() if k != "organization_details" and str(u.get('telegram_id')) == str(tg_user_id)), None)
                    
                    if existing_user_key:
                        user_entry = visitor_data_cache[existing_user_key]
                        user_entry.update({
                            'first_name': user_info_dict.get('first_name'), 'last_name': user_info_dict.get('last_name'),
                            'username': user_info_dict.get('username'), 'photo_url': user_info_dict.get('photo_url'),
                            'visited_at': now.timestamp(), 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S')
                        })
                        user_id_to_save = existing_user_key
                    else:
                        new_user_id = generate_unique_id(visitor_data_cache)
                        user_entry = {
                            'id': new_user_id, 'telegram_id': tg_user_id,
                            'first_name': user_info_dict.get('first_name'), 'last_name': user_info_dict.get('last_name'),
                            'username': user_info_dict.get('username'), 'photo_url': user_info_dict.get('photo_url'),
                            'is_premium': user_info_dict.get('is_premium', False), 'phone_number': None,
                            'visited_at': now.timestamp(), 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'),
                            'bonuses': 0, 'history': [], 'debts': 0, 'debt_history': [], 'invoices': [],
                            'referral_code': f'PROMO{new_user_id}', 'referred_by': None, 'referrals': [], 'has_been_welcomed': False,
                            'referral_bonuses': 0, 'referral_bonus_history': [], 'has_made_first_purchase': False,
                        }
                        visitor_data_cache[new_user_id] = user_entry
                        user_id_to_save = new_user_id
                    
                    save_visitor_data()

                return jsonify({"status": "ok", "verified": True, "user_id": user_id_to_save})
            else:
                 return jsonify({"status": "error", "verified": True, "message": "User ID not found"}), 400
        else:
            return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403
    except Exception as e:
        logging.exception("Error in /verify endpoint")
        return jsonify({"status": "error", "message": "Internal server error"}), 500

@app.route('/submit_referral', methods=['POST'])
def submit_referral():
    try:
        data = request.get_json()
        user_id = str(data.get('user_id'))
        referral_code = data.get('referral_code')

        with _data_lock:
            if not user_id or user_id not in visitor_data_cache:
                return jsonify({"status": "error", "message": "Пользователь не найден."}), 404

            user = visitor_data_cache[user_id]
            if user.get('has_been_welcomed', False):
                return jsonify({"status": "ok", "message": "Вы уже прошли этот шаг."}), 200

            user['has_been_welcomed'] = True
            bonus_settings = visitor_data_cache.get('bonus_program_settings', {})
            promo_bonus = float(bonus_settings.get('referral_promo_bonus', 0))

            if referral_code:
                referrer_id = next((u_id for u_id, u in visitor_data_cache.items() if u_id not in ["organization_details", "bonus_program_settings"] and u.get('referral_code') == referral_code), None)
                
                if not referrer_id:
                    return jsonify({"status": "error", "message": "Промокод не найден."}), 404
                if referrer_id == user_id:
                    return jsonify({"status": "error", "message": "Нельзя использовать свой промокод."}), 400

                user['referred_by'] = referrer_id
                referrer = visitor_data_cache[referrer_id]
                if 'referrals' not in referrer: referrer['referrals'] = []
                referrer['referrals'].append(user_id)

                if promo_bonus > 0:
                    user['bonuses'] = user.get('bonuses', 0) + promo_bonus
                    now = datetime.now(ALMATY_TZ)
                    history_entry = {
                        "type": "accrual", "amount": promo_bonus, "description": "Бонус за промокод",
                        "date": now.isoformat(), "date_str": now.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    if 'history' not in user: user['history'] = []
                    user['history'].append(history_entry)
            
            save_visitor_data()
            message = "Промокод успешно применен!" if referral_code else "Добро пожаловать!"
            return jsonify({"status": "ok", "message": message}), 200

    except Exception as e:
        logging.exception("Error in /submit_referral endpoint")
        return jsonify({"status": "error", "message": "Внутренняя ошибка сервера"}), 500

@app.route('/admin')
def admin_panel():
    users_list = []
    user_name_map = {uid: f"{ud.get('first_name', '')} {ud.get('last_name', '')}".strip() or f"ID: {uid}" for uid, ud in visitor_data_cache.items() if uid not in ["organization_details", "bonus_program_settings"]}

    for user_id, user_data in visitor_data_cache.items():
        if user_id in ["organization_details", "bonus_program_settings"]: continue
        user_data_copy = user_data.copy()
        user_data_copy['id'] = user_id
        user_data_copy['referrals_count'] = len(user_data_copy.get('referrals', []))
        referrer_id = user_data_copy.get('referred_by')
        user_data_copy['referrer_info'] = user_name_map.get(referrer_id, None)
        users_list.append(user_data_copy)
    
    total_users = len(users_list)
    total_bonuses = sum(u.get('bonuses', 0) for u in users_list)
    total_debts = sum(u.get('debts', 0) for u in users_list)
    total_referral_bonuses = sum(u.get('referral_bonuses', 0) for u in users_list)
    
    summary_stats = {
        "total_users": total_users, "total_bonuses": total_bonuses,
        "total_debts": total_debts, "total_referral_bonuses": total_referral_bonuses
    }
    return render_template_string(ADMIN_TEMPLATE, users=users_list, summary=summary_stats)

@app.route('/admin/add_client', methods=['POST'])
def add_client():
    try:
        data = request.get_json()
        phone_number = data.get('phone_number')
        first_name = data.get('first_name')
        if not phone_number or not first_name:
            return jsonify({"status": "error", "message": "Имя и номер телефона обязательны."}), 400
        
        with _data_lock:
            if any(u.get('phone_number') == phone_number for k, u in visitor_data_cache.items() if k not in ["organization_details", "bonus_program_settings"]):
                return jsonify({"status": "error", "message": "Клиент с таким номером телефона уже существует."}), 409

            now = datetime.now(ALMATY_TZ)
            new_id = generate_unique_id(visitor_data_cache)
            new_client = {
                'id': new_id, 'telegram_id': None, 'first_name': first_name, 'last_name': None,
                'username': None, 'photo_url': None, 'is_premium': False, 'phone_number': phone_number,
                'visited_at': now.timestamp(), 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'),
                'bonuses': 0, 'history': [], 'debts': 0, 'debt_history': [], 'invoices': [],
                'referral_code': f'PROMO{new_id}', 'referred_by': None, 'referrals': [], 'has_been_welcomed': True,
                'referral_bonuses': 0, 'referral_bonus_history': [], 'has_made_first_purchase': False,
            }
            visitor_data_cache[new_id] = new_client
            save_visitor_data()
        return jsonify({"status": "ok", "message": "Client added successfully"}), 201
    except Exception as e:
        logging.exception("Error in /admin/add_client endpoint")
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/admin/add_transaction', methods=['POST'])
def add_transaction():
    try:
        data = request.get_json()
        user_id = str(data.get('user_id'))
        accrue_amount = float(data.get('accrue_amount', 0))
        deduct_amount = float(data.get('deduct_amount', 0))
        accrue_referral_amount = float(data.get('accrue_referral_amount', 0))
        deduct_referral_amount = float(data.get('deduct_referral_amount', 0))
        add_debt_amount = float(data.get('add_debt_amount', 0))
        repay_debt_amount = float(data.get('repay_debt_amount', 0))

        if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400
        
        with _data_lock:
            if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404
            user = visitor_data_cache[user_id]
            now = datetime.now(ALMATY_TZ)
            now_iso, now_str = now.isoformat(), now.strftime('%Y-%m-%d %H:%M:%S')

            if deduct_amount > user.get('bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно основных бонусов для списания"}), 400
            if deduct_referral_amount > user.get('referral_bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно бонусов от друзей для списания"}), 400
            if repay_debt_amount > user.get('debts', 0): return jsonify({"status": "error", "message": "Сумма погашения превышает текущий долг"}), 400

            if 'history' not in user: user['history'] = []
            if 'referral_bonus_history' not in user: user['referral_bonus_history'] = []
            if 'debt_history' not in user: user['debt_history'] = []

            user['bonuses'] = round(user.get('bonuses', 0) + accrue_amount - deduct_amount, 2)
            if accrue_amount > 0: user['history'].append({"type": "accrual", "amount": accrue_amount, "description": "Начисление бонусов (админ)", "date": now_iso, "date_str": now_str})
            if deduct_amount > 0: user['history'].append({"type": "deduction", "amount": deduct_amount, "description": "Списание бонусов (админ)", "date": now_iso, "date_str": now_str})

            user['referral_bonuses'] = round(user.get('referral_bonuses', 0) + accrue_referral_amount - deduct_referral_amount, 2)
            if accrue_referral_amount > 0: user['referral_bonus_history'].append({"type": "accrual", "amount": accrue_referral_amount, "description": "Начисление бонусов от друзей (админ)", "date": now_iso, "date_str": now_str})
            if deduct_referral_amount > 0: user['referral_bonus_history'].append({"type": "deduction", "amount": deduct_referral_amount, "description": "Списание бонусов от друзей (админ)", "date": now_iso, "date_str": now_str})

            user['debts'] = round(user.get('debts', 0) + add_debt_amount - repay_debt_amount, 2)
            if add_debt_amount > 0: user['debt_history'].append({"type": "accrual", "amount": add_debt_amount, "description": "Добавление долга", "date": now_iso, "date_str": now_str})
            if repay_debt_amount > 0: user['debt_history'].append({"type": "payment", "amount": repay_debt_amount, "description": "Погашение долга", "date": now_iso, "date_str": now_str})
            
            save_visitor_data()
            return jsonify({"status": "ok", "message": "Transaction successful"}), 200
    except Exception as e:
        logging.exception("Error in /admin/add_transaction endpoint")
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/admin/add_invoice', methods=['POST'])
def add_invoice():
    try:
        data = request.get_json()
        user_id = str(data.get('user_id'))
        total_amount = float(data.get('total_amount', 0))
        items = data.get('items', [])
        deduct_bonuses = float(data.get('deduct_bonuses', 0))
        bonus_source = data.get('bonus_source', 'main')

        if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400
        if not items: return jsonify({"status": "error", "message": "Необходимо добавить товары в накладную."}), 400
        
        with _data_lock:
            if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404
            user = visitor_data_cache[user_id]
            
            if bonus_source == 'main' and deduct_bonuses > user.get('bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно основных бонусов для списания."}), 400
            if bonus_source == 'referral' and deduct_bonuses > user.get('referral_bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно бонусов от друзей для списания."}), 400
            if deduct_bonuses > total_amount: return jsonify({"status": "error", "message": "Сумма списания не может превышать сумму накладной."}), 400

            now = datetime.now(ALMATY_TZ)
            now_iso, now_str = now.isoformat(), now.strftime('%Y-%m-%d %H:%M:%S')
            invoice_id = str(uuid.uuid4().hex[:8]).upper()
            
            processed_items = [{"product_name": item.get('product_name'), "quantity": float(item.get('quantity', 0)), "unit_price": float(item.get('unit_price', 0)), "item_total": round(float(item.get('quantity', 0)) * float(item.get('unit_price', 0)), 2)} for item in items]
            
            new_invoice = {
                "invoice_id": invoice_id, "date": now_iso, "date_str": now_str, 
                "total_amount": round(total_amount, 2), "items": processed_items,
                "bonuses_deducted": round(deduct_bonuses, 2),
                "bonus_source_used": bonus_source if deduct_bonuses > 0 else None
            }
            if 'invoices' not in user: user['invoices'] = []
            user['invoices'].append(new_invoice)
            
            if deduct_bonuses > 0:
                if bonus_source == 'main':
                    user['bonuses'] = round(user.get('bonuses', 0) - deduct_bonuses, 2)
                    if 'history' not in user: user['history'] = []
                    user['history'].append({"type": "deduction", "amount": deduct_bonuses, "description": f"Оплата по накладной #{invoice_id}", "date": now_iso, "date_str": now_str})
                elif bonus_source == 'referral':
                    user['referral_bonuses'] = round(user.get('referral_bonuses', 0) - deduct_bonuses, 2)
                    if 'referral_bonus_history' not in user: user['referral_bonus_history'] = []
                    user['referral_bonus_history'].append({"type": "deduction", "amount": deduct_bonuses, "description": f"Оплата по накладной #{invoice_id}", "date": now_iso, "date_str": now_str})

            bonus_settings = visitor_data_cache.get('bonus_program_settings', {})
            invoice_bonus_percentage = float(bonus_settings.get('invoice_bonus_percentage', 0))
            
            if deduct_bonuses <= 0 and invoice_bonus_percentage > 0 and total_amount > 0:
                bonus_from_invoice = round((total_amount * invoice_bonus_percentage) / 100, 2)
                if bonus_from_invoice > 0:
                    user['bonuses'] = user.get('bonuses', 0) + bonus_from_invoice
                    if 'history' not in user: user['history'] = []
                    user['history'].append({"type": "accrual", "amount": bonus_from_invoice, "description": f"Бонус с накладной #{invoice_id}", "date": now_iso, "date_str": now_str})

            if not user.get('has_made_first_purchase', False) and total_amount > 0:
                user['has_made_first_purchase'] = True
                referrer_id = user.get('referred_by')
                if referrer_id and referrer_id in visitor_data_cache:
                    referrer = visitor_data_cache[referrer_id]
                    referrer_bonus_percentage = float(bonus_settings.get('referrer_first_purchase_percentage', 0))
                    if referrer_bonus_percentage > 0:
                        commission = round((total_amount * referrer_bonus_percentage) / 100, 2)
                        if commission > 0:
                            referrer['referral_bonuses'] = referrer.get('referral_bonuses', 0) + commission
                            if 'referral_bonus_history' not in referrer: referrer['referral_bonus_history'] = []
                            referrer['referral_bonus_history'].append({
                                "type": "accrual", "amount": commission,
                                "description": f"Бонус от друга {user.get('first_name', 'ID:'+user_id)}",
                                "date": now_iso, "date_str": now_str
                            })

            save_visitor_data()
        return jsonify({"status": "ok", "message": "Invoice added successfully", "invoice_id": invoice_id}), 200
    except Exception as e:
        logging.exception("Error in /admin/add_invoice endpoint")
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/admin/delete_invoice', methods=['POST'])
def delete_invoice():
    try:
        data = request.get_json()
        user_id, invoice_id = str(data.get('user_id')), data.get('invoice_id')
        if not user_id or not invoice_id: return jsonify({"status": "error", "message": "User ID and Invoice ID are required"}), 400
        
        with _data_lock:
            if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404
            user = visitor_data_cache[user_id]
            if 'invoices' not in user: return jsonify({"status": "error", "message": "User has no invoices"}), 404
            original_count = len(user['invoices'])
            user['invoices'] = [inv for inv in user['invoices'] if inv.get('invoice_id') != invoice_id]
            if len(user['invoices']) == original_count: return jsonify({"status": "error", "message": "Invoice not found for this user"}), 404
            save_visitor_data()
        return jsonify({"status": "ok", "message": "Invoice deleted successfully"}), 200
    except Exception as e:
        logging.exception("Error in /admin/delete_invoice endpoint")
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/admin/delete_client', methods=['POST'])
def delete_client():
    try:
        user_id = str(request.get_json().get('user_id'))
        if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400

        with _data_lock:
            if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404
            if visitor_data_cache[user_id].get('telegram_id') is not None: return jsonify({"status": "error", "message": "Cannot delete a Telegram-linked user"}), 403
            
            user_to_delete = visitor_data_cache[user_id]
            referrer_id = user_to_delete.get('referred_by')
            if referrer_id and referrer_id in visitor_data_cache:
                referrer = visitor_data_cache[referrer_id]
                if 'referrals' in referrer and user_id in referrer['referrals']:
                    referrer['referrals'].remove(user_id)
            
            del visitor_data_cache[user_id]
            save_visitor_data()
        return jsonify({"status": "ok", "message": "Client deleted successfully"}), 200
    except Exception as e:
        logging.exception("Error in /admin/delete_client endpoint")
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/admin/organization_details', methods=['GET'])
def get_organization_details():
    try:
        return jsonify(visitor_data_cache.get('organization_details', {})), 200
    except Exception as e:
        logging.exception("Error getting organization details")
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/admin/organization_details', methods=['POST'])
def save_organization_details():
    try:
        data = request.get_json()
        with _data_lock:
            visitor_data_cache['organization_details'] = {
                "name": data.get("name", ""), "phone_numbers": data.get("phone_numbers", []),
                "address": data.get("address", ""), "whatsapp_link": data.get("whatsapp_link", ""),
                "telegram_link": data.get("telegram_link", "")
            }
            save_visitor_data()
        return jsonify({"status": "ok", "message": "Organization details saved successfully"}), 200
    except Exception as e:
        logging.exception("Error saving organization details")
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/admin/bonus_settings', methods=['GET'])
def get_bonus_settings():
    try:
        return jsonify(visitor_data_cache.get('bonus_program_settings', {})), 200
    except Exception as e:
        logging.exception("Error getting bonus settings")
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/admin/bonus_settings', methods=['POST'])
def save_bonus_settings():
    try:
        data = request.get_json()
        with _data_lock:
            settings = visitor_data_cache.get('bonus_program_settings', {})
            settings['invoice_bonus_percentage'] = float(data.get('invoice_bonus_percentage', 0))
            settings['referral_promo_bonus'] = float(data.get('referral_promo_bonus', 0))
            settings['referrer_first_purchase_percentage'] = float(data.get('referrer_first_purchase_percentage', 0))
            visitor_data_cache['bonus_program_settings'] = settings
            save_visitor_data()
        return jsonify({"status": "ok", "message": "Bonus program settings saved"}), 200
    except Exception as e:
        logging.exception("Error saving bonus settings")
        return jsonify({"status": "error", "message": str(e)}), 500

if __name__ == '__main__':
    print("--- BONUS SYSTEM SERVER ---")
    print(f"Server starting on http://{HOST}:{PORT}")

    print("Attempting to load local data file...")
    load_visitor_data()

    if not visitor_data_cache or len(visitor_data_cache) <= 2:
        print("Local data file not found or is empty.")
        if HF_TOKEN_READ:
            print("Attempting to restore data from Hugging Face...")
            if not download_data_from_hf():
                 print("Failed to restore from Hugging Face. Starting fresh.")
        else:
            print("HF_TOKEN_READ not set. Cannot restore from backup. Starting fresh.")
    else:
        user_count = len([k for k in visitor_data_cache if k not in ['organization_details', 'bonus_program_settings']])
        print(f"Successfully loaded data for {user_count} users from local file.")

    print("WARNING: The /admin route is NOT protected. Implement proper authentication for production.")

    if HF_TOKEN_WRITE:
        backup_thread = threading.Thread(target=periodic_backup, daemon=True)
        backup_thread.start()
        print("Periodic backup thread started (every hour).")
    else:
        print("WARNING: HF_TOKEN_WRITE not set. Periodic backups to Hugging Face are disabled.")

    print("--- Server Ready ---")
    app.run(host=HOST, port=PORT, debug=False)