File size: 159,583 Bytes
eddf660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
from flask import Flask, render_template_string, request, redirect, url_for, jsonify, flash, abort, Response, session, g
import json
import os
import logging
import threading
import time
from datetime import datetime, timedelta
import pytz
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
import uuid
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
import functools
from functools import wraps
from collections import defaultdict
from urllib.parse import quote

app = Flask(__name__)
app.secret_key = os.urandom(24)
app.permanent_session_lifetime = timedelta(days=7)

ADMIN_PASS = os.getenv("ADMIN_PASS", "noskiadmin")

DATA_DIR = 'pos_data'
os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(os.path.join(app.static_folder, 'product_images'), exist_ok=True)

INVENTORY_FILE = os.path.join(DATA_DIR, 'inventory.json')
TRANSACTIONS_FILE = os.path.join(DATA_DIR, 'transactions.json')
USERS_FILE = os.path.join(DATA_DIR, 'users.json')
KASSAS_FILE = os.path.join(DATA_DIR, 'kassas.json')
EXPENSES_FILE = os.path.join(DATA_DIR, 'expenses.json')
PERSONAL_EXPENSES_FILE = os.path.join(DATA_DIR, 'personal_expenses.json')
SHIFTS_FILE = os.path.join(DATA_DIR, 'shifts.json')

DATA_FILES = {
    'inventory': (INVENTORY_FILE, threading.Lock()),
    'transactions': (TRANSACTIONS_FILE, threading.Lock()),
    'users': (USERS_FILE, threading.Lock()),
    'kassas': (KASSAS_FILE, threading.Lock()),
    'expenses': (EXPENSES_FILE, threading.Lock()),
    'personal_expenses': (PERSONAL_EXPENSES_FILE, threading.Lock()),
    'shifts': (SHIFTS_FILE, threading.Lock()),
}

HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE", "YOUR_WRITE_TOKEN_HERE")
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ", "YOUR_READ_TOKEN_HERE")
REPO_ID = "Kgshop/baseai"

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

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def get_current_time():
    return datetime.now(ALMATY_TZ)

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return str(obj)
        return json.JSONEncoder.default(self, obj)

def to_decimal(value_str, default='0.00'):
    if value_str is None or value_str == '':
        return Decimal(default)
    try:
        return Decimal(str(value_str).replace(',', '.'))
    except InvalidOperation:
        logging.warning(f"Could not convert '{value_str}' to Decimal. Returned {default}.")
        return Decimal(default)
        
def load_json_data(file_key):
    filepath, lock = DATA_FILES[file_key]
    filename = os.path.basename(filepath)
    with lock:
        try:
            hf_hub_download(
                repo_id=REPO_ID, filename=filename, repo_type="dataset", token=HF_TOKEN_READ,
                local_dir=DATA_DIR, local_dir_use_symlinks=False
            )
        except HfHubHTTPError as e:
            if e.response.status_code != 404:
                logging.error(f"HTTP error downloading {filename}: {e}")
        except Exception as e:
            logging.error(f"Unknown error downloading {filename}: {e}")

        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            return []

def save_json_data(file_key, data):
    filepath, lock = DATA_FILES[file_key]
    with lock:
        try:
            temp_file = filepath + ".tmp"
            with open(temp_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=4, cls=DecimalEncoder)
            os.replace(temp_file, filepath)
        except Exception as e:
            logging.error(f"Critical error saving {filepath}: {e}", exc_info=True)

@functools.lru_cache(maxsize=1)
def get_hf_api():
    if not HF_TOKEN_WRITE or HF_TOKEN_WRITE == "YOUR_WRITE_TOKEN_HERE":
        return None
    try:
        return HfApi()
    except Exception as e:
        logging.error(f"Error initializing HfApi: {e}")
        return None

def upload_db_to_hf(file_key):
    api = get_hf_api()
    if not api:
        return
    filepath, _ = DATA_FILES[file_key]
    if not os.path.exists(filepath):
        return
    try:
        filename = os.path.basename(filepath)
        commit_time = get_current_time().strftime('%Y-%m-%d %H:%M:%S %Z%z')
        api.upload_file(
            path_or_fileobj=filepath, path_in_repo=filename, repo_id=REPO_ID, repo_type="dataset",
            token=HF_TOKEN_WRITE, commit_message=f"Automated backup {filename} {commit_time}",
            run_as_future=True
        )
    except Exception as e:
        logging.error(f"Error initiating upload of {filepath}: {e}")

def periodic_backup():
    while True:
        time.sleep(1800)
        try:
            for key in DATA_FILES.keys():
                upload_db_to_hf(key)
        except Exception as e:
            logging.error(f"Error during scheduled backup: {e}", exc_info=True)
            
def find_item_by_field(data, field, value):
    for item in data:
        if isinstance(item, dict) and str(item.get(field)) == str(value):
            return item
    return None

def find_user_by_pin(pin):
    users = load_json_data('users')
    return find_item_by_field(users, 'pin', pin)

def format_currency_py(value):
    try:
        number = to_decimal(value)
        return f"{number:,.2f}".replace(",", " ").replace(".", ",")
    except (InvalidOperation, TypeError, ValueError):
        return "0,00"

def generate_receipt_html(transaction):
    has_discounts = any(to_decimal(item.get('discount_per_item', '0')) > 0 for item in transaction.get('items', []))

    if has_discounts:
        table_headers = """
        <th style="text-align: center; width: 5%;">№</th>
        <th style="text-align: left;">Наименование</th>
        <th style="text-align: right;">Кол-во</th>
        <th style="text-align: right;">Цена</th>
        <th style="text-align: right;">Скидка</th>
        <th style="text-align: right;">Сумма</th>
        """
        total_colspan = 5
    else:
        table_headers = """
        <th style="text-align: center; width: 5%;">№</th>
        <th style="text-align: left;">Наименование</th>
        <th style="text-align: right;">Кол-во</th>
        <th style="text-align: right;">Цена</th>
        <th style="text-align: right;">Сумма</th>
        """
        total_colspan = 4

    items_html = ""
    for i, item in enumerate(transaction['items']):
        discount_cell = f"""<td style="text-align: right;">{format_currency_py(item.get('discount_per_item', '0'))}</td>""" if has_discounts else ""
        items_html += f"""
        <tr>
            <td style="text-align: center;">{i + 1}</td>
            <td>{item['name']}</td>
            <td style="text-align: right;">{item['quantity']}</td>
            <td style="text-align: right;">{format_currency_py(item['price_at_sale'])}</td>
            {discount_cell}
            <td style="text-align: right;">{format_currency_py(item['total'])}</td>
        </tr>
        """
        
    total_amount_str = format_currency_py(transaction['total_amount'])
    
    return f"""
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Накладная {transaction['id'][:8]}</title>
        <style>
            body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; margin: 0; padding: 10px; background-color: #f4f4f4; color: #333; }}
            .invoice-box {{ max-width: 800px; margin: auto; padding: 20px; border: 1px solid #eee; background: white; box-shadow: 0 0 10px rgba(0,0,0,0.15); }}
            .header {{ text-align: center; margin-bottom: 20px; }}
            .header h1 {{ margin: 0; font-size: 22px; font-weight: 600; }}
            .header p {{ margin: 2px 0; font-size: 14px; }}
            .details-grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; font-size: 14px; }}
            table {{ width: 100%; line-height: inherit; text-align: left; border-collapse: collapse; }}
            table th {{ background: #f2f2f2; font-weight: bold; padding: 8px; border-bottom: 2px solid #ddd; }}
            table td {{ padding: 8px; border-bottom: 1px solid #eee; }}
            table tr.total td {{ font-weight: bold; font-size: 1.1em; border-top: 2px solid #ddd; }}
            .footer-info {{ font-size: 14px; margin-top: 20px; }}
            @media screen and (max-width: 600px) {{
                body {{ padding: 0; }}
                .invoice-box {{ padding: 15px; box-shadow: none; border: none; }}
                .details-grid {{ grid-template-columns: 1fr; gap: 10px; }}
                table th, table td {{ font-size: 12px; padding: 5px; }}
                .header h1 {{ font-size: 18px; }}
                .header p {{ font-size: 12px; }}
                table tr.total td {{ font-size: 1em; }}
            }}
        </style>
    </head>
    <body>
        <div class="invoice-box">
            <div class="header">
                <h1>Товарная накладная № {transaction['id'][:8]}</h1>
                <p>от {datetime.fromisoformat(transaction['timestamp']).strftime('%d.%m.%Y %H:%M')}</p>
            </div>
            <table>
                <thead>
                    <tr>{table_headers}</tr>
                </thead>
                <tbody>{items_html}</tbody>
            </table>
            <table style="margin-top: 20px;">
                <tr class="total">
                    <td colspan="{total_colspan}" style="text-align: right;">Итого к оплате:</td>
                    <td style="text-align: right;">{total_amount_str} ₸</td>
                </tr>
            </table>
            <div class="footer-info">
                <p>Способ оплаты: {'Наличные' if transaction['payment_method'] == 'cash' else 'Карта'}</p>
                <p>Кассир: {transaction['user_name']}</p>
            </div>
        </div>
    </body>
    </html>
    """

def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'admin_logged_in' not in session:
            flash("Для доступа к этой странице требуется аутентификация.", "warning")
            return redirect(url_for('admin_login', next=request.url))
        return f(*args, **kwargs)
    return decorated_function

@app.context_processor
def inject_utils():
    return {'format_currency_py': format_currency_py, 'get_current_time': get_current_time, 'quote': quote}

@app.route('/')
def sales_screen():
    inventory = load_json_data('inventory')
    kassas = load_json_data('kassas')
    
    active_inventory = []
    for p in inventory:
        if isinstance(p, dict) and any(v.get('stock', 0) > 0 for v in p.get('variants', [])):
            active_inventory.append(p)

    active_inventory.sort(key=lambda x: x.get('name', '').lower())

    grouped_inventory = defaultdict(list)
    for p in active_inventory:
        first_letter = p.get('name', '#')[0].upper()
        grouped_inventory[first_letter].append(p)

    sorted_grouped_inventory = sorted(grouped_inventory.items())

    html = BASE_TEMPLATE.replace('__TITLE__', "Касса").replace('__CONTENT__', SALES_SCREEN_CONTENT).replace('__SCRIPTS__', SALES_SCREEN_SCRIPTS)
    return render_template_string(html, inventory=active_inventory, kassas=kassas, grouped_inventory=sorted_grouped_inventory)

@app.route('/inventory', methods=['GET', 'POST'])
@admin_required
def inventory_management():
    if request.method == 'POST':
        try:
            name = request.form.get('name', '').strip()
            barcode = request.form.get('barcode', '').strip()
            
            if not name or not barcode:
                flash("Название и штрих-код - обязательные поля.", "danger")
                return redirect(url_for('inventory_management'))

            inventory = load_json_data('inventory')
            if find_item_by_field(inventory, 'barcode', barcode):
                flash(f"Товар со штрих-кодом {barcode} уже существует.", "warning")
                return redirect(url_for('inventory_management'))

            variants = []
            variant_names = request.form.getlist('variant_name[]')
            variant_prices = request.form.getlist('variant_price[]')
            variant_cost_prices = request.form.getlist('variant_cost_price[]')
            variant_stocks = request.form.getlist('variant_stock[]')
            variant_image_urls = request.form.getlist('variant_image_url[]')

            for i in range(len(variant_names)):
                v_name = variant_names[i].strip()
                if not v_name: continue
                variants.append({
                    'id': uuid.uuid4().hex,
                    'option_name': "Вариант",
                    'option_value': v_name,
                    'price': str(to_decimal(variant_prices[i])),
                    'cost_price': str(to_decimal(variant_cost_prices[i])),
                    'stock': int(to_decimal(variant_stocks[i], '0')),
                    'image_url': variant_image_urls[i] if i < len(variant_image_urls) else ''
                })
            
            if not variants:
                flash("Нужно добавить хотя бы один вариант товара.", "danger")
                return redirect(url_for('inventory_management'))

            new_product = {
                'id': uuid.uuid4().hex,
                'name': name,
                'barcode': barcode,
                'variants': variants,
                'timestamp_added': get_current_time().isoformat(),
                'timestamp_updated': get_current_time().isoformat()
            }
            inventory.append(new_product)
            save_json_data('inventory', inventory)
            upload_db_to_hf('inventory')
            flash(f"Товар '{name}' успешно добавлен.", "success")
        except Exception as e:
            logging.error(f"Error adding product: {e}", exc_info=True)
            flash(f"Ошибка при добавлении товара: {e}", "danger")
        return redirect(url_for('inventory_management'))
    
    inventory_list = load_json_data('inventory')
    inventory_list.sort(key=lambda x: x.get('name', '').lower())
    
    total_units = 0
    total_cost_value = Decimal('0.00')
    total_retail_value = Decimal('0.00')

    for product in inventory_list:
        if isinstance(product, dict) and 'variants' in product:
            for variant in product.get('variants', []):
                stock = variant.get('stock', 0)
                cost_price = to_decimal(variant.get('cost_price', '0'))
                price = to_decimal(variant.get('price', '0'))
                
                total_units += stock
                total_cost_value += Decimal(stock) * cost_price
                total_retail_value += Decimal(stock) * price
    
    potential_profit = total_retail_value - total_cost_value

    inventory_summary = {
        'total_units': total_units,
        'total_cost_value': total_cost_value,
        'potential_profit': potential_profit
    }

    html = BASE_TEMPLATE.replace('__TITLE__', "Склад").replace('__CONTENT__', INVENTORY_CONTENT).replace('__SCRIPTS__', INVENTORY_SCRIPTS)
    return render_template_string(html, inventory=inventory_list, inventory_summary=inventory_summary)

@app.route('/inventory/edit/<product_id>', methods=['POST'])
@admin_required
def edit_product(product_id):
    inventory = load_json_data('inventory')
    product_found = False
    for i, product in enumerate(inventory):
        if isinstance(product, dict) and product.get('id') == product_id:
            try:
                name = request.form.get('name', '').strip()
                barcode = request.form.get('barcode', '').strip()

                if not name or not barcode:
                    flash("Название и штрих-код обязательны.", "danger")
                    return redirect(url_for('inventory_management'))

                existing_barcode = find_item_by_field(inventory, 'barcode', barcode)
                if existing_barcode and existing_barcode.get('id') != product_id:
                    flash(f"Штрих-код {barcode} уже используется другим товаром.", "warning")
                    return redirect(url_for('inventory_management'))

                inventory[i]['name'] = name
                inventory[i]['barcode'] = barcode
                
                new_variants = []
                variant_ids = request.form.getlist('variant_id[]')
                variant_names = request.form.getlist('variant_name[]')
                variant_prices = request.form.getlist('variant_price[]')
                variant_cost_prices = request.form.getlist('variant_cost_price[]')
                variant_stocks = request.form.getlist('variant_stock[]')
                variant_image_urls = request.form.getlist('variant_image_url[]')

                for j in range(len(variant_ids)):
                    v_name = variant_names[j].strip()
                    if not v_name: continue
                    new_variants.append({
                        'id': variant_ids[j] or uuid.uuid4().hex,
                        'option_name': "Вариант",
                        'option_value': v_name,
                        'price': str(to_decimal(variant_prices[j])),
                        'cost_price': str(to_decimal(variant_cost_prices[j])),
                        'stock': int(to_decimal(variant_stocks[j], '0')),
                        'image_url': variant_image_urls[j] if j < len(variant_image_urls) else ''
                    })
                
                inventory[i]['variants'] = new_variants
                inventory[i]['timestamp_updated'] = get_current_time().isoformat()
                product_found = True
                break
            except Exception as e:
                logging.error(f"Error updating product: {e}", exc_info=True)
                flash(f"Ошибка при обновлении товара: {e}", "danger")
                return redirect(url_for('inventory_management'))
    
    if product_found:
        save_json_data('inventory', inventory)
        upload_db_to_hf('inventory')
        flash("Товар успешно обновлен.", "success")
    else:
        flash("Товар не найден.", "danger")
    return redirect(url_for('inventory_management'))

@app.route('/inventory/delete/<product_id>', methods=['POST'])
@admin_required
def delete_product(product_id):
    inventory = load_json_data('inventory')
    initial_len = len(inventory)
    inventory = [p for p in inventory if not (isinstance(p, dict) and p.get('id') == product_id)]
    if len(inventory) < initial_len:
        save_json_data('inventory', inventory)
        upload_db_to_hf('inventory')
        flash("Товар удален.", "success")
    else:
        flash("Товар не найден.", "warning")
    return redirect(url_for('inventory_management'))

@app.route('/inventory/stock_in', methods=['POST'])
@admin_required
def stock_in():
    try:
        product_id = request.form.get('product_id')
        variant_id = request.form.get('variant_id')
        quantity = int(request.form.get('quantity', 0))
        cost_price_str = request.form.get('cost_price')
        delivery_cost = to_decimal(request.form.get('delivery_cost', '0'))

        if not product_id or not variant_id or quantity <= 0:
            flash("Неверные данные для оприходования.", "danger")
            return redirect(url_for('inventory_management'))

        inventory = load_json_data('inventory')
        product = find_item_by_field(inventory, 'id', product_id)
        if not product:
            flash("Товар не найден.", "danger")
            return redirect(url_for('inventory_management'))

        variant_found = False
        variant_name_for_log = ""
        for i, variant in enumerate(product.get('variants', [])):
            if variant.get('id') == variant_id:
                variant_name_for_log = variant.get('option_value', '')
                
                old_stock = variant.get('stock', 0)
                variant['stock'] = old_stock + quantity
                
                old_cost = to_decimal(variant.get('cost_price', '0'))
                new_cost = to_decimal(cost_price_str) if cost_price_str else old_cost

                if old_stock + quantity > 0:
                    avg_cost = ((old_cost * old_stock) + (new_cost * quantity) + delivery_cost) / (old_stock + quantity)
                    variant['cost_price'] = str(avg_cost.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))
                
                variant_found = True
                break

        if not variant_found:
            flash("Вариант товара не найден.", "danger")
            return redirect(url_for('inventory_management'))

        if delivery_cost > 0:
            expenses = load_json_data('expenses')
            new_expense = {
                'id': uuid.uuid4().hex,
                'timestamp': get_current_time().isoformat(),
                'amount': str(delivery_cost),
                'description': f"Дорога: {product['name']} ({variant_name_for_log})"
            }
            expenses.append(new_expense)
            save_json_data('expenses', expenses)
            upload_db_to_hf('expenses')

        product['timestamp_updated'] = get_current_time().isoformat()
        save_json_data('inventory', inventory)
        upload_db_to_hf('inventory')
        flash(f"Остаток товара '{product['name']} ({variant_name_for_log})' увеличен на {quantity}.", "success")

    except Exception as e:
        logging.error(f"Error stocking in: {e}", exc_info=True)
        flash(f"Ошибка при оприходовании: {e}", "danger")

    return redirect(url_for('inventory_management'))

@app.route('/upload_image', methods=['POST'])
@admin_required
def upload_image():
    if 'image' not in request.files:
        return jsonify({'success': False, 'message': 'No file part'}), 400
    file = request.files['image']
    if file.filename == '':
        return jsonify({'success': False, 'message': 'No selected file'}), 400
    if file:
        try:
            filename = str(uuid.uuid4()) + os.path.splitext(file.filename)[1]
            save_path = os.path.join(app.static_folder, 'product_images', filename)
            file.save(save_path)
            url = url_for('static', filename=f'product_images/{filename}')
            return jsonify({'success': True, 'url': url})
        except Exception as e:
            logging.error(f"Image upload failed: {e}", exc_info=True)
            return jsonify({'success': False, 'message': f'Server error: {e}'}), 500
    return jsonify({'success': False, 'message': 'Unknown error'}), 500

@app.route('/api/product_by_barcode/<barcode>')
def get_product_by_barcode(barcode):
    inventory = load_json_data('inventory')
    product = find_item_by_field(inventory, 'barcode', barcode)
    if product:
        active_variants = [v for v in product.get('variants', []) if v.get('stock', 0) > 0]
        if active_variants:
            product_copy = product.copy()
            product_copy['variants'] = active_variants
            return jsonify({'success': True, 'product': product_copy})
        else:
            return jsonify({'success': False, 'message': 'Товар закончился на складе'}), 404
    return jsonify({'success': False, 'message': 'Товар не найден'}), 404

@app.route('/api/complete_sale', methods=['POST'])
def complete_sale():
    try:
        data = request.get_json()
        cart = data.get('cart', {})
        user_id = data.get('userId')
        kassa_id = data.get('kassaId')
        shift_id = data.get('shiftId')
        payment_method = data.get('paymentMethod', 'cash')

        if not cart or not user_id or not kassa_id or not shift_id:
            return jsonify({'success': False, 'message': 'Неполные данные для продажи. Начните смену.'}), 400

        inventory = load_json_data('inventory')
        users = load_json_data('users')
        kassas = load_json_data('kassas')
        
        user = find_item_by_field(users, 'id', user_id)
        kassa = find_item_by_field(kassas, 'id', kassa_id)

        if not user or not kassa:
            return jsonify({'success': False, 'message': 'Кассир или касса не найдены.'}), 404

        sale_items = []
        total_amount = Decimal('0.00')
        inventory_updates = {}

        for item_id, cart_item in cart.items():
            if cart_item.get('isCustom'):
                price_at_sale = to_decimal(cart_item.get('price', '0'))
                quantity_sold = cart_item.get('quantity', 1)
                item_total = price_at_sale * Decimal(quantity_sold)
                total_amount += item_total
                sale_items.append({
                    'product_id': None,
                    'variant_id': item_id,
                    'name': cart_item.get('productName', 'Товар без штрихкода'),
                    'barcode': 'CUSTOM',
                    'quantity': quantity_sold,
                    'price_at_sale': str(price_at_sale),
                    'cost_price_at_sale': '0.00',
                    'discount_per_item': '0.00',
                    'total': str(item_total),
                    'is_custom': True
                })
                continue
            
            variant_id = item_id
            product = find_item_by_field(inventory, 'id', cart_item['productId'])
            if not product:
                return jsonify({'success': False, 'message': f"Товар с ID {cart_item['productId']} не найден."}), 404
            
            variant = find_item_by_field(product.get('variants', []), 'id', variant_id)
            if not variant:
                 return jsonify({'success': False, 'message': f"Вариант товара с ID {variant_id} не найден."}), 404
            
            quantity_sold = cart_item['quantity']
            current_stock = variant.get('stock', 0)

            if quantity_sold > current_stock:
                return jsonify({'success': False, 'message': f"Недостаточно товара '{product['name']} ({variant['option_value']})'. В наличии: {current_stock}"}), 400

            price_at_sale = to_decimal(variant.get('price', '0'))
            cost_price_at_sale = to_decimal(variant.get('cost_price', '0'))
            discount_per_item = to_decimal(cart_item.get('discount', '0'))

            if discount_per_item > price_at_sale:
                return jsonify({'success': False, 'message': f"Скидка на '{product['name']}' не может быть больше цены."}), 400

            final_price = price_at_sale - discount_per_item
            item_total = final_price * Decimal(quantity_sold)
            total_amount += item_total

            sale_items.append({
                'product_id': product['id'],
                'variant_id': variant_id,
                'name': f"{product['name']} ({variant['option_value']})",
                'barcode': product.get('barcode'),
                'quantity': quantity_sold,
                'price_at_sale': str(price_at_sale),
                'cost_price_at_sale': str(cost_price_at_sale),
                'discount_per_item': str(discount_per_item),
                'total': str(item_total)
            })
            inventory_updates[variant_id] = {'product_id': product['id'], 'new_stock': current_stock - quantity_sold}

        now_iso = get_current_time().isoformat()
        
        new_transaction = {
            'id': uuid.uuid4().hex,
            'timestamp': now_iso,
            'type': 'sale',
            'status': 'completed',
            'original_transaction_id': None,
            'user_id': user_id,
            'user_name': user.get('name', 'N/A'),
            'kassa_id': kassa_id,
            'kassa_name': kassa.get('name', 'N/A'),
            'shift_id': shift_id,
            'items': sale_items,
            'total_amount': str(total_amount),
            'payment_method': payment_method
        }
        
        new_transaction['invoice_html'] = generate_receipt_html(new_transaction)
        transactions = load_json_data('transactions')
        transactions.append(new_transaction)

        for variant_id, update_info in inventory_updates.items():
            for p in inventory:
                if p.get('id') == update_info['product_id']:
                    for v in p.get('variants', []):
                        if v.get('id') == variant_id:
                            v['stock'] = update_info['new_stock']
                            p['timestamp_updated'] = now_iso
                            break
                    break

        if payment_method == 'cash':
            for i, k in enumerate(kassas):
                if k.get('id') == kassa_id:
                    current_balance = to_decimal(k.get('balance', '0'))
                    kassas[i]['balance'] = str(current_balance + total_amount)
                    if 'history' not in kassas[i] or not isinstance(kassas[i]['history'], list):
                        kassas[i]['history'] = []
                    kassas[i]['history'].append({
                        'type': 'sale',
                        'amount': str(total_amount),
                        'timestamp': now_iso,
                        'transaction_id': new_transaction['id']
                    })
                    break

        save_json_data('transactions', transactions)
        save_json_data('inventory', inventory)
        save_json_data('kassas', kassas)
        
        upload_db_to_hf('transactions')
        upload_db_to_hf('inventory')
        upload_db_to_hf('kassas')

        receipt_url = url_for('view_receipt', transaction_id=new_transaction['id'], _external=True)
        return jsonify({
            'success': True, 
            'message': 'Продажа успешно зарегистрирована.', 
            'transactionId': new_transaction['id'],
            'receiptUrl': receipt_url
        })

    except Exception as e:
        logging.error(f"Error completing sale: {e}", exc_info=True)
        return jsonify({'success': False, 'message': f'Внутренняя ошибка сервера: {e}'}), 500

@app.route('/receipt/<transaction_id>')
def view_receipt(transaction_id):
    transactions = load_json_data('transactions')
    transaction = find_item_by_field(transactions, 'id', transaction_id)
    if transaction and 'invoice_html' in transaction:
        return Response(transaction['invoice_html'], mimetype='text/html')
    # Fallback to old key for compatibility
    if transaction and 'receipt_html' in transaction:
        return Response(transaction['receipt_html'], mimetype='text/html')
    abort(404, description="Накладная не найдена")

@app.route('/transactions')
@admin_required
def transaction_history():
    selected_date_str = request.args.get('date', get_current_time().strftime('%Y-%m-%d'))
    selected_kassa_id = request.args.get('kassa', '')
    try:
        selected_date = datetime.strptime(selected_date_str, '%Y-%m-%d').date()
    except ValueError:
        selected_date = get_current_time().date()
        selected_date_str = selected_date.strftime('%Y-%m-%d')
    
    transactions = load_json_data('transactions')
    kassas = load_json_data('kassas')
    
    filtered_transactions = [
        t for t in transactions 
        if datetime.fromisoformat(t['timestamp']).date() == selected_date
    ]
    
    if selected_kassa_id:
        filtered_transactions = [
            t for t in filtered_transactions
            if t.get('kassa_id') == selected_kassa_id
        ]
    
    total_sales = sum(to_decimal(t['total_amount']) for t in filtered_transactions if t.get('type') == 'sale')
    
    total_quantity_sold = 0
    for t in filtered_transactions:
        if t.get('type') == 'sale':
            for item in t.get('items', []):
                total_quantity_sold += int(item.get('quantity', 0))
    
    filtered_transactions.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
    
    html = BASE_TEMPLATE.replace('__TITLE__', "История транзакций").replace('__CONTENT__', TRANSACTIONS_CONTENT).replace('__SCRIPTS__', TRANSACTIONS_SCRIPTS)
    return render_template_string(html, transactions=filtered_transactions, total_sales=total_sales, total_quantity_sold=total_quantity_sold, selected_date=selected_date_str, kassas=kassas, selected_kassa_id=selected_kassa_id)

@app.route('/admin/transaction/edit/<transaction_id>', methods=['POST'])
@admin_required
def edit_transaction(transaction_id):
    try:
        data = request.get_json()
        items_update = data.get('items', [])
        
        transactions = load_json_data('transactions')
        kassas = load_json_data('kassas')
        
        transaction_index = -1
        for i, t in enumerate(transactions):
            if t.get('id') == transaction_id:
                transaction_index = i
                break
        
        if transaction_index == -1:
            return jsonify({'success': False, 'message': 'Транзакция не найдена'}), 404
        
        original_transaction = transactions[transaction_index]
        old_total_amount = to_decimal(original_transaction['total_amount'])
        
        new_total_amount = Decimal('0.00')
        updated_items = []
        
        for item in original_transaction['items']:
            item_id = item.get('variant_id') or item.get('product_id') 
            update_data = find_item_by_field(items_update, 'id', item_id)
            
            if update_data:
                new_price = to_decimal(update_data.get('price', item['price_at_sale']))
                new_discount = to_decimal(update_data.get('discount', item.get('discount_per_item', '0')))
                
                item['price_at_sale'] = str(new_price)
                item['discount_per_item'] = str(new_discount)
                item_total = (new_price - new_discount) * Decimal(item['quantity'])
                item['total'] = str(item_total)
            
            new_total_amount += to_decimal(item['total'])
        
        transactions[transaction_index]['total_amount'] = str(new_total_amount)
        
        if 'edits' not in transactions[transaction_index]:
            transactions[transaction_index]['edits'] = []
            
        transactions[transaction_index]['edits'].append({
            'timestamp': get_current_time().isoformat(),
            'admin_user': session.get('admin_username', 'admin'),
            'old_total': str(old_total_amount),
            'new_total': str(new_total_amount)
        })

        transactions[transaction_index]['invoice_html'] = generate_receipt_html(transactions[transaction_index])

        amount_diff = new_total_amount - old_total_amount
        if amount_diff != Decimal(0) and original_transaction['payment_method'] == 'cash':
            kassa_id = original_transaction.get('kassa_id')
            for i, k in enumerate(kassas):
                if k.get('id') == kassa_id:
                    k['balance'] = str(to_decimal(k.get('balance', '0')) + amount_diff)
                    k.setdefault('history', []).append({
                        'type': 'correction',
                        'amount': str(amount_diff),
                        'timestamp': get_current_time().isoformat(),
                        'description': f"Корректировка транзакции {transaction_id[:8]}"
                    })
                    break
            save_json_data('kassas', kassas)
            upload_db_to_hf('kassas')

        save_json_data('transactions', transactions)
        upload_db_to_hf('transactions')
        
        flash("Транзакция успешно обновлена.", "success")
        return jsonify({'success': True, 'message': 'Транзакция обновлена'})
    except Exception as e:
        logging.error(f"Error editing transaction: {e}", exc_info=True)
        return jsonify({'success': False, 'message': f'Внутренняя ошибка: {e}'}), 500

@app.route('/admin/transaction/delete/<transaction_id>', methods=['POST'])
@admin_required
def delete_transaction(transaction_id):
    transactions = load_json_data('transactions')
    inventory = load_json_data('inventory')
    kassas = load_json_data('kassas')

    transaction_to_delete = find_item_by_field(transactions, 'id', transaction_id)
    if not transaction_to_delete:
        flash("Транзакция не найдена.", "danger")
        return redirect(url_for('transaction_history'))

    for item in transaction_to_delete.get('items', []):
        if item.get('is_custom'):
            continue
        
        product = find_item_by_field(inventory, 'id', item.get('product_id'))
        if not product: continue
        
        variant = find_item_by_field(product.get('variants', []), 'id', item.get('variant_id'))
        if not variant: continue

        quantity_change = item.get('quantity', 0)
        
        if transaction_to_delete.get('type') == 'sale':
            variant['stock'] = variant.get('stock', 0) + quantity_change
        elif transaction_to_delete.get('type') == 'return':
             variant['stock'] = variant.get('stock', 0) - quantity_change

    if transaction_to_delete.get('payment_method') == 'cash':
        kassa = find_item_by_field(kassas, 'id', transaction_to_delete.get('kassa_id'))
        if kassa:
            current_balance = to_decimal(kassa.get('balance', '0'))
            amount_change = to_decimal(transaction_to_delete.get('total_amount'))
            
            kassa['balance'] = str(current_balance - amount_change)
            
            kassa.setdefault('history', []).append({
                'type': 'deletion',
                'amount': str(-amount_change),
                'timestamp': get_current_time().isoformat(),
                'description': f"Удаление транзакции {transaction_id[:8]}"
            })

    transactions = [t for t in transactions if t.get('id') != transaction_id]
    
    if transaction_to_delete.get('type') == 'return':
        original_id = transaction_to_delete.get('original_transaction_id')
        if original_id:
            for i, t in enumerate(transactions):
                if t.get('id') == original_id:
                    transactions[i]['status'] = 'completed'
                    break

    save_json_data('inventory', inventory)
    save_json_data('kassas', kassas)
    save_json_data('transactions', transactions)
    
    upload_db_to_hf('inventory')
    upload_db_to_hf('kassas')
    upload_db_to_hf('transactions')
    
    flash("Транзакция успешно удалена.", "success")
    return redirect(url_for('transaction_history'))

@app.route('/reports')
@admin_required
def reports():
    today = get_current_time().date()
    start_date_str = request.args.get('start_date', (today.replace(day=1)).strftime('%Y-%m-%d'))
    end_date_str = request.args.get('end_date', (today).strftime('%Y-%m-%d'))

    start_date = datetime.strptime(start_date_str, '%Y-%m-%d').replace(tzinfo=ALMATY_TZ)
    end_date = (datetime.strptime(end_date_str, '%Y-%m-%d') + timedelta(days=1)).replace(tzinfo=ALMATY_TZ)
    num_days = (end_date - start_date).days

    transactions = load_json_data('transactions')
    expenses = load_json_data('expenses')
    personal_expenses = load_json_data('personal_expenses')
    users = load_json_data('users')

    filtered_transactions = [
        t for t in transactions 
        if start_date <= datetime.fromisoformat(t['timestamp']) < end_date
    ]
    filtered_expenses = [
        e for e in expenses 
        if start_date <= datetime.fromisoformat(e['timestamp']) < end_date
    ]
    filtered_personal_expenses = [
        e for e in personal_expenses 
        if start_date <= datetime.fromisoformat(e['timestamp']) < end_date
    ]
    
    total_revenue = sum(to_decimal(t['total_amount']) for t in filtered_transactions)
    total_cogs = sum(
        to_decimal(item.get('cost_price_at_sale', '0')) * to_decimal(str(item['quantity']))
        for t in filtered_transactions for item in t['items']
    )
    gross_profit = total_revenue - total_cogs
    total_expenses = sum(to_decimal(e['amount']) for e in filtered_expenses)
    total_personal_expenses = sum(to_decimal(e['amount']) for e in filtered_personal_expenses)
    
    sales_by_cashier = defaultdict(lambda: {'count': 0, 'total': Decimal(0)})
    for t in filtered_transactions:
        if t.get('type') == 'sale':
            cashier_name = t.get('user_name', 'Неизвестный')
            sales_by_cashier[cashier_name]['count'] += 1
            sales_by_cashier[cashier_name]['total'] += to_decimal(t['total_amount'])
        elif t.get('type') == 'return':
            cashier_name = t.get('user_name', 'Неизвестный')
            sales_by_cashier[cashier_name]['count'] -= 1
            sales_by_cashier[cashier_name]['total'] += to_decimal(t['total_amount'])

    cashier_payouts = defaultdict(Decimal)
    for t in filtered_transactions:
        if t.get('type') != 'sale': continue
        user = find_item_by_field(users, 'id', t.get('user_id'))
        if user:
            payment_type = user.get('payment_type')
            payment_value = to_decimal(user.get('payment_value', '0'))
            if payment_type == 'percentage' and payment_value > 0:
                payout = to_decimal(t['total_amount']) * (payment_value / Decimal(100))
                cashier_payouts[user['name']] += payout

    for user in users:
        if user.get('payment_type') == 'salary':
            monthly_salary = to_decimal(user.get('payment_value', '0'))
            if monthly_salary > 0:
                daily_salary = monthly_salary / Decimal(30) 
                period_salary = daily_salary * Decimal(num_days)
                cashier_payouts[user['name']] += period_salary

    total_salary_expenses = sum(cashier_payouts.values())
    net_profit = gross_profit - total_expenses - total_personal_expenses - total_salary_expenses
    
    stats = {
        'total_revenue': total_revenue,
        'total_cogs': total_cogs,
        'gross_profit': gross_profit,
        'total_expenses': total_expenses,
        'total_personal_expenses': total_personal_expenses,
        'total_salary_expenses': total_salary_expenses,
        'net_profit': net_profit,
        'sales_by_cashier': sorted(sales_by_cashier.items(), key=lambda item: item[1]['total'], reverse=True),
        'cashier_payouts': sorted(cashier_payouts.items(), key=lambda item: item[1], reverse=True)
    }

    filtered_expenses.sort(key=lambda x: x['timestamp'], reverse=True)
    filtered_personal_expenses.sort(key=lambda x: x['timestamp'], reverse=True)

    html = BASE_TEMPLATE.replace('__TITLE__', "Отчеты").replace('__CONTENT__', REPORTS_CONTENT).replace('__SCRIPTS__', REPORTS_SCRIPTS)
    return render_template_string(html, stats=stats, start_date=start_date_str, end_date=end_date_str, expenses=filtered_expenses, personal_expenses=filtered_personal_expenses)

@app.route('/reports/product_roi')
@admin_required
def product_roi_report():
    inventory = load_json_data('inventory')
    transactions = load_json_data('transactions')

    product_stats = []

    for product in inventory:
        for variant in product.get('variants', []):
            total_revenue = Decimal('0.00')
            total_cogs = Decimal('0.00')
            total_qty_sold = 0

            for t in transactions:
                if t['type'] in ['sale', 'return']:
                    for item in t['items']:
                        if item.get('variant_id') == variant['id']:
                            total_revenue += to_decimal(item['total'])
                            total_cogs += to_decimal(item.get('cost_price_at_sale', '0')) * to_decimal(str(item['quantity']))
                            if t['type'] == 'sale':
                                total_qty_sold += item['quantity']
                            elif t['type'] == 'return':
                                total_qty_sold -= item['quantity']

            current_stock = to_decimal(str(variant.get('stock', 0)))
            cost_price = to_decimal(variant.get('cost_price', '0'))
            
            inventory_value = current_stock * cost_price
            
            total_investment = total_cogs + inventory_value 
            payback = total_revenue - total_investment

            product_stats.append({
                'name': product['name'],
                'variant_name': variant['option_value'],
                'total_qty_sold': total_qty_sold,
                'total_revenue': total_revenue,
                'total_investment': total_investment,
                'inventory_value': inventory_value,
                'payback': payback
            })

    product_stats.sort(key=lambda x: x['payback'], reverse=True)
    html = BASE_TEMPLATE.replace('__TITLE__', "Отчет по окупаемости товаров").replace('__CONTENT__', PRODUCT_ROI_CONTENT).replace('__SCRIPTS__', '')
    return render_template_string(html, stats=product_stats)

@app.route('/admin', methods=['GET'])
@admin_required
def admin_panel():
    users = load_json_data('users')
    kassas = load_json_data('kassas')
    expenses = load_json_data('expenses')
    personal_expenses = load_json_data('personal_expenses')
    expenses.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
    personal_expenses.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
    html = BASE_TEMPLATE.replace('__TITLE__', "Админ-панель").replace('__CONTENT__', ADMIN_CONTENT).replace('__SCRIPTS__', ADMIN_SCRIPTS)
    return render_template_string(html, users=users, kassas=kassas, expenses=expenses, personal_expenses=personal_expenses)

@app.route('/admin/shifts')
@admin_required
def admin_shifts():
    shifts = load_json_data('shifts')
    shifts.sort(key=lambda x: x.get('start_time', ''), reverse=True)
    html = BASE_TEMPLATE.replace('__TITLE__', "История смен").replace('__CONTENT__', SHIFTS_CONTENT)
    return render_template_string(html, shifts=shifts)

@app.route('/admin/user', methods=['POST'])
@admin_required
def manage_user():
    action = request.form.get('action')
    users = load_json_data('users')
    
    if action == 'add':
        name = request.form.get('name', '').strip()
        pin = request.form.get('pin', '').strip()
        payment_type = request.form.get('payment_type')
        payment_value = to_decimal(request.form.get('payment_value', '0'))
        if name and pin and pin.isdigit() and payment_type:
            new_user = {
                'id': uuid.uuid4().hex, 'name': name, 'pin': pin,
                'payment_type': payment_type, 'payment_value': str(payment_value)
            }
            users.append(new_user)
            flash(f"Кассир '{name}' добавлен.", "success")
        else:
            flash("Все поля обязательны.", "danger")
    
    elif action == 'edit':
        user_id = request.form.get('id')
        user = find_item_by_field(users, 'id', user_id)
        if user:
            user['name'] = request.form.get('name', '').strip()
            user['pin'] = request.form.get('pin', '').strip()
            user['payment_type'] = request.form.get('payment_type')
            user['payment_value'] = str(to_decimal(request.form.get('payment_value', '0')))
            flash(f"Данные кассира '{user['name']}' обновлены.", "success")
        else:
            flash("Кассир не найден.", "warning")

    elif action == 'delete':
        user_id = request.form.get('id')
        initial_len = len(users)
        users = [u for u in users if u.get('id') != user_id]
        if len(users) < initial_len:
            flash("Кассир удален.", "success")
        else:
            flash("Кассир не найден.", "warning")

    save_json_data('users', users)
    upload_db_to_hf('users')
    return redirect(url_for('admin_panel'))

@app.route('/admin/kassa', methods=['POST'])
@admin_required
def manage_kassa():
    action = request.form.get('action')
    kassas = load_json_data('kassas')
    
    if action == 'add':
        name = request.form.get('name', '').strip()
        balance = to_decimal(request.form.get('balance', '0'))
        if name:
            new_kassa = {
                'id': uuid.uuid4().hex,
                'name': name,
                'balance': str(balance),
                'history': []
            }
            if balance > 0:
                new_kassa['history'].append({
                    'type': 'deposit',
                    'amount': str(balance),
                    'timestamp': get_current_time().isoformat(),
                    'description': 'Начальный баланс'
                })
            kassas.append(new_kassa)
            flash(f"Касса '{name}' добавлена.", "success")
        else:
            flash("Название кассы обязательно.", "danger")

    elif action == 'delete':
        kassa_id = request.form.get('id')
        initial_len = len(kassas)
        kassas = [k for k in kassas if k.get('id') != kassa_id]
        if len(kassas) < initial_len:
            flash("Касса удалена.", "success")
        else:
            flash("Касса не найдена.", "warning")
            
    save_json_data('kassas', kassas)
    upload_db_to_hf('kassas')
    return redirect(url_for('admin_panel'))

@app.route('/admin/kassa_op', methods=['POST'])
@admin_required
def kassa_operation():
    kassa_id = request.form.get('kassa_id')
    op_type = request.form.get('op_type')
    amount = to_decimal(request.form.get('amount', '0'))
    description = request.form.get('description', '').strip()
    
    if not kassa_id or not op_type or amount <= 0:
        flash("Выберите кассу, тип операции и укажите положительную сумму.", "danger")
        return redirect(url_for('admin_panel'))
    
    kassas = load_json_data('kassas')
    kassa_found = False
    for i, kassa in enumerate(kassas):
        if kassa.get('id') == kassa_id:
            current_balance = to_decimal(kassa.get('balance', '0'))
            new_balance = current_balance
            
            if op_type == 'deposit':
                new_balance += amount
            elif op_type == 'withdrawal':
                if amount > current_balance:
                    flash("Сумма изъятия превышает баланс кассы.", "danger")
                    return redirect(url_for('admin_panel'))
                new_balance -= amount
            
            kassas[i]['balance'] = str(new_balance)
            if 'history' not in kassas[i]: kassas[i]['history'] = []
            kassas[i]['history'].append({
                'type': op_type,
                'amount': str(amount),
                'timestamp': get_current_time().isoformat(),
                'description': description or f"{'Внесение' if op_type == 'deposit' else 'Изъятие'} средств"
            })
            kassa_found = True
            break
            
    if kassa_found:
        save_json_data('kassas', kassas)
        upload_db_to_hf('kassas')
        flash("Операция по кассе успешно проведена.", "success")
    else:
        flash("Касса не найдена.", "danger")
        
    return redirect(url_for('admin_panel'))
    
@app.route('/admin/expense', methods=['POST'])
@admin_required
def manage_expense():
    amount = to_decimal(request.form.get('amount', '0'))
    description = request.form.get('description', '').strip()

    if amount <= 0 or not description:
        flash("Укажите положительную сумму и описание расхода.", "danger")
        return redirect(url_for('admin_panel'))

    new_expense = {
        'id': uuid.uuid4().hex,
        'timestamp': get_current_time().isoformat(),
        'amount': str(amount),
        'description': description
    }
    expenses = load_json_data('expenses')
    expenses.append(new_expense)
    save_json_data('expenses', expenses)
    upload_db_to_hf('expenses')
    flash("Расход успешно добавлен.", "success")
    return redirect(url_for('admin_panel'))

@app.route('/admin/expense/delete/<expense_id>', methods=['POST'])
@admin_required
def delete_expense(expense_id):
    expenses = load_json_data('expenses')
    initial_len = len(expenses)
    expenses = [e for e in expenses if e.get('id') != expense_id]
    if len(expenses) < initial_len:
        save_json_data('expenses', expenses)
        upload_db_to_hf('expenses')
        flash("Расход удален.", "success")
    else:
        flash("Расход не найден.", "warning")
    return redirect(url_for('admin_panel'))

@app.route('/admin/personal_expense', methods=['POST'])
@admin_required
def manage_personal_expense():
    amount = to_decimal(request.form.get('amount', '0'))
    description = request.form.get('description', '').strip()

    if amount <= 0 or not description:
        flash("Укажите положительную сумму и описание личного расхода.", "danger")
        return redirect(url_for('admin_panel'))

    new_expense = {
        'id': uuid.uuid4().hex,
        'timestamp': get_current_time().isoformat(),
        'amount': str(amount),
        'description': description
    }
    expenses = load_json_data('personal_expenses')
    expenses.append(new_expense)
    save_json_data('personal_expenses', expenses)
    upload_db_to_hf('personal_expenses')
    flash("Личный расход успешно добавлен.", "success")
    return redirect(url_for('admin_panel'))

@app.route('/admin/personal_expense/delete/<expense_id>', methods=['POST'])
@admin_required
def delete_personal_expense(expense_id):
    expenses = load_json_data('personal_expenses')
    initial_len = len(expenses)
    expenses = [e for e in expenses if e.get('id') != expense_id]
    if len(expenses) < initial_len:
        save_json_data('personal_expenses', expenses)
        upload_db_to_hf('personal_expenses')
        flash("Личный расход удален.", "success")
    else:
        flash("Личный расход не найден.", "warning")
    return redirect(url_for('admin_panel'))

@app.route('/cashier_login', methods=['GET', 'POST'])
def cashier_login():
    if request.method == 'POST':
        pin = request.form.get('pin')
        user = find_user_by_pin(pin)
        if user:
            return redirect(url_for('cashier_dashboard', user_id=user['id']))
        else:
            flash("Неверный ПИН-код.", "danger")
    html = BASE_TEMPLATE.replace('__TITLE__', "Вход для кассира").replace('__CONTENT__', CASHIER_LOGIN_CONTENT).replace('__SCRIPTS__', '')
    return render_template_string(html)

@app.route('/api/verify_pin', methods=['POST'])
def verify_pin():
    pin = request.json.get('pin')
    user = find_user_by_pin(pin)
    if user:
        return jsonify({'success': True, 'user': {'id': user['id'], 'name': user['name']}})
    else:
        return jsonify({'success': False, 'message': 'Неверный ПИН-код'}), 401

@app.route('/api/shift/start', methods=['POST'])
def start_shift():
    data = request.json
    user_id = data.get('userId')
    kassa_id = data.get('kassaId')
    
    if not user_id:
        return jsonify({'success': False, 'message': 'Missing user ID'}), 400
        
    shifts = load_json_data('shifts')
    open_shift = next((s for s in shifts if s.get('user_id') == user_id and s.get('end_time') is None), None)
    if open_shift:
        return jsonify({'success': True, 'shift': open_shift})

    if not kassa_id:
        return jsonify({'success': False, 'message': 'Выберите кассу для начала новой смены'}), 400

    users = load_json_data('users')
    kassas = load_json_data('kassas')
    user = find_item_by_field(users, 'id', user_id)
    kassa = find_item_by_field(kassas, 'id', kassa_id)

    if not user or not kassa:
        return jsonify({'success': False, 'message': 'Кассир или касса не найдены'}), 404

    new_shift = {
        'id': uuid.uuid4().hex,
        'user_id': user_id,
        'user_name': user['name'],
        'kassa_id': kassa_id,
        'kassa_name': kassa['name'],
        'start_time': get_current_time().isoformat(),
        'start_balance': kassa.get('balance', '0'),
        'end_time': None
    }
    shifts.append(new_shift)
    save_json_data('shifts', shifts)
    upload_db_to_hf('shifts')
    return jsonify({'success': True, 'shift': new_shift})

@app.route('/api/shift/end', methods=['POST'])
def end_shift():
    data = request.json
    shift_id = data.get('shiftId')
    if not shift_id:
        return jsonify({'success': False, 'message': 'Missing shift ID'}), 400

    shifts = load_json_data('shifts')
    kassas = load_json_data('kassas')
    transactions = load_json_data('transactions')
    
    shift_found = False
    for i, shift in enumerate(shifts):
        if shift.get('id') == shift_id:
            if shift.get('end_time'):
                return jsonify({'success': False, 'message': 'Смена уже закрыта'}), 400
            
            shift['end_time'] = get_current_time().isoformat()
            
            kassa = find_item_by_field(kassas, 'id', shift['kassa_id'])
            shift['end_balance'] = kassa.get('balance', '0') if kassa else '0'

            shift_transactions = [
                t for t in transactions 
                if t.get('shift_id') == shift_id and datetime.fromisoformat(t['timestamp']) >= datetime.fromisoformat(shift['start_time'])
            ]
            
            cash_sales = sum(to_decimal(t['total_amount']) for t in shift_transactions if t['type'] == 'sale' and t['payment_method'] == 'cash')
            card_sales = sum(to_decimal(t['total_amount']) for t in shift_transactions if t['type'] == 'sale' and t['payment_method'] == 'card')
            
            shift['cash_sales'] = str(cash_sales)
            shift['card_sales'] = str(card_sales)
            shift['total_sales'] = str(cash_sales + card_sales)
            
            shifts[i] = shift
            shift_found = True
            break
    
    if not shift_found:
        return jsonify({'success': False, 'message': 'Смена не найдена'}), 404
        
    save_json_data('shifts', shifts)
    upload_db_to_hf('shifts')
    return jsonify({'success': True, 'message': 'Смена успешно закрыта'})

@app.route('/cashier_dashboard/<user_id>')
def cashier_dashboard(user_id):
    users = load_json_data('users')
    user = find_item_by_field(users, 'id', user_id)
    if not user:
        abort(404, "Кассир не найден")
    
    transactions = load_json_data('transactions')
    user_transactions = [t for t in transactions if t.get('user_id') == user_id]
    user_transactions.sort(key=lambda x: x['timestamp'], reverse=True)
    
    html = BASE_TEMPLATE.replace('__TITLE__', f"Продажи кассира: {user['name']}").replace('__CONTENT__', CASHIER_DASHBOARD_CONTENT).replace('__SCRIPTS__', '')
    return render_template_string(html, user=user, transactions=user_transactions)

@app.route('/return_transaction/<transaction_id>', methods=['POST'])
def return_transaction(transaction_id):
    cashier_id = request.form.get('cashier_id')
    if not cashier_id:
        flash("Не удалось определить кассира для оформления возврата.", "danger")
        return redirect(url_for('cashier_login'))

    transactions = load_json_data('transactions')
    inventory = load_json_data('inventory')
    kassas = load_json_data('kassas')
    
    original_transaction = find_item_by_field(transactions, 'id', transaction_id)

    if not original_transaction:
        flash("Оригинальная транзакция не найдена.", "danger")
        return redirect(url_for('cashier_dashboard', user_id=cashier_id))
    if original_transaction.get('status') == 'returned':
        flash("Эта продажа уже была возвращена.", "warning")
        return redirect(url_for('cashier_dashboard', user_id=cashier_id))

    total_amount = to_decimal(original_transaction['total_amount'])
    
    return_items = []
    inventory_updates = {}
    for item in original_transaction['items']:
        return_items.append({**item, 'quantity': -item['quantity'], 'total': str(-to_decimal(item['total']))})
        if not item.get('is_custom'):
            product = find_item_by_field(inventory, 'id', item['product_id'])
            if product:
                variant = find_item_by_field(product.get('variants', []), 'id', item['variant_id'])
                if variant:
                    inventory_updates[item['variant_id']] = {'product_id': item['product_id'], 'new_stock': variant.get('stock', 0) + item['quantity']}


    now_iso = get_current_time().isoformat()
    return_transaction = {
        'id': uuid.uuid4().hex,
        'timestamp': now_iso,
        'type': 'return',
        'status': 'completed',
        'original_transaction_id': transaction_id,
        'user_id': original_transaction['user_id'],
        'user_name': original_transaction['user_name'],
        'kassa_id': original_transaction['kassa_id'],
        'kassa_name': original_transaction['kassa_name'],
        'shift_id': original_transaction.get('shift_id'),
        'items': return_items,
        'total_amount': str(-total_amount),
        'payment_method': original_transaction['payment_method']
    }
    transactions.append(return_transaction)

    for i, t in enumerate(transactions):
        if t['id'] == transaction_id:
            transactions[i]['status'] = 'returned'
            break

    for variant_id, update_info in inventory_updates.items():
        for p in inventory:
            if p.get('id') == update_info['product_id']:
                for v in p.get('variants', []):
                    if v.get('id') == variant_id:
                        v['stock'] = update_info['new_stock']
                        p['timestamp_updated'] = now_iso
                        break
                break
    
    if original_transaction['payment_method'] == 'cash':
        for i, k in enumerate(kassas):
            if k['id'] == original_transaction['kassa_id']:
                current_balance = to_decimal(k.get('balance', '0'))
                kassas[i]['balance'] = str(current_balance - total_amount)
                kassas[i].setdefault('history', []).append({
                    'type': 'return', 'amount': str(-total_amount), 'timestamp': now_iso,
                    'transaction_id': return_transaction['id']
                })
                break
                
    save_json_data('transactions', transactions)
    save_json_data('inventory', inventory)
    save_json_data('kassas', kassas)
    upload_db_to_hf('transactions')
    upload_db_to_hf('inventory')
    upload_db_to_hf('kassas')
    
    flash("Возврат успешно оформлен.", "success")
    return redirect(url_for('cashier_dashboard', user_id=cashier_id))

@app.route('/backup', methods=['POST'])
@admin_required
def backup_hf():
    try:
        for key in DATA_FILES.keys():
            upload_db_to_hf(key)
        flash(f"Резервное копирование {len(DATA_FILES)} файлов инициировано.", "success")
    except Exception as e:
        flash(f"Ошибка при резервном копировании: {e}", "danger")
    return redirect(url_for('admin_panel'))

@app.route('/download', methods=['GET'])
@admin_required
def download_hf():
    errors = []
    success_count = 0
    for key in DATA_FILES.keys():
        filepath, _ = DATA_FILES[key]
        filename = os.path.basename(filepath)
        try:
            hf_hub_download(
                repo_id=REPO_ID, filename=filename, repo_type="dataset", token=HF_TOKEN_READ,
                local_dir=DATA_DIR, local_dir_use_symlinks=False, force_download=True,
            )
            success_count += 1
        except Exception as e:
            errors.append(f"Ошибка загрузки {filename}: {e}")
    if success_count > 0:
        flash(f"Успешно загружено {success_count} файлов. Данные перезаписаны.", "success")
    if errors:
        flash("Произошли ошибки: " + "; ".join(errors), "danger")
    return redirect(url_for('admin_panel'))

@app.route('/admin_login', methods=['GET', 'POST'])
def admin_login():
    if request.method == 'POST':
        password = request.form.get('password')
        if password == ADMIN_PASS:
            session['admin_logged_in'] = True
            session.permanent = True
            next_url = request.args.get('next')
            flash("Вы успешно вошли в систему.", "success")
            return redirect(next_url or url_for('admin_panel'))
        else:
            flash("Неверный пароль.", "danger")
    html = BASE_TEMPLATE.replace('__TITLE__', "Вход для администратора").replace('__CONTENT__', ADMIN_LOGIN_CONTENT).replace('__SCRIPTS__', '')
    return render_template_string(html)

@app.route('/admin_logout')
def admin_logout():
    session.pop('admin_logged_in', None)
    flash("Вы вышли из системы.", "info")
    return redirect(url_for('sales_screen'))

BASE_TEMPLATE = """
<!DOCTYPE html>
<html lang="ru" data-bs-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>__TITLE__ - POS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        :root { --sidebar-width: 250px; }
        body { background-color: #f8f9fa; }
        .sidebar { position: fixed; top: 0; left: 0; width: var(--sidebar-width); height: 100vh; background-color: #343a40; padding-top: 1rem; }
        .sidebar .nav-link { color: rgba(255,255,255,.75); }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { color: #fff; }
        .main-content { margin-left: var(--sidebar-width); padding: 1.5rem; }
        @media (max-width: 992px) {
            .sidebar { transform: translateX(calc(-1 * var(--sidebar-width))); transition: transform 0.3s ease-in-out; z-index: 1040; }
            .sidebar.active { transform: translateX(0); }
            .main-content { margin-left: 0; }
        }
        [data-bs-theme="dark"] body { background-color: #212529; color: #dee2e6; }
        [data-bs-theme="dark"] .card, [data-bs-theme="dark"] .modal-content, [data-bs-theme="dark"] .list-group-item, [data-bs-theme="dark"] .table, [data-bs-theme="dark"] .accordion-item { background-color: #343a40; }
        [data-bs-theme="dark"] .accordion-button { background-color: #3e444a; color: #fff; }
        [data-bs-theme="dark"] .accordion-button:not(.collapsed) { background-color: #495057;}
        [data-bs-theme="dark"] .accordion-button::after { filter: invert(1) grayscale(100) brightness(200%); }
        [data-bs-theme="dark"] .table-hover>tbody>tr:hover>* { color: var(--bs-table-hover-color); background-color: rgba(255, 255, 255, 0.075); }
        [data-bs-theme="dark"] .text-dark { color: #dee2e6 !important; }
        .product-card { cursor: pointer; }
        .product-card:hover { border-color: var(--bs-primary); }
        .payback-positive { color: var(--bs-success); }
        .payback-negative { color: var(--bs-danger); }
        .payback-zero { color: var(--bs-secondary); }
    </style>
</head>
<body>
<nav class="sidebar">
    <div class="p-3 text-white">
        <a href="/" class="text-white text-decoration-none"><h4 class="fw-bold"><i class="fas fa-cash-register me-2"></i>POS System</h4></a>
    </div>
    <ul class="nav flex-column">
        <li class="nav-item"><a class="nav-link {% if request.endpoint == 'sales_screen' %}active{% endif %}" href="{{ url_for('sales_screen') }}"><i class="fas fa-fw fa-dollar-sign me-2"></i>Касса</a></li>
        <li class="nav-item"><a class="nav-link {% if request.endpoint == 'inventory_management' %}active{% endif %}" href="{{ url_for('inventory_management') }}"><i class="fas fa-fw fa-boxes me-2"></i>Склад</a></li>
        <li class="nav-item"><a class="nav-link {% if request.endpoint == 'transaction_history' %}active{% endif %}" href="{{ url_for('transaction_history') }}"><i class="fas fa-fw fa-history me-2"></i>Транзакции</a></li>
        <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle {% if request.endpoint in ['reports', 'product_roi_report'] %}active{% endif %}" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-fw fa-chart-line me-2"></i>Отчеты
            </a>
            <ul class="dropdown-menu dropdown-menu-dark">
                <li><a class="dropdown-item" href="{{ url_for('reports') }}">Сводный отчет</a></li>
                <li><a class="dropdown-item" href="{{ url_for('product_roi_report') }}">Окупаемость товаров</a></li>
            </ul>
        </li>
        <li class="nav-item"><a class="nav-link {% if request.endpoint in ['cashier_login', 'cashier_dashboard'] %}active{% endif %}" href="{{ url_for('cashier_login') }}"><i class="fas fa-fw fa-user-circle me-2"></i>Кабинет кассира</a></li>
        <li class="nav-item"><a class="nav-link {% if request.endpoint in ['admin_panel', 'admin_shifts'] %}active{% endif %}" href="{{ url_for('admin_panel') }}"><i class="fas fa-fw fa-cogs me-2"></i>Админка</a></li>
        {% if session.admin_logged_in %}
        <li class="nav-item"><a class="nav-link" href="{{ url_for('admin_logout') }}"><i class="fas fa-fw fa-sign-out-alt me-2"></i>Выйти (Админ)</a></li>
        {% endif %}
    </ul>
    <div class="mt-auto p-3 text-secondary small">
        &copy; {{ get_current_time().year }}<br>{{ get_current_time().strftime('%Y-%m-%d %H:%M') }}
    </div>
</nav>

<div class="main-content">
    <header class="d-flex justify-content-between align-items-center mb-4">
        <button class="btn btn-dark d-lg-none" id="sidebar-toggle"><i class="fas fa-bars"></i></button>
        <h2 class="h3 mb-0">__TITLE__</h2>
        <div id="theme-toggle" style="cursor: pointer;"><i class="fas fa-sun fa-lg"></i></div>
    </header>
    <main>
        {% with messages = get_flashed_messages(with_categories=true) %}
          {% if messages %}
            {% for category, message in messages %}
              <div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
                {{ message }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
              </div>
            {% endfor %}
          {% endif %}
        {% endwith %}
        __CONTENT__
    </main>
</div>

<div class="modal fade" id="receiptModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Продажа завершена</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>Накладная успешно создана.</p>
        <div class="mb-3">
            <label for="whatsapp-phone" class="form-label">Отправить накладную на WhatsApp</label>
            <div class="input-group">
                <span class="input-group-text">+7</span>
                <input type="tel" class="form-control" id="whatsapp-phone" placeholder="7071234567">
            </div>
            <div class="form-text">Введите номер без +7.</div>
        </div>
        <input type="hidden" id="receipt-url">
      </div>
      <div class="modal-footer">
        <a id="view-receipt-btn" href="#" target="_blank" class="btn btn-secondary">Посмотреть накладную</a>
        <button type="button" id="send-whatsapp-btn" class="btn btn-success"><i class="fab fa-whatsapp"></i> Отправить</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="variantSelectModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="variantSelectModalTitle">Выберите вариант</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="variant-list" class="list-group"></div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('sidebar-toggle')?.addEventListener('click', () => document.querySelector('.sidebar').classList.toggle('active'));
        const themeToggle = document.getElementById('theme-toggle');
        const getStoredTheme = () => localStorage.getItem('theme');
        const setStoredTheme = theme => localStorage.setItem('theme', theme);
        const getPreferredTheme = () => getStoredTheme() || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
        const setTheme = theme => {
            document.documentElement.setAttribute('data-bs-theme', theme);
            themeToggle.innerHTML = theme === 'dark' ? '<i class="fas fa-moon fa-lg"></i>' : '<i class="fas fa-sun fa-lg"></i>';
        };
        setTheme(getPreferredTheme());
        themeToggle.addEventListener('click', () => {
            const newTheme = getPreferredTheme() === 'light' ? 'dark' : 'light';
            setStoredTheme(newTheme);
            setTheme(newTheme);
        });
    });
</script>
__SCRIPTS__
</body>
</html>
"""

SALES_SCREEN_CONTENT = """
<div class="row">
    <div class="col-lg-7 mb-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Товары</h5>
                <div>
                    <button id="custom-item-btn" class="btn btn-info btn-sm"><i class="fas fa-plus me-2"></i>Свой товар</button>
                    <button id="scan-btn" class="btn btn-primary btn-sm"><i class="fas fa-barcode me-2"></i>Сканировать</button>
                </div>
            </div>
            <div class="card-body">
                <div id="scanner-container" class="mb-3" style="display: none; position: relative;">
                    <div id="reader" style="width: 100%;"></div>
                    <div id="scanner-status" style="position: absolute; top: 10px; left: 10px; background: rgba(0,0,0,0.5); color: white; padding: 5px; border-radius: 5px; display: none;"></div>
                    <button id="stop-scan-btn" class="btn btn-danger btn-sm mt-2">Остановить</button>
                </div>
                <input type="text" id="product-search" class="form-control mb-3" placeholder="Поиск по названию или штрих-коду...">
                
                <div id="product-accordion" class="accordion">
                    {% for letter, products in grouped_inventory %}
                    <div class="accordion-item">
                        <h2 class="accordion-header" id="heading-{{ letter }}">
                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-{{ letter }}" aria-expanded="false" aria-controls="collapse-{{ letter }}">
                                {{ letter }}
                            </button>
                        </h2>
                        <div id="collapse-{{ letter }}" class="accordion-collapse collapse" aria-labelledby="heading-{{ letter }}" data-bs-parent="#product-accordion">
                            <div class="accordion-body d-grid gap-2" style="grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));">
                                {% for p in products %}
                                <div class="card text-center product-card" data-barcode="{{ p.barcode }}">
                                    <div class="card-body p-2">
                                        <h6 class="card-title small mb-1">{{ p.name }}</h6>
                                        <p class="card-text fw-bold mb-0">
                                            {% if p.variants|length > 1 %}
                                                от {{ format_currency_py(p.variants|map(attribute='price')|min) }} ₸ 
                                            {% elif p.variants|length == 1 %}
                                                {{ format_currency_py(p.variants[0].price) }} ₸
                                            {% else %}
                                                Нет в наличии
                                            {% endif %}
                                        </p>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-5">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Накладная</h5>
                    <div id="shift-controls"></div>
                </div>
                <div id="session-info" class="small text-muted mt-1"></div>
            </div>
            <div class="card-body">
                <div id="cart-items" class="list-group mb-3" style="max-height: 400px; overflow-y: auto;"></div>
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h4 class="mb-0">Итого:</h4>
                    <h4 class="mb-0" id="cart-total">0,00 ₸</h4>
                </div>
                <div class="d-grid gap-2">
                    <div class="btn-group"><button class="btn btn-success flex-grow-1" id="pay-cash-btn"><i class="fas fa-money-bill-wave me-2"></i>Наличные</button><button class="btn btn-info flex-grow-1" id="pay-card-btn"><i class="far fa-credit-card me-2"></i>Карта</button></div>
                    <button class="btn btn-danger" id="clear-cart-btn">Очистить</button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="cashierLoginModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Вход для кассира</h5></div>
      <div class="modal-body">
        <label for="cashier-pin-input" class="form-label">Введите ПИН-код</label>
        <input type="password" id="cashier-pin-input" class="form-control form-control-lg text-center" inputmode="numeric" autofocus>
        <div id="pin-error" class="text-danger mt-2"></div>
      </div>
       <div class="modal-footer"><button type="button" id="pin-submit-btn" class="btn btn-primary">Войти</button></div>
    </div>
  </div>
</div>

<div class="modal fade" id="startShiftModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Начать смену</h5></div>
      <div class="modal-body">
        <p>Кассир: <strong id="start-shift-cashier-name"></strong></p>
        <label for="kassa-select-modal" class="form-label">Выберите кассу</label>
        <select id="kassa-select-modal" class="form-select">
            <option value="">-- Выберите кассу --</option>
            {% for k in kassas %}<option value="{{ k.id }}" data-name="{{ k.name }}">{{ k.name }}</option>{% endfor %}
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" id="logout-btn" class="btn btn-secondary me-auto">Сменить кассира</button>
        <button type="button" id="start-shift-confirm-btn" class="btn btn-primary">Начать</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="customItemModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Товар без штрихкода</h5></div>
      <form id="custom-item-form">
        <div class="modal-body">
          <div class="mb-3"><label class="form-label">Название (необязательно)</label><input type="text" id="custom-item-name" class="form-control" placeholder="Напр. 'Пакет'"></div>
          <div class="mb-3"><label class="form-label">Цена за 1 шт.</label><input type="text" id="custom-item-price" class="form-control" inputmode="decimal" required></div>
          <div class="mb-3"><label class="form-label">Количество</label><input type="number" id="custom-item-qty" class="form-control" value="1" min="1" required></div>
        </div>
        <div class="modal-footer"><button type="submit" class="btn btn-primary">Добавить в накладную</button></div>
      </form>
    </div>
  </div>
</div>
"""

SALES_SCREEN_SCRIPTS = """
<script>
document.addEventListener('DOMContentLoaded', () => {
    const cart = {};
    const productGrid = document.getElementById('product-accordion');
    const cartItemsEl = document.getElementById('cart-items');
    const cartTotalEl = document.getElementById('cart-total');
    let audioCtx;
    let isScannerPaused = false;
    
    const receiptModal = new bootstrap.Modal(document.getElementById('receiptModal'));
    const variantSelectModal = new bootstrap.Modal(document.getElementById('variantSelectModal'));
    const cashierLoginModal = new bootstrap.Modal(document.getElementById('cashierLoginModal'));
    const startShiftModal = new bootstrap.Modal(document.getElementById('startShiftModal'));
    const customItemModal = new bootstrap.Modal(document.getElementById('customItemModal'));

    const session = {
        cashier: null,
        kassa: null,
        shift: null
    };

    function playBeep() {
        if (!audioCtx) {
            try { audioCtx = new (window.AudioContext || window.webkitAudioContext)(); } 
            catch (e) { console.error("Web Audio API is not supported"); return; }
        }
        const oscillator = audioCtx.createOscillator();
        const gainNode = audioCtx.createGain();
        oscillator.connect(gainNode);
        gainNode.connect(audioCtx.destination);
        oscillator.type = 'sine';
        oscillator.frequency.setValueAtTime(880, audioCtx.currentTime);
        gainNode.gain.setValueAtTime(0.5, audioCtx.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + 0.15);
        oscillator.start(audioCtx.currentTime);
        oscillator.stop(audioCtx.currentTime + 0.15);
    }
    
    function parseLocaleNumber(stringNumber) {
        return parseFloat(String(stringNumber).replace(/\\s/g, '').replace(',', '.')) || 0;
    }

    const updateCartView = () => {
        cartItemsEl.innerHTML = '';
        let total = 0;
        if (Object.keys(cart).length === 0) {
            cartItemsEl.innerHTML = '<p class="text-center text-muted">Корзина пуста</p>';
        }
        for (const id in cart) {
            const item = cart[id];
            total += (parseLocaleNumber(item.price) - parseLocaleNumber(item.discount)) * item.quantity;
            cartItemsEl.innerHTML += `
                <div class="list-group-item">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="mb-0 small">${item.productName} ${item.variantName ? '('+item.variantName+')' : ''}</h6>
                            <small>${item.price} ₸</small>
                        </div>
                        <div class="d-flex align-items-center">
                            <button class="btn btn-sm btn-outline-secondary cart-qty-btn" data-id="${id}" data-op="-1">-</button>
                            <input type="number" class="form-control form-control-sm text-center mx-1 cart-qty-input" data-id="${id}" value="${item.quantity}" style="width: 60px;" min="1">
                            <button class="btn btn-sm btn-outline-secondary cart-qty-btn" data-id="${id}" data-op="1">+</button>
                        </div>
                    </div>
                     <div class="input-group input-group-sm mt-2">
                      <span class="input-group-text">Скидка</span>
                      <input type="text" class="form-control cart-discount-input" data-id="${id}" value="${item.discount}" inputmode="decimal">
                    </div>
                </div>`;
        }
        cartTotalEl.textContent = total.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' ₸';
    };

    const addToCart = (product, variant) => {
        if (cart[variant.id]) {
            cart[variant.id].quantity++;
        } else {
            cart[variant.id] = {
                productId: product.id,
                productName: product.name,
                variantName: variant.option_value,
                price: String(variant.price).replace('.',','),
                quantity: 1,
                discount: '0'
            };
        }
        playBeep();
        updateCartView();
    };
    
    const handleProductSelection = (product) => {
        if (!product.variants || product.variants.length === 0) {
            alert("У этого товара нет доступных вариантов.");
            return;
        }
        if (product.variants.length === 1) {
            addToCart(product, product.variants[0]);
        } else {
            document.getElementById('variantSelectModalTitle').textContent = `Выберите вариант для "${product.name}"`;
            const variantList = document.getElementById('variant-list');
            variantList.innerHTML = '';
            product.variants.forEach(variant => {
                const btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-center';
                const imageUrl = variant.image_url ? `<img src="${variant.image_url}" class="img-thumbnail me-3" style="width: 50px; height: 50px; object-fit: cover;">` : '<div style="width: 50px; height: 50px;" class="me-3"></div>';
                btn.innerHTML = `
                    <div class="d-flex align-items-center">
                        ${imageUrl}
                        <div>${variant.option_value} - <strong>${parseFloat(variant.price).toLocaleString('ru-RU', {minimumFractionDigits: 2})} ₸</strong></div>
                    </div>
                    <span class="badge bg-secondary">Остаток: ${variant.stock}</span>`;
                btn.addEventListener('click', () => {
                    addToCart(product, variant);
                    variantSelectModal.hide();
                });
                variantList.appendChild(btn);
            });
            variantSelectModal.show();
        }
    };
    
    const fetchAndHandleProduct = (barcode) => {
        fetch(`/api/product_by_barcode/${barcode}`)
            .then(res => res.json())
            .then(data => {
                if (data.success) handleProductSelection(data.product);
                else alert(data.message);
            });
    }

    productGrid.addEventListener('click', e => {
        const card = e.target.closest('.product-card');
        if (card) {
            fetchAndHandleProduct(card.dataset.barcode);
        }
    });

    const updateCartItemQuantity = (id, newQuantity) => {
        if (cart[id]) {
            const qty = parseInt(newQuantity, 10);
            if (!isNaN(qty) && qty > 0) {
                cart[id].quantity = qty;
            } else {
                delete cart[id];
            }
            updateCartView();
        }
    };

    cartItemsEl.addEventListener('click', e => {
        if (e.target.classList.contains('cart-qty-btn')) {
            const id = e.target.dataset.id;
            const op = parseInt(e.target.dataset.op);
            if (cart[id]) {
                const newQuantity = cart[id].quantity + op;
                updateCartItemQuantity(id, newQuantity);
            }
        }
    });

    cartItemsEl.addEventListener('change', e => {
        if (e.target.classList.contains('cart-qty-input')) {
            const id = e.target.dataset.id;
            updateCartItemQuantity(id, e.target.value);
        }
        if (e.target.classList.contains('cart-discount-input')) {
            const id = e.target.dataset.id;
            if (cart[id]) {
                cart[id].discount = e.target.value;
                updateCartView();
            }
        }
    });
    
    document.getElementById('clear-cart-btn').addEventListener('click', () => {
        for(const id in cart) delete cart[id];
        updateCartView();
    });

    document.getElementById('product-search').addEventListener('input', e => {
        const term = e.target.value.toLowerCase();
        const productCards = document.querySelectorAll('#product-accordion .product-card');
        productCards.forEach(card => {
            const productName = card.querySelector('.card-title').textContent.toLowerCase();
            const barcode = card.dataset.barcode.toLowerCase();
            const show = productName.includes(term) || barcode.includes(term);
            card.style.display = show ? '' : 'none';
        });
        document.querySelectorAll('#product-accordion .accordion-item').forEach(accordionItem => {
            const collapseElement = accordionItem.querySelector('.accordion-collapse');
            const matchingCardsInGroup = accordionItem.querySelectorAll('.product-card:not([style*="display: none"])');
            const bsCollapse = bootstrap.Collapse.getOrCreateInstance(collapseElement, { toggle: false });

            if (term === '') {
                bsCollapse.hide(); 
            } else {
                if (matchingCardsInGroup.length > 0) {
                    bsCollapse.show();
                } else {
                    bsCollapse.hide();
                }
            }
        });
    });

    const completeSale = (paymentMethod) => {
        if (!session.shift || !session.cashier || !session.kassa) {
            alert('Смена не активна. Начните смену, чтобы проводить продажи.');
            return;
        }
        if (Object.keys(cart).length === 0) {
            alert('Корзина пуста!');
            return;
        }
        fetch('/api/complete_sale', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ 
                cart: cart, 
                userId: session.cashier.id, 
                kassaId: session.kassa.id,
                shiftId: session.shift.id,
                paymentMethod: paymentMethod
            })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                for(const id in cart) delete cart[id];
                updateCartView();
                document.getElementById('receipt-url').value = data.receiptUrl;
                document.getElementById('view-receipt-btn').href = data.receiptUrl;
                receiptModal.show();
            } else {
                alert(`Ошибка: ${data.message}`);
            }
        })
        .catch(err => alert(`Сетевая ошибка: ${err}`));
    };
    
    document.getElementById('pay-cash-btn').addEventListener('click', () => completeSale('cash'));
    document.getElementById('pay-card-btn').addEventListener('click', () => completeSale('card'));
    
    document.getElementById('send-whatsapp-btn').addEventListener('click', () => {
        const phone = document.getElementById('whatsapp-phone').value.replace(/\\D/g, '');
        const receiptUrl = document.getElementById('receipt-url').value;
        if (phone && receiptUrl) {
            const fullPhone = '7' + phone;
            const message = encodeURIComponent(`Ваша накладная: ${receiptUrl}`);
            window.open(`https://wa.me/${fullPhone}?text=${message}`, '_blank');
        } else {
            alert('Введите номер телефона.');
        }
    });

    const html5QrCode = new Html5Qrcode("reader");
    const scannerStatusEl = document.getElementById('scanner-status');
    
    const onScanSuccess = (decodedText, decodedResult) => {
        if (isScannerPaused) return;
        isScannerPaused = true;
        scannerStatusEl.textContent = 'Пауза...';
        scannerStatusEl.style.display = 'block';
        if (html5QrCode.getState() === 2) html5QrCode.pause();
        fetchAndHandleProduct(decodedText);
        setTimeout(() => {
            isScannerPaused = false;
            scannerStatusEl.style.display = 'none';
            if (html5QrCode.getState() === 2) html5QrCode.resume();
        }, 1000);
    };

    const startScanner = () => {
        document.getElementById('scanner-container').style.display = 'block';
        const config = { fps: 15, qrbox: { width: 300, height: 150 } };
        html5QrCode.start({ facingMode: "environment" }, config, onScanSuccess)
            .catch(err => console.error("Scanner start error:", err));
    };
    
    const stopScanner = () => {
        if (html5QrCode.isScanning) {
            html5QrCode.stop().then(() => {
                document.getElementById('scanner-container').style.display = 'none';
            }).catch(err => console.error("Failed to stop scanner", err));
        } else {
            document.getElementById('scanner-container').style.display = 'none';
        }
    };

    document.getElementById('scan-btn').addEventListener('click', startScanner);
    document.getElementById('stop-scan-btn').addEventListener('click', stopScanner);

    const updateSessionUI = () => {
        const sessionInfoEl = document.getElementById('session-info');
        const shiftControlsEl = document.getElementById('shift-controls');
        
        if (session.shift) {
            sessionInfoEl.innerHTML = `Кассир: <strong>${session.cashier.name}</strong> | Касса: <strong>${session.kassa.name}</strong>`;
            shiftControlsEl.innerHTML = '<button id="end-shift-btn" class="btn btn-danger btn-sm">Закончить смену</button>';
            document.getElementById('end-shift-btn').addEventListener('click', handleEndShift);
        } else if (session.cashier) {
            sessionInfoEl.innerHTML = `Кассир: <strong>${session.cashier.name}</strong>. Смена не начата.`;
            shiftControlsEl.innerHTML = '<button id="start-shift-btn" class="btn btn-success btn-sm">Начать смену</button>';
            document.getElementById('start-shift-btn').addEventListener('click', () => {
                 document.getElementById('start-shift-cashier-name').textContent = session.cashier.name;
                 startShiftModal.show();
            });
        } else {
            sessionInfoEl.innerHTML = 'Нет активного кассира';
            shiftControlsEl.innerHTML = '';
        }
    };
    
    const handleLogin = (pin) => {
        fetch('/api/verify_pin', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({pin: pin})
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                session.cashier = data.user;
                localStorage.setItem('current_cashier', JSON.stringify(data.user));
                cashierLoginModal.hide();
                updateSessionUI();
                document.getElementById('start-shift-cashier-name').textContent = session.cashier.name;
                startShiftModal.show();
            } else {
                document.getElementById('pin-error').textContent = data.message;
            }
        });
    };

    const handleLogout = () => {
        session.cashier = null;
        session.kassa = null;
        session.shift = null;
        localStorage.removeItem('current_cashier');
        localStorage.removeItem('current_kassa');
        localStorage.removeItem('current_shift');
        startShiftModal.hide();
        updateSessionUI();
        cashierLoginModal.show();
    };

    const handleStartShift = () => {
        const kassaSelect = document.getElementById('kassa-select-modal');
        const kassaId = kassaSelect.value;
        const kassaName = kassaSelect.options[kassaSelect.selectedIndex].dataset.name;
        if (!kassaId) { alert('Выберите кассу'); return; }

        fetch('/api/shift/start', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({userId: session.cashier.id, kassaId: kassaId})
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                session.kassa = {id: data.shift.kassa_id, name: data.shift.kassa_name};
                session.shift = data.shift;
                localStorage.setItem('current_kassa', JSON.stringify(session.kassa));
                localStorage.setItem('current_shift', JSON.stringify(session.shift));
                startShiftModal.hide();
                updateSessionUI();
            } else {
                alert(`Ошибка: ${data.message}`);
            }
        });
    };
    
    const handleEndShift = () => {
        if (!confirm('Вы уверены, что хотите закончить смену?')) return;
        fetch('/api/shift/end', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({shiftId: session.shift.id})
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                session.kassa = null;
                session.shift = null;
                localStorage.removeItem('current_kassa');
                localStorage.removeItem('current_shift');
                updateSessionUI();
                alert(data.message);
            } else {
                alert(`Ошибка: ${data.message}`);
            }
        });
    };

    const initializeSession = () => {
        const storedCashier = localStorage.getItem('current_cashier');
        const storedKassa = localStorage.getItem('current_kassa');
        const storedShift = localStorage.getItem('current_shift');
        
        if (storedCashier) session.cashier = JSON.parse(storedCashier);
        if (storedKassa) session.kassa = JSON.parse(storedKassa);
        if (storedShift) session.shift = JSON.parse(storedShift);
        
        updateSessionUI();
        
        if (!session.cashier) {
            cashierLoginModal.show();
        } else if (!session.shift) {
            document.getElementById('start-shift-cashier-name').textContent = session.cashier.name;
            startShiftModal.show();
        }
    };
    
    document.getElementById('pin-submit-btn').addEventListener('click', () => {
        const pinInput = document.getElementById('cashier-pin-input');
        handleLogin(pinInput.value);
        pinInput.value = '';
    });
    document.getElementById('cashier-pin-input').addEventListener('keypress', (e) => { if(e.key === 'Enter') handleLogin(e.target.value); });
    document.getElementById('start-shift-confirm-btn').addEventListener('click', handleStartShift);
    document.getElementById('logout-btn').addEventListener('click', handleLogout);

    document.getElementById('custom-item-btn').addEventListener('click', () => customItemModal.show());
    document.getElementById('custom-item-form').addEventListener('submit', (e) => {
        e.preventDefault();
        const name = document.getElementById('custom-item-name').value || 'Товар без штрихкода';
        const price = document.getElementById('custom-item-price').value;
        const qty = parseInt(document.getElementById('custom-item-qty').value);
        
        if (parseLocaleNumber(price) > 0 && qty > 0) {
            const customId = 'custom_' + Date.now();
            cart[customId] = {
                productName: name,
                price: String(price).replace('.',','),
                quantity: qty,
                discount: '0',
                isCustom: true
            };
            updateCartView();
            customItemModal.hide();
            e.target.reset();
        } else {
            alert('Введите корректную цену и количество.');
        }
    });

    updateCartView();
    initializeSession();
});
</script>
"""

INVENTORY_CONTENT = """
<div class="row mb-4">
    <div class="col-md-4">
        <div class="card text-center">
            <div class="card-body">
                <h6 class="card-subtitle mb-2 text-muted">Единиц товара на складе</h6>
                <h4 class="card-title">{{ inventory_summary.total_units }} шт.</h4>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card text-center">
            <div class="card-body">
                <h6 class="card-subtitle mb-2 text-muted">Сумма по себестоимости</h6>
                <h4 class="card-title">{{ format_currency_py(inventory_summary.total_cost_value) }} ₸</h4>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card text-center">
            <div class="card-body">
                <h6 class="card-subtitle mb-2 text-muted">Потенциальная прибыль</h6>
                <h4 class="card-title text-success">{{ format_currency_py(inventory_summary.potential_profit) }} ₸</h4>
            </div>
        </div>
    </div>
</div>
<div class="d-flex justify-content-between mb-3">
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addProductModal"><i class="fas fa-plus me-2"></i>Добавить товар</button>
    <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#stockInModal"><i class="fas fa-truck-loading me-2"></i>Оприходовать</button>
</div>
<input type="text" id="inventory-search" class="form-control mb-3" placeholder="Поиск по названию, варианту или штрих-коду...">

<div class="accordion" id="inventoryAccordion">
  {% for p in inventory %}
  <div class="accordion-item">
    <h2 class="accordion-header" id="heading-{{ p.id }}">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-{{ p.id }}">
        <strong>{{ p.name }}</strong>&nbsp;<small class="text-muted"> ({{ p.barcode }})</small>
      </button>
    </h2>
    <div id="collapse-{{ p.id }}" class="accordion-collapse collapse" data-bs-parent="#inventoryAccordion">
      <div class="accordion-body">
        <div class="d-flex justify-content-end mb-2">
            <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editProductModal-{{ p.id }}"><i class="fas fa-edit me-1"></i>Редактировать товар</button>
            <form action="{{ url_for('delete_product', product_id=p.id) }}" method="POST" class="d-inline ms-2" onsubmit="return confirm('Удалить товар?');">
                <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
            </form>
        </div>
        <table class="table table-sm table-bordered">
            <thead><tr><th>Фото</th><th>Вариант</th><th>Цена</th><th>Себест.</th><th>Остаток</th></tr></thead>
            <tbody>
                {% for v in p.variants %}
                <tr>
                    <td><img src="{{ v.image_url if v.image_url else url_for('static', filename='placeholder.png') }}" class="img-thumbnail" style="width: 40px; height: 40px; object-fit: cover;"></td>
                    <td>{{ v.option_value }}</td>
                    <td>{{ format_currency_py(v.price) }} ₸</td>
                    <td>{{ format_currency_py(v.cost_price) }} ₸</td>
                    <td>{{ v.stock }}</td>
                </tr>
                {% else %}
                <tr><td colspan="5" class="text-center text-muted">Нет вариантов</td></tr>
                {% endfor %}
            </tbody>
        </table>
      </div>
    </div>
  </div>
  {% endfor %}
</div>

<div class="modal fade" id="addProductModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Новый товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form action="{{ url_for('inventory_management') }}" method="POST">
        <div class="modal-body">
          <div class="row">
              <div class="col-md-6 mb-3"><label class="form-label">Название</label><input type="text" name="name" class="form-control" required></div>
              <div class="col-md-6 mb-3"><label class="form-label">Штрих-код</label>
                <div class="input-group"><input type="text" name="barcode" class="form-control barcode-input" required><button type="button" class="btn btn-outline-secondary scan-modal-btn"><i class="fas fa-barcode"></i></button></div>
              </div>
          </div>
          <div id="modal-scanner-add" class="mb-2" style="display:none;"></div>
          <hr>
          <h6>Варианты товара</h6>
          <div id="variants-container-add"></div>
          <button type="button" class="btn btn-sm btn-outline-success mt-2" id="add-variant-btn-add">Добавить вариант</button>
        </div>
        <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
      </form>
    </div>
  </div>
</div>

{% for p in inventory %}
<div class="modal fade" id="editProductModal-{{ p.id }}" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Редактировать товар</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form action="{{ url_for('edit_product', product_id=p.id) }}" method="POST">
        <div class="modal-body">
          <div class="row">
              <div class="col-md-6 mb-3"><label class="form-label">Название</label><input type="text" name="name" class="form-control" value="{{ p.name }}" required></div>
              <div class="col-md-6 mb-3"><label class="form-label">Штрих-код</label><input type="text" name="barcode" class="form-control" value="{{ p.barcode }}" required></div>
          </div>
          <hr>
          <h6>Варианты товара</h6>
          <div id="variants-container-edit-{{ p.id }}">
            {% for v in p.variants %}
            <div class="row g-2 mb-2 align-items-center variant-row">
                <input type="hidden" name="variant_id[]" value="{{ v.id }}">
                <div class="col-2">
                    <img src="{{ v.image_url if v.image_url else url_for('static', filename='placeholder.png') }}" class="img-thumbnail variant-preview mb-1" style="width: 50px; height: 50px; object-fit: cover;">
                    <input type="file" class="form-control form-control-sm variant-image-upload" accept="image/*">
                    <input type="hidden" class="variant-image-url-input" name="variant_image_url[]" value="{{ v.image_url }}">
                </div>
                <div class="col-2"><input type="text" name="variant_name[]" class="form-control" placeholder="Название варианта" value="{{ v.option_value }}" required></div>
                <div class="col"><input type="text" name="variant_price[]" class="form-control" placeholder="Цена" value="{{ v.price|string|replace('.', ',') }}" inputmode="decimal"></div>
                <div class="col"><input type="text" name="variant_cost_price[]" class="form-control" placeholder="Себестоимость" value="{{ v.cost_price|string|replace('.', ',') }}" inputmode="decimal"></div>
                <div class="col"><input type="number" name="variant_stock[]" class="form-control" placeholder="Остаток" value="{{ v.stock }}"></div>
                <div class="col-auto"><button type="button" class="btn btn-sm btn-danger remove-variant-btn"><i class="fas fa-times"></i></button></div>
            </div>
            {% endfor %}
          </div>
          <button type="button" class="btn btn-sm btn-outline-success mt-2 add-variant-btn-edit" data-target-container="variants-container-edit-{{ p.id }}">Добавить вариант</button>
        </div>
        <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
      </form>
    </div>
  </div>
</div>
{% endfor %}

<div class="modal fade" id="stockInModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Оприходование товара</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form action="{{ url_for('stock_in') }}" method="POST">
        <div class="modal-body">
            <div class="mb-3">
                <label for="stockin-product" class="form-label">Товар</label>
                <select id="stockin-product" name="product_id" class="form-select" required>
                    <option value="">-- Выберите товар --</option>
                    {% for p in inventory %}
                    <option value="{{ p.id }}">{{ p.name }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="mb-3">
                <label for="stockin-variant" class="form-label">Вариант</label>
                <select id="stockin-variant" name="variant_id" class="form-select" required disabled>
                    <option value="">-- Сначала выберите товар --</option>
                </select>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="stockin-quantity" class="form-label">Количество</label>
                    <input type="number" id="stockin-quantity" name="quantity" class="form-control" required min="1">
                </div>
                <div class="col-md-6 mb-3">
                    <label for="stockin-cost" class="form-label">Себестоимость (за ед.)</label>
                    <input type="text" id="stockin-cost" name="cost_price" class="form-control" inputmode="decimal" placeholder="Необязательно">
                </div>
            </div>
            <div class="mb-3">
                <label for="stockin-delivery" class="form-label">Стоимость доставки (общая)</label>
                <input type="text" id="stockin-delivery" name="delivery_cost" class="form-control" inputmode="decimal" placeholder="0">
                <div class="form-text">Эта сумма будет добавлена в расходы как "Дорога" и учтена в себестоимости.</div>
            </div>
        </div>
        <div class="modal-footer"><button type="submit" class="btn btn-primary">Оприходовать</button></div>
      </form>
    </div>
  </div>
</div>
"""

INVENTORY_SCRIPTS = """
<script>
document.addEventListener('DOMContentLoaded', () => {
    let currentScanner = null;
    let currentScannerContainer = null;
    const placeholderImg = "{{ url_for('static', filename='placeholder.png') }}";

    document.querySelectorAll('.scan-modal-btn').forEach(btn => {
        btn.addEventListener('click', e => {
            const form = e.target.closest('form');
            const scannerContainer = form.querySelector('[id^="modal-scanner-"]');
            const barcodeInput = form.querySelector('.barcode-input');
            
            if (currentScanner) {
                try { currentScanner.stop(); } catch(e) {}
                currentScanner = null;
                if(currentScannerContainer) currentScannerContainer.style.display = 'none';
                return;
            }
            scannerContainer.style.display = 'block';
            currentScannerContainer = scannerContainer;
            const scannerId = scannerContainer.id + '-reader';
            if(!document.getElementById(scannerId)) scannerContainer.innerHTML = `<div id="${scannerId}" style="width: 100%;"></div>`;

            const html5QrCode = new Html5Qrcode(scannerId);
            currentScanner = html5QrCode;
            const onScanSuccess = (decodedText, decodedResult) => {
                barcodeInput.value = decodedText;
                try { html5QrCode.stop(); } catch(e) {}
                currentScanner = null;
                scannerContainer.style.display = 'none';
            };
            html5QrCode.start({ facingMode: "environment" }, { fps: 10, qrbox: { width: 250, height: 250 } }, onScanSuccess);
        });
    });
    
    document.querySelectorAll('.modal').forEach(modal => {
        modal.addEventListener('hidden.bs.modal', () => {
             if (currentScanner) {
                try { currentScanner.stop(); } catch(e) {}
                currentScanner = null;
             }
             if(currentScannerContainer) {
                 currentScannerContainer.style.display = 'none';
                 currentScannerContainer.innerHTML = '';
             }
        });
    });
    
    const handleImageUpload = (fileInput) => {
        const file = fileInput.files[0];
        if (!file) return;

        const row = fileInput.closest('.variant-row');
        const preview = row.querySelector('.variant-preview');
        const urlInput = row.querySelector('.variant-image-url-input');

        const formData = new FormData();
        formData.append('image', file);
        
        preview.src = "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="; // Spinner

        fetch("{{ url_for('upload_image') }}", {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                preview.src = data.url;
                urlInput.value = data.url;
            } else {
                alert('Ошибка загрузки: ' + data.message);
                preview.src = placeholderImg;
            }
        })
        .catch(error => {
            console.error('Upload error:', error);
            alert('Сетевая ошибка при загрузке изображения.');
            preview.src = placeholderImg;
        });
    };

    const createVariantRow = () => {
        const div = document.createElement('div');
        div.className = 'row g-2 mb-2 align-items-center variant-row';
        div.innerHTML = `
            <input type="hidden" name="variant_id[]" value="">
            <div class="col-2">
                <img src="${placeholderImg}" class="img-thumbnail variant-preview mb-1" style="width: 50px; height: 50px; object-fit: cover;">
                <input type="file" class="form-control form-control-sm variant-image-upload" accept="image/*">
                <input type="hidden" class="variant-image-url-input" name="variant_image_url[]" value="">
            </div>
            <div class="col-2"><input type="text" name="variant_name[]" class="form-control" placeholder="Название варианта" required></div>
            <div class="col"><input type="text" name="variant_price[]" class="form-control" placeholder="Цена" inputmode="decimal"></div>
            <div class="col"><input type="text" name="variant_cost_price[]" class="form-control" placeholder="Себестоимость" inputmode="decimal"></div>
            <div class="col"><input type="number" name="variant_stock[]" class="form-control" placeholder="Остаток" value="0"></div>
            <div class="col-auto"><button type="button" class="btn btn-sm btn-danger remove-variant-btn"><i class="fas fa-times"></i></button></div>
        `;
        div.querySelector('.remove-variant-btn').addEventListener('click', () => div.remove());
        div.querySelector('.variant-image-upload').addEventListener('change', (e) => handleImageUpload(e.target));
        return div;
    };
    
    document.body.addEventListener('change', e => {
        if (e.target.classList.contains('variant-image-upload')) {
            handleImageUpload(e.target);
        }
    });

    document.getElementById('add-variant-btn-add').addEventListener('click', () => {
        document.getElementById('variants-container-add').appendChild(createVariantRow());
    });
    
    document.querySelectorAll('.add-variant-btn-edit').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const containerId = e.target.dataset.targetContainer;
            document.getElementById(containerId).appendChild(createVariantRow());
        });
    });
    
    document.querySelectorAll('.remove-variant-btn').forEach(btn => {
        btn.addEventListener('click', e => e.target.closest('.variant-row').remove());
    });
    
    const addProductModal = document.getElementById('addProductModal');
    addProductModal.addEventListener('shown.bs.modal', () => {
        const container = document.getElementById('variants-container-add');
        if (container.children.length === 0) {
            container.appendChild(createVariantRow());
        }
    });

    const inventoryData = JSON.parse('{{ inventory|tojson|safe }}');
    const productSelect = document.getElementById('stockin-product');
    const variantSelect = document.getElementById('stockin-variant');

    productSelect.addEventListener('change', () => {
        const productId = productSelect.value;
        variantSelect.innerHTML = '<option value="">-- Выберите вариант --</option>';
        variantSelect.disabled = true;

        if (productId) {
            const product = inventoryData.find(p => p.id === productId);
            if (product && product.variants) {
                product.variants.forEach(v => {
                    const option = document.createElement('option');
                    option.value = v.id;
                    option.textContent = v.option_value;
                    variantSelect.appendChild(option);
                });
                variantSelect.disabled = false;
            }
        }
    });

    document.getElementById('inventory-search').addEventListener('input', e => {
        const term = e.target.value.toLowerCase();
        document.querySelectorAll('#inventoryAccordion .accordion-item').forEach(item => {
            const productName = item.querySelector('.accordion-button strong').textContent.toLowerCase();
            const barcode = item.querySelector('.accordion-button small').textContent.toLowerCase();
            const variantNameElements = item.querySelectorAll('.accordion-body table tbody tr td:nth-child(2)');
            const variantMatch = Array.from(variantNameElements).some(td => td.textContent.toLowerCase().includes(term));
            const show = productName.includes(term) || barcode.includes(term) || variantMatch;
            item.style.display = show ? '' : 'none';
        });
    });
});
</script>
"""

TRANSACTIONS_CONTENT = """
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-auto">
                <label for="date-filter" class="form-label">Дата</label>
                <input type="date" id="date-filter" name="date" value="{{ selected_date }}" class="form-control">
            </div>
            <div class="col-auto">
                <label for="kassa-filter" class="form-label">Касса</label>
                <select id="kassa-filter" name="kassa" class="form-select">
                    <option value="">Все кассы</option>
                    {% for k in kassas %}
                    <option value="{{ k.id }}" {% if k.id == selected_kassa_id %}selected{% endif %}>{{ k.name }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-primary">Показать</button>
            </div>
        </form>
        <hr>
        {% set selected_kassa = kassas|selectattr('id', 'equalto', selected_kassa_id)|first %}
        <div class="d-flex justify-content-between align-items-center flex-wrap">
            <h4 class="mb-0">Общая выручка за {{ selected_date }}{% if selected_kassa %} (Касса: {{ selected_kassa.name }}){% endif %}: <span class="text-success">{{ format_currency_py(total_sales) }} ₸</span></h4>
            <h5 class="mb-0 text-muted">Продано пар: <span class="fw-bold text-dark">{{ total_quantity_sold }}</span></h5>
        </div>
    </div>
</div>
<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-sm table-hover">
                <thead><tr><th>ID</th><th>Дата</th><th>Тип</th><th>Кассир</th><th>Касса</th><th>Сумма</th><th>Статус</th><th>Позиции</th><th></th></tr></thead>
                <tbody>
                {% for t in transactions %}
                <tr class="{% if t.type == 'return' %}table-danger{% endif %}">
                    <td><a href="{{ url_for('view_receipt', transaction_id=t.id) if t.type == 'sale' and (t.invoice_html or t.receipt_html) else '#' }}" target="_blank"><small class="text-muted">{{ t.id[:8] }}</small></a></td>
                    <td>{{ t.timestamp[11:16] }}</td>
                    <td>
                        {% if t.type == 'sale' %}
                            {% set display_type = 'Наличные' if t.payment_method == 'cash' else 'Карта' %}
                            {% set badge_class = 'primary' if t.payment_method == 'cash' else 'info' %}
                        {% elif t.type == 'return' %}
                            {% set display_type = 'Возврат' %}
                            {% set badge_class = 'danger' %}
                        {% endif %}
                        <span class="badge bg-{{ badge_class }}">{{ display_type }}</span>
                    </td>
                    <td>{{ t.user_name }}</td><td>{{ t.kassa_name }}</td>
                    <td class="fw-bold">{{ format_currency_py(t.total_amount) }} ₸</td>
                    <td><span class="badge bg-{{'success' if t.status == 'completed' else 'secondary'}}">{{t.status}}</span></td>
                    <td>
                        <ul class="list-unstyled mb-0 small">
                        {% for item in t['items'] %}<li>{{ item.name }} ({{ item.quantity }}x{{ format_currency_py(item.price_at_sale) }}{% if item.get('discount_per_item', '0')|float > 0 %} -{{ format_currency_py(item.discount_per_item) }}{% endif %})</li>{% endfor %}
                        </ul>
                    </td>
                    <td>
                        {% if session.admin_logged_in %}
                            {% if t.type == 'sale' %}
                            <button class="btn btn-xs btn-outline-secondary py-0 px-1" data-bs-toggle="modal" data-bs-target="#editTransactionModal" data-transaction-id="{{t.id}}" data-transaction-items="{{t['items']|tojson}}">
                                <i class="fas fa-pencil-alt"></i>
                            </button>
                            {% endif %}
                            <form action="{{ url_for('delete_transaction', transaction_id=t.id) }}" method="POST" class="d-inline ms-1" onsubmit="return confirm('Удалить эту транзакцию? Действие необратимо.');">
                                <button type="submit" class="btn btn-xs btn-outline-danger py-0 px-1"><i class="fas fa-trash"></i></button>
                            </form>
                        {% endif %}
                    </td>
                </tr>
                {% else %}
                <tr><td colspan="9" class="text-center">Нет транзакций за выбранную дату.</td></tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="editTransactionModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Редактировать транзакцию</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <p>ID: <strong id="edit-trans-id"></strong></p>
        <form id="edit-trans-form">
            <div id="edit-trans-items-container" class="table-responsive"></div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
        <button type="button" id="save-trans-btn" class="btn btn-primary">Сохранить изменения</button>
      </div>
    </div>
  </div>
</div>
"""

TRANSACTIONS_SCRIPTS = """
<script>
document.addEventListener('DOMContentLoaded', () => {
    const editModal = new bootstrap.Modal(document.getElementById('editTransactionModal'));
    const editModalEl = document.getElementById('editTransactionModal');
    let currentTransactionId = null;

    editModalEl.addEventListener('show.bs.modal', event => {
        const button = event.relatedTarget;
        currentTransactionId = button.dataset.transactionId;
        const items = JSON.parse(button.dataset.transactionItems);
        
        document.getElementById('edit-trans-id').textContent = currentTransactionId.substring(0, 8);
        const container = document.getElementById('edit-trans-items-container');
        
        let tableHtml = `<table class="table table-sm"><thead><tr><th>Товар</th><th>Цена</th><th>Скидка</th></tr></thead><tbody>`;
        items.forEach(item => {
            const itemId = item.variant_id || item.product_id;
            tableHtml += `
                <tr data-item-id="${itemId}">
                    <td>${item.name} (${item.quantity} шт.)</td>
                    <td><input type="text" class="form-control form-control-sm" name="price" value="${String(item.price_at_sale).replace('.',',')}" inputmode="decimal"></td>
                    <td><input type="text" class="form-control form-control-sm" name="discount" value="${String(item.discount_per_item || '0').replace('.',',')}" inputmode="decimal"></td>
                </tr>`;
        });
        tableHtml += `</tbody></table>`;
        container.innerHTML = tableHtml;
    });

    document.getElementById('save-trans-btn').addEventListener('click', () => {
        const form = document.getElementById('edit-trans-form');
        const items_update = [];
        form.querySelectorAll('tbody tr').forEach(row => {
            items_update.push({
                id: row.dataset.itemId,
                price: row.querySelector('input[name="price"]').value,
                discount: row.querySelector('input[name="discount"]').value
            });
        });

        fetch(`/admin/transaction/edit/${currentTransactionId}`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ items: items_update })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                editModal.hide();
                window.location.reload();
            } else {
                alert('Ошибка: ' + data.message);
            }
        })
        .catch(err => {
            console.error(err);
            alert('Сетевая ошибка.');
        });
    });
});
</script>
"""

REPORTS_CONTENT = """
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" action="{{ url_for('reports') }}">
            <div class="row g-2 align-items-end">
                <div class="col-md-4"><label for="start_date" class="form-label">Начало периода</label><input type="date" id="start_date" name="start_date" value="{{ start_date }}" class="form-control"></div>
                <div class="col-md-4"><label for="end_date" class="form-label">Конец периода</label><input type="date" id="end_date" name="end_date" value="{{ end_date }}" class="form-control"></div>
                <div class="col-md-4"><button type="submit" class="btn btn-primary w-100">Сформировать отчет</button></div>
            </div>
        </form>
    </div>
</div>

<div class="row">
    <div class="col-lg-7">
        <div class="card mb-4">
            <div class="card-header"><h5 class="mb-0">Сводный отчет за период</h5></div>
            <div class="card-body">
                <ul class="list-group list-group-flush">
                    <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-chart-bar me-2 text-primary"></i>Выручка (за вычетом возвратов)</span> <strong>{{ format_currency_py(stats.total_revenue) }} ₸</strong></li>
                    <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-cogs me-2 text-secondary"></i>Себестоимость проданных товаров</span> <strong>{{ format_currency_py(stats.total_cogs) }} ₸</strong></li>
                    <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-piggy-bank me-2 text-info"></i>Валовая прибыль</span> <strong class="text-info">{{ format_currency_py(stats.gross_profit) }} ₸</strong></li>
                    <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-receipt me-2 text-warning"></i>Расходы (операционные)</span> <strong class="text-warning">-{{ format_currency_py(stats.total_expenses) }} ₸</strong></li>
                    <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-user-tie me-2" style="color: orange;"></i>Расходы (личные)</span> <strong class="text-warning">-{{ format_currency_py(stats.total_personal_expenses) }} ₸</strong></li>
                    <li class="list-group-item d-flex justify-content-between"><span><i class="fas fa-users-cog me-2 text-danger"></i>Расходы (зарплаты)</span> <strong class="text-danger">-{{ format_currency_py(stats.total_salary_expenses) }} ₸</strong></li>
                    <li class="list-group-item d-flex justify-content-between fs-5"><span><i class="fas fa-check-circle me-2 text-success"></i>Чистая прибыль</span> <strong class="text-success">{{ format_currency_py(stats.net_profit) }} ₸</strong></li>
                </ul>
            </div>
        </div>
        <div class="card mb-4">
            <div class="card-header"><h5 class="mb-0">Расчеты с кассирами за период</h5></div>
            <div class="card-body p-0">
                <div class="table-responsive"><table class="table table-sm mb-0">
                    <thead><tr><th>Кассир</th><th class="text-end">К выплате</th></tr></thead>
                    <tbody>
                    {% for name, payout in stats.cashier_payouts %}
                    <tr><td>{{ name }}</td><td class="text-end">{{ format_currency_py(payout) }} ₸</td></tr>
                    {% else %}<tr><td colspan="2" class="text-center text-muted">Нет данных для расчета.</td></tr>
                    {% endfor %}
                    </tbody>
                </table></div>
            </div>
        </div>
    </div>
    <div class="col-lg-5">
        <div class="card mb-4">
            <div class="card-header"><h5 class="mb-0">Продажи по кассирам</h5></div>
            <div class="card-body p-0">
                <div class="table-responsive"><table class="table table-hover mb-0">
                    <thead><tr><th>Кассир</th><th>Чеков</th><th class="text-end">Сумма</th></tr></thead>
                    <tbody>
                    {% for name, data in stats.sales_by_cashier %}
                    <tr><td>{{ name }}</td><td>{{ data.count }}</td><td class="text-end">{{ format_currency_py(data.total) }} ₸</td></tr>
                    {% else %}<tr><td colspan="3" class="text-center text-muted">Нет продаж за выбранный период.</td></tr>
                    {% endfor %}
                    </tbody>
                </table></div>
            </div>
        </div>
        <div class="card mb-4">
            <div class="card-header"><h5 class="mb-0">Операционные расходы за период</h5></div>
            <div class="card-body p-0">
                <div class="table-responsive" style="max-height: 200px; overflow-y: auto;"><table class="table table-sm mb-0">
                    <thead><tr><th>Дата</th><th>Описание</th><th class="text-end">Сумма</th></tr></thead>
                    <tbody>
                    {% for expense in expenses %}
                    <tr>
                        <td><small>{{ expense.timestamp[:10] }}</small></td>
                        <td>{{ expense.description }}</td>
                        <td class="text-end">{{ format_currency_py(expense.amount) }} ₸</td>
                    </tr>
                    {% else %}<tr><td colspan="3" class="text-center text-muted">Нет расходов за выбранный период.</td></tr>
                    {% endfor %}
                    </tbody>
                </table></div>
            </div>
        </div>
        <div class="card mb-4">
            <div class="card-header"><h5 class="mb-0">Личные расходы за период</h5></div>
            <div class="card-body p-0">
                <div class="table-responsive" style="max-height: 200px; overflow-y: auto;"><table class="table table-sm mb-0">
                    <thead><tr><th>Дата</th><th>Описание</th><th class="text-end">Сумма</th></tr></thead>
                    <tbody>
                    {% for expense in personal_expenses %}
                    <tr>
                        <td><small>{{ expense.timestamp[:10] }}</small></td>
                        <td>{{ expense.description }}</td>
                        <td class="text-end">{{ format_currency_py(expense.amount) }} ₸</td>
                    </tr>
                    {% else %}<tr><td colspan="3" class="text-center text-muted">Нет личных расходов за выбранный период.</td></tr>
                    {% endfor %}
                    </tbody>
                </table></div>
            </div>
        </div>
    </div>
</div>
"""

REPORTS_SCRIPTS = ""

PRODUCT_ROI_CONTENT = """
<div class="card">
    <div class="card-header"><h5 class="mb-0">Окупаемость по товарам</h5></div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover table-sm mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Товар (вариант)</th>
                        <th class="text-end">Продано, шт</th>
                        <th class="text-end">Выручка</th>
                        <th class="text-end">Стоимость на складе</th>
                        <th class="text-end">Общие вложения</th>
                        <th class="text-end">Результат (Окупаемость)</th>
                    </tr>
                </thead>
                <tbody>
                {% for item in stats %}
                    <tr>
                        <td><strong>{{ item.name }}</strong><br><small class="text-muted">{{ item.variant_name }}</small></td>
                        <td class="text-end">{{ item.total_qty_sold }}</td>
                        <td class="text-end">{{ format_currency_py(item.total_revenue) }} ₸</td>
                        <td class="text-end">{{ format_currency_py(item.inventory_value) }} ₸</td>
                        <td class="text-end text-secondary">{{ format_currency_py(item.total_investment) }} ₸</td>
                        <td class="text-end fw-bold 
                            {% if item.payback > 0 %}payback-positive
                            {% elif item.payback < 0 %}payback-negative
                            {% else %}payback-zero{% endif %}">
                            {{ format_currency_py(item.payback) }} ₸ 
                        </td>
                    </tr>
                {% else %}
                    <tr><td colspan="6" class="text-center">Нет данных для анализа.</td></tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    <div class="card-footer small text-muted">
        <i class="fas fa-info-circle me-1"></i>
        <strong>Общие вложения</strong> = Себестоимость проданных товаров + Стоимость текущих остатков на складе.
        <strong>Результат</strong> = Выручка - Общие вложения.
    </div>
</div>
"""

ADMIN_CONTENT = """
<div class="row">
    <div class="col-12 mb-4">
        <a href="{{ url_for('admin_shifts') }}" class="btn btn-info"><i class="fas fa-history me-2"></i>История смен кассиров</a>
    </div>
    <div class="col-md-6 mb-4">
        <div class="card h-100">
            <div class="card-header d-flex justify-content-between align-items-center"><h5 class="mb-0">Кассиры</h5><button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addUserModal"><i class="fas fa-plus"></i></button></div>
            <div class="card-body">
                <ul class="list-group">
                    {% for u in users %}
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <div>{{ u.name }} <br>
                        <small class="text-muted">
                        {% if u.payment_type == 'salary' %}Зарплата: {{ format_currency_py(u.payment_value) }} ₸/мес.
                        {% elif u.payment_type == 'percentage' %}Процент: {{ u.payment_value }}%
                        {% endif %}
                        </small>
                        </div>
                        <div>
                            <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editUserModal-{{ u.id }}"><i class="fas fa-edit"></i></button>
                            <form action="{{ url_for('manage_user') }}" method="POST" class="d-inline" onsubmit="return confirm('Удалить кассира?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="{{ u.id }}"><button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button></form>
                        </div>
                    </li>
                    {% endfor %}
                </ul>
            </div>
        </div>
    </div>
    <div class="col-md-6 mb-4">
        <div class="card h-100">
            <div class="card-header"><h5 class="mb-0">Кассы</h5></div>
            <div class="card-body">
                <form action="{{ url_for('manage_kassa') }}" method="POST" class="mb-3">
                    <input type="hidden" name="action" value="add">
                    <div class="input-group">
                        <input type="text" name="name" class="form-control" placeholder="Название кассы" required>
                        <input type="text" name="balance" class="form-control" placeholder="Начальный баланс" value="0" inputmode="decimal">
                        <button type="submit" class="btn btn-primary">Добавить</button>
                    </div>
                </form>
                <ul class="list-group">
                    {% for k in kassas %}
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <div>{{ k.name }} <br><small class="fw-bold">{{ format_currency_py(k.balance) }} ₸</small></div>
                        <form action="{{ url_for('manage_kassa') }}" method="POST" onsubmit="return confirm('Удалить кассу?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="{{ k.id }}"><button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button></form>
                    </li>
                    {% endfor %}
                </ul>
            </div>
        </div>
    </div>
    <div class="col-12 mb-4">
        <div class="card">
            <div class="card-header"><h5 class="mb-0">Операции по кассе (Внесение/Изъятие)</h5></div>
            <div class="card-body">
                <form action="{{ url_for('kassa_operation') }}" method="POST">
                    <div class="row g-2 align-items-end">
                        <div class="col-md-3"><label class="form-label">Касса</label><select name="kassa_id" class="form-select" required><option value="">-- Выберите --</option>{% for k in kassas %}<option value="{{k.id}}">{{k.name}}</option>{% endfor %}</select></div>
                        <div class="col-md-2"><label class="form-label">Операция</label><select name="op_type" class="form-select" required><option value="deposit">Внесение</option><option value="withdrawal">Изъятие</option></select></div>
                        <div class="col-md-2"><label class="form-label">Сумма</label><input type="text" name="amount" class="form-control" required inputmode="decimal"></div>
                        <div class="col-md-3"><label class="form-label">Описание</label><input type="text" name="description" class="form-control"></div>
                        <div class="col-md-2"><button type="submit" class="btn btn-success w-100">Выполнить</button></div>
                    </div>
                </form>
            </div>
        </div>
    </div>
     <div class="col-lg-6 mb-4">
        <div class="card h-100">
            <div class="card-header"><h5 class="mb-0">Учет расходов (операционные)</h5></div>
            <div class="card-body d-flex flex-column">
                <form action="{{ url_for('manage_expense') }}" method="POST" class="mb-4">
                    <div class="row g-2 align-items-end">
                        <div class="col-md-4"><label class="form-label">Сумма</label><input type="text" name="amount" class="form-control" required inputmode="decimal"></div>
                        <div class="col-md-8"><label class="form-label">Описание</label><input type="text" name="description" class="form-control" required placeholder="Напр: Аренда за май"></div>
                        <div class="col-12"><button type="submit" class="btn btn-warning w-100 mt-2">Добавить расход</button></div>
                    </div>
                </form>
                <h6>Все расходы:</h6>
                <div class="table-responsive flex-grow-1" style="max-height: 400px; overflow-y: auto;">
                    <table class="table table-sm table-striped">
                        <thead><tr><th>Дата</th><th>Описание</th><th class="text-end">Сумма</th><th></th></tr></thead>
                        <tbody>
                        {% for e in expenses %}
                        <tr>
                            <td><small>{{ e.timestamp[:10] }}</small></td>
                            <td>{{ e.description }}</td>
                            <td class="text-end fw-bold">{{ format_currency_py(e.amount) }} ₸</td>
                            <td class="text-end">
                                <form action="{{ url_for('delete_expense', expense_id=e.id) }}" method="POST" onsubmit="return confirm('Удалить этот расход?');">
                                    <button type="submit" class="btn btn-sm btn-outline-danger py-0 px-1"><i class="fas fa-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                        {% else %}
                        <tr><td colspan="4" class="text-center">Расходов пока нет</td></tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-6 mb-4">
        <div class="card h-100">
            <div class="card-header"><h5 class="mb-0">Учет расходов (личные)</h5></div>
            <div class="card-body d-flex flex-column">
                <form action="{{ url_for('manage_personal_expense') }}" method="POST" class="mb-4">
                    <div class="row g-2 align-items-end">
                        <div class="col-md-4"><label class="form-label">Сумма</label><input type="text" name="amount" class="form-control" required inputmode="decimal"></div>
                        <div class="col-md-8"><label class="form-label">Описание</label><input type="text" name="description" class="form-control" required placeholder="Напр: Обед"></div>
                        <div class="col-12"><button type="submit" class="btn btn-info w-100 mt-2">Добавить расход</button></div>
                    </div>
                </form>
                <h6>Все расходы:</h6>
                <div class="table-responsive flex-grow-1" style="max-height: 400px; overflow-y: auto;">
                    <table class="table table-sm table-striped">
                        <thead><tr><th>Дата</th><th>Описание</th><th class="text-end">Сумма</th><th></th></tr></thead>
                        <tbody>
                        {% for e in personal_expenses %}
                        <tr>
                            <td><small>{{ e.timestamp[:10] }}</small></td>
                            <td>{{ e.description }}</td>
                            <td class="text-end fw-bold">{{ format_currency_py(e.amount) }} ₸</td>
                            <td class="text-end">
                                <form action="{{ url_for('delete_personal_expense', expense_id=e.id) }}" method="POST" onsubmit="return confirm('Удалить этот расход?');">
                                    <button type="submit" class="btn btn-sm btn-outline-danger py-0 px-1"><i class="fas fa-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                        {% else %}
                        <tr><td colspan="4" class="text-center">Расходов пока нет</td></tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-12">
        <div class="card">
            <div class="card-header"><h5 class="mb-0">Резервное копирование</h5></div>
            <div class="card-body">
                <p>Данные периодически сохраняются в облако. Можно сделать это вручную.</p>
                <form method="POST" action="{{ url_for('backup_hf') }}" class="d-inline-block me-2">
                    <button type="submit" class="btn btn-outline-primary"><i class="fas fa-cloud-upload-alt me-2"></i>Сохранить в облако</button>
                </form>
                <form method="GET" action="{{ url_for('download_hf') }}" class="d-inline-block" onsubmit="return confirm('ВНИМАНИЕ! Это действие заменит все локальные данные данными из облака. Продолжить?');">
                    <button type="submit" class="btn btn-outline-danger"><i class="fas fa-cloud-download-alt me-2"></i>Загрузить из облака</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="addUserModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Новый кассир</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form action="{{ url_for('manage_user') }}" method="POST">
        <input type="hidden" name="action" value="add">
        <div class="modal-body">
          <div class="mb-3"><label class="form-label">Имя</label><input type="text" name="name" class="form-control" required></div>
          <div class="mb-3"><label class="form-label">ПИН-код</label><input type="password" name="pin" class="form-control" required></div>
          <div class="mb-3"><label class="form-label">Тип оплаты</label><select name="payment_type" class="form-select"><option value="percentage">Процент от продаж</option><option value="salary">Фиксированная зарплата</option></select></div>
          <div class="mb-3"><label class="form-label">Значение</label><input type="text" name="payment_value" class="form-control" inputmode="decimal" value="0" required><small class="form-text text-muted">Для процентов - число (напр. 5), для зарплаты - сумма в тенге.</small></div>
        </div>
        <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
      </form>
    </div>
  </div>
</div>
{% for u in users %}
<div class="modal fade" id="editUserModal-{{ u.id }}" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Редактировать кассира</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form action="{{ url_for('manage_user') }}" method="POST">
        <input type="hidden" name="action" value="edit">
        <input type="hidden" name="id" value="{{ u.id }}">
        <div class="modal-body">
          <div class="mb-3"><label class="form-label">Имя</label><input type="text" name="name" value="{{ u.name }}" class="form-control" required></div>
          <div class="mb-3"><label class="form-label">ПИН-код</label><input type="password" name="pin" value="{{ u.pin }}" class="form-control" required></div>
          <div class="mb-3"><label class="form-label">Тип оплаты</label><select name="payment_type" class="form-select">
            <option value="percentage" {% if u.payment_type == 'percentage' %}selected{% endif %}>Процент от продаж</option>
            <option value="salary" {% if u.payment_type == 'salary' %}selected{% endif %}>Фиксированная зарплата</option></select>
          </div>
          <div class="mb-3"><label class="form-label">Значение</label><input type="text" name="payment_value" class="form-control" value="{{ u.payment_value }}" inputmode="decimal" required></div>
        </div>
        <div class="modal-footer"><button type="submit" class="btn btn-primary">Сохранить</button></div>
      </form>
    </div>
  </div>
</div>
{% endfor %}
"""

ADMIN_SCRIPTS = ""

SHIFTS_CONTENT = """
<div class="card">
    <div class="card-header"><h5 class="mb-0">История смен</h5></div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover table-sm mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Кассир</th>
                        <th>Касса</th>
                        <th>Начало смены</th>
                        <th>Конец смены</th>
                        <th class="text-end">Продажи (наличные)</th>
                        <th class="text-end">Продажи (карта)</th>
                        <th class="text-end">Итого продаж</th>
                    </tr>
                </thead>
                <tbody>
                {% for s in shifts %}
                    <tr>
                        <td>{{ s.user_name }}</td>
                        <td>{{ s.kassa_name }}</td>
                        <td>{{ s.start_time[:16]|replace('T', ' ') }}</td>
                        <td>{{ (s.end_time[:16]|replace('T', ' ')) if s.end_time else '<span class="badge bg-success">Активна</span>' }}</td>
                        <td class="text-end">{{ format_currency_py(s.get('cash_sales', 0)) }} ₸</td>
                        <td class="text-end">{{ format_currency_py(s.get('card_sales', 0)) }} ₸</td>
                        <td class="text-end fw-bold">{{ format_currency_py(s.get('total_sales', 0)) }} ₸</td>
                    </tr>
                {% else %}
                    <tr><td colspan="7" class="text-center">Нет данных о сменах.</td></tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
"""

ADMIN_LOGIN_CONTENT = """
<div class="row justify-content-center mt-5">
    <div class="col-md-6 col-lg-4">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title text-center">Вход для администратора</h4>
                <form method="POST">
                    <div class="mb-3">
                        <label for="password" class="form-label">Пароль</label>
                        <input type="password" name="password" id="password" class="form-control" required autofocus>
                    </div>
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary">Войти</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
"""

CASHIER_LOGIN_CONTENT = """
<div class="row justify-content-center">
    <div class="col-md-6 col-lg-4">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title text-center">Вход для кассира</h4>
                <form method="POST" action="{{ url_for('cashier_login') }}">
                    <div class="mb-3">
                        <label for="pin" class="form-label">Введите ваш ПИН-код</label>
                        <input type="password" name="pin" id="pin" class="form-control form-control-lg text-center" required autofocus>
                    </div>
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary btn-lg">Войти</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
"""

CASHIER_DASHBOARD_CONTENT = """
<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-sm table-hover">
                <thead><tr><th>ID</th><th>Дата</th><th>Тип</th><th>Сумма</th><th>Статус</th><th>Действие</th></tr></thead>
                <tbody>
                {% for t in transactions %}
                <tr class="{% if t.type == 'return' %}table-danger{% endif %}">
                    <td><small class="text-muted">{{ t.id[:8] }}</small></td>
                    <td>{{ t.timestamp[:16]|replace('T', ' ') }}</td>
                    <td><span class="badge bg-{{'primary' if t.type == 'sale' else 'warning'}}">{{'Продажа' if t.type == 'sale' else 'Возврат'}}</span></td>
                    <td class="fw-bold">{{ format_currency_py(t.total_amount) }} ₸</td>
                    <td><span class="badge bg-{{'success' if t.status == 'completed' else 'secondary'}}">{{t.status}}</span></td>
                    <td>
                        {% if t.type == 'sale' and t.status == 'completed' %}
                        <form action="{{ url_for('return_transaction', transaction_id=t.id) }}" method="POST" onsubmit="return confirm('Оформить возврат по этой накладной?');">
                            <input type="hidden" name="cashier_id" value="{{ user.id }}">
                            <button type="submit" class="btn btn-sm btn-warning">Возврат</button>
                        </form>
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
"""

if __name__ == '__main__':
    backup_thread = threading.Thread(target=periodic_backup, daemon=True)
    backup_thread.start()
    for key in DATA_FILES.keys():
        load_json_data(key)
    app.run(debug=False, host='0.0.0.0', port=7860, use_reloader=False)