File size: 227,249 Bytes
baae1a3
9ef1f27
 
 
 
 
 
 
9a91292
9ef1f27
9151c0c
9fdd31e
c79f542
9ef1f27
9151c0c
9ef1f27
 
9151c0c
9ef1f27
 
 
 
 
 
c79f542
 
 
 
 
 
 
 
 
 
 
9ef1f27
 
9151c0c
9fdd31e
 
 
 
9151c0c
0727a3e
9ef1f27
 
 
 
127da28
 
4a9487a
9a91292
 
4a9487a
 
 
 
 
 
 
 
9151c0c
127da28
 
 
 
9a91292
 
 
1b526a1
d3908cc
 
 
 
 
 
127da28
 
9ef1f27
 
c79f542
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
 
 
9fdd31e
9151c0c
 
9fdd31e
9151c0c
 
 
 
 
 
9fdd31e
589c5f2
 
 
 
 
 
 
 
9151c0c
 
 
589c5f2
 
9151c0c
 
 
 
9fdd31e
 
 
 
9768e46
9fdd31e
9151c0c
9fdd31e
9768e46
9fdd31e
9768e46
9fdd31e
9768e46
9fdd31e
 
 
 
 
 
 
9151c0c
 
9fdd31e
 
 
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
9768e46
9fdd31e
9768e46
9fdd31e
9768e46
9151c0c
 
 
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9768e46
9fdd31e
9768e46
9151c0c
9a91292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
9151c0c
9a91292
589c5f2
 
127da28
 
 
9a91292
127da28
4a9487a
127da28
4a9487a
9a91292
 
298111d
09b1f6b
9151c0c
127da28
 
 
 
 
 
 
 
589c5f2
9fdd31e
 
 
127da28
9fdd31e
127da28
 
 
 
 
 
 
9151c0c
9fdd31e
 
 
 
 
baae1a3
 
 
 
 
 
298111d
 
 
 
 
 
9151c0c
127da28
9fdd31e
9151c0c
9fdd31e
 
127da28
9fdd31e
 
 
 
9ef1f27
 
9fdd31e
 
9151c0c
 
 
9fdd31e
 
9ef1f27
 
9fdd31e
 
 
9151c0c
9fdd31e
 
 
 
 
 
 
9151c0c
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
d3908cc
9fdd31e
9151c0c
9fdd31e
 
 
 
 
 
 
 
 
 
9151c0c
9fdd31e
 
 
 
 
d3908cc
9fdd31e
 
 
 
 
 
 
 
 
589c5f2
 
9a91292
 
 
9fdd31e
 
 
 
9151c0c
 
 
127da28
 
 
9a91292
09b1f6b
 
9fdd31e
 
 
 
09b1f6b
 
 
298111d
09b1f6b
 
298111d
baae1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
 
 
baae1a3
 
9151c0c
9fdd31e
9151c0c
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
09b1f6b
 
 
298111d
 
09b1f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
9151c0c
09b1f6b
9fdd31e
baae1a3
9fdd31e
 
baae1a3
 
 
9151c0c
9fdd31e
baae1a3
9fdd31e
 
 
9151c0c
d3908cc
9fdd31e
d3908cc
 
 
9151c0c
9fdd31e
 
 
 
 
d3908cc
 
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
d3908cc
1b526a1
 
 
 
 
a3641c0
1b526a1
 
 
 
 
d3908cc
1b526a1
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
9ef1f27
9151c0c
9ef1f27
9151c0c
 
9fdd31e
 
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
9a91292
 
9fdd31e
 
 
 
 
09b1f6b
 
 
 
 
 
 
 
 
 
9fdd31e
 
9a91292
589c5f2
a8c75d8
09b1f6b
9fdd31e
9a91292
 
09b1f6b
9fdd31e
9a91292
589c5f2
9fdd31e
 
298111d
09b1f6b
 
 
 
 
 
298111d
9151c0c
9ef1f27
 
9151c0c
9fdd31e
 
9151c0c
 
 
 
 
 
 
9fdd31e
 
 
 
9151c0c
 
9fdd31e
 
9768e46
a8c75d8
 
 
 
9fdd31e
589c5f2
9a91292
589c5f2
9a91292
 
09b1f6b
 
 
 
 
 
9a91292
 
589c5f2
9a91292
 
09b1f6b
 
9a91292
 
 
 
 
 
 
 
 
9fdd31e
589c5f2
9151c0c
589c5f2
9fdd31e
589c5f2
9fdd31e
 
 
 
5afdc5e
71c173f
9768e46
 
 
 
 
 
 
 
 
a8c75d8
9768e46
 
71c173f
5afdc5e
 
 
7e7da4d
5afdc5e
 
 
 
9151c0c
 
9a91292
9151c0c
 
 
 
127da28
09b1f6b
127da28
09b1f6b
127da28
09b1f6b
9a91292
09b1f6b
9a91292
09b1f6b
9a91292
09b1f6b
1b526a1
09b1f6b
d3908cc
09b1f6b
d3908cc
09b1f6b
d3908cc
09b1f6b
d3908cc
09b1f6b
d3908cc
09b1f6b
127da28
09b1f6b
127da28
 
9151c0c
 
9fdd31e
 
 
09b1f6b
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
09b1f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
09b1f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
09b1f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
09b1f6b
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
09b1f6b
 
9fdd31e
 
 
 
298111d
09b1f6b
9fdd31e
 
09b1f6b
298111d
09b1f6b
baae1a3
09b1f6b
9fdd31e
09b1f6b
 
 
9fdd31e
09b1f6b
 
 
9fdd31e
baae1a3
09b1f6b
baae1a3
9151c0c
09b1f6b
9fdd31e
 
09b1f6b
9fdd31e
09b1f6b
9fdd31e
09b1f6b
9fdd31e
09b1f6b
9151c0c
09b1f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
298111d
9151c0c
5afdc5e
09b1f6b
9151c0c
 
9fdd31e
127da28
9151c0c
 
 
 
 
9ef1f27
9fdd31e
9151c0c
 
 
 
 
 
9fdd31e
 
 
 
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
9151c0c
9fdd31e
 
 
 
 
9a91292
9fdd31e
 
 
4530018
 
 
 
 
 
 
9151c0c
 
 
 
 
 
 
9fdd31e
 
 
 
9151c0c
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
baae1a3
 
9fdd31e
09b1f6b
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589c5f2
9a91292
9fdd31e
 
 
9a91292
9fdd31e
 
 
 
589c5f2
9fdd31e
9151c0c
9fdd31e
9151c0c
 
 
 
 
9fdd31e
4530018
9151c0c
589c5f2
9fdd31e
 
 
 
 
 
 
 
 
9151c0c
 
9fdd31e
 
 
 
9151c0c
9fdd31e
 
 
 
 
9151c0c
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
 
 
baae1a3
9fdd31e
 
 
 
 
 
baae1a3
 
 
 
 
 
 
 
 
4530018
baae1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
09b1f6b
 
 
 
 
 
 
 
4530018
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
 
 
9fdd31e
9151c0c
 
 
9fdd31e
 
 
 
baae1a3
 
 
 
 
 
 
 
9fdd31e
baae1a3
 
 
 
 
 
 
4530018
 
 
 
 
 
09b1f6b
9fdd31e
 
 
 
 
9151c0c
9fdd31e
9151c0c
9fdd31e
 
 
baae1a3
 
 
 
 
 
 
9fdd31e
 
 
 
 
9151c0c
9fdd31e
 
 
 
4530018
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
4530018
 
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
 
baae1a3
9fdd31e
 
 
09b1f6b
4530018
09b1f6b
 
9fdd31e
 
 
 
 
09b1f6b
9fdd31e
 
baae1a3
 
9fdd31e
 
09b1f6b
9151c0c
 
 
 
9fdd31e
9151c0c
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
9151c0c
9fdd31e
9151c0c
 
 
9fdd31e
9151c0c
 
9fdd31e
9151c0c
 
 
09b1f6b
 
4530018
 
 
09b1f6b
 
 
 
 
 
 
9151c0c
09b1f6b
 
 
baae1a3
 
 
 
 
9fdd31e
09b1f6b
9fdd31e
 
baae1a3
 
09b1f6b
9fdd31e
 
 
 
 
 
 
 
 
 
9151c0c
 
 
9fdd31e
 
 
 
 
9151c0c
9fdd31e
9151c0c
9fdd31e
 
 
09b1f6b
9fdd31e
09b1f6b
9fdd31e
9151c0c
9fdd31e
9151c0c
9fdd31e
9151c0c
4530018
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
09b1f6b
589c5f2
09b1f6b
9151c0c
 
9fdd31e
9151c0c
 
09b1f6b
589c5f2
09b1f6b
9151c0c
9fdd31e
9151c0c
9fdd31e
589c5f2
 
 
 
 
9151c0c
9fdd31e
9151c0c
9fdd31e
 
 
 
09b1f6b
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
9fdd31e
9151c0c
 
9fdd31e
589c5f2
9151c0c
9fdd31e
 
 
 
 
9151c0c
 
9fdd31e
9151c0c
9fdd31e
 
 
 
9151c0c
9fdd31e
 
 
 
 
 
9151c0c
9fdd31e
 
 
 
 
 
9151c0c
9fdd31e
9151c0c
9fdd31e
 
 
 
 
 
 
 
589c5f2
9fdd31e
 
 
9151c0c
9fdd31e
9151c0c
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
5afdc5e
9151c0c
5e5f525
 
 
 
 
 
9151c0c
5e5f525
9151c0c
 
9a91292
9151c0c
 
9fdd31e
9151c0c
127da28
09b1f6b
127da28
09b1f6b
127da28
09b1f6b
9a91292
09b1f6b
9a91292
09b1f6b
9a91292
09b1f6b
1b526a1
09b1f6b
d3908cc
09b1f6b
d3908cc
09b1f6b
d3908cc
09b1f6b
d3908cc
09b1f6b
d3908cc
09b1f6b
127da28
09b1f6b
127da28
 
9151c0c
9fdd31e
 
 
 
 
 
 
 
 
 
09b1f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
127da28
9fdd31e
09b1f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
09b1f6b
 
 
 
 
9151c0c
09b1f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c75d8
 
9fdd31e
 
09b1f6b
9fdd31e
 
 
 
09b1f6b
 
9fdd31e
 
 
 
298111d
09b1f6b
9fdd31e
 
09b1f6b
 
9fdd31e
 
09b1f6b
9fdd31e
 
baae1a3
09b1f6b
9fdd31e
09b1f6b
9fdd31e
09b1f6b
 
 
 
9fdd31e
09b1f6b
 
9fdd31e
 
09b1f6b
 
9fdd31e
9151c0c
09b1f6b
 
 
9151c0c
5e5f525
09b1f6b
9151c0c
 
 
127da28
 
9151c0c
 
 
 
a8c75d8
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baae1a3
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
 
 
 
9fdd31e
4530018
9fdd31e
 
9151c0c
589c5f2
9151c0c
9fdd31e
589c5f2
9151c0c
9fdd31e
9151c0c
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baae1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
 
 
 
 
baae1a3
 
 
 
 
 
9fdd31e
 
 
 
 
baae1a3
4530018
 
 
 
 
 
 
 
 
 
 
09b1f6b
4530018
 
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
 
4530018
baae1a3
09b1f6b
 
 
9fdd31e
09b1f6b
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
9fdd31e
baae1a3
 
 
9fdd31e
 
09b1f6b
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c75d8
9fdd31e
 
 
09b1f6b
a8c75d8
 
 
 
09b1f6b
 
 
a8c75d8
 
 
09b1f6b
a8c75d8
71c173f
a8c75d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71c173f
a8c75d8
71c173f
 
09b1f6b
a8c75d8
 
09b1f6b
a8c75d8
 
 
9151c0c
 
 
a8c75d8
9151c0c
 
 
 
 
 
 
9fdd31e
9151c0c
9fdd31e
9151c0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
9151c0c
 
a8c75d8
9fdd31e
 
 
 
 
 
 
 
 
 
 
9151c0c
9fdd31e
 
 
 
127da28
 
9151c0c
 
9ef1f27
 
 
 
9151c0c
baae1a3
9fdd31e
 
9151c0c
 
 
9fdd31e
 
 
 
 
 
 
9151c0c
 
9fdd31e
 
 
9151c0c
 
 
9fdd31e
9151c0c
 
 
 
baae1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
4530018
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298111d
4530018
9fdd31e
9151c0c
 
 
9fdd31e
 
9151c0c
 
 
 
baae1a3
 
 
 
9151c0c
7e7da4d
9151c0c
9ef1f27
9151c0c
7e7da4d
9151c0c
 
9a91292
9fdd31e
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
9fdd31e
9151c0c
09b1f6b
9fdd31e
 
09b1f6b
 
9fdd31e
 
09b1f6b
9fdd31e
 
 
 
 
 
9151c0c
9fdd31e
 
 
 
 
 
 
298111d
09b1f6b
 
298111d
9151c0c
7e7da4d
 
9151c0c
 
 
9fdd31e
 
 
9151c0c
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
 
9fdd31e
9151c0c
 
9fdd31e
 
 
 
 
 
baae1a3
 
 
 
 
 
9fdd31e
 
 
09b1f6b
baae1a3
9fdd31e
 
09b1f6b
 
 
 
 
 
 
 
 
9fdd31e
 
baae1a3
9fdd31e
 
9151c0c
 
9fdd31e
9151c0c
9fdd31e
 
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
9151c0c
9fdd31e
9151c0c
9fdd31e
 
 
 
 
 
 
 
 
 
 
9151c0c
9fdd31e
9151c0c
9fdd31e
 
 
 
 
127da28
9a91292
9fdd31e
 
9151c0c
baae1a3
 
 
 
 
09b1f6b
9fdd31e
 
9151c0c
9fdd31e
 
 
 
 
 
9151c0c
9fdd31e
9151c0c
 
 
9fdd31e
 
 
9151c0c
7e7da4d
9ef1f27
 
 
 
9151c0c
 
 
 
 
 
9a91292
9fdd31e
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
9151c0c
9fdd31e
 
 
9151c0c
9fdd31e
 
 
 
 
 
9768e46
 
 
9fdd31e
 
9768e46
9fdd31e
baae1a3
 
 
 
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
9a91292
9fdd31e
 
 
 
9151c0c
 
9fdd31e
 
 
 
 
 
127da28
baae1a3
 
 
 
9151c0c
 
 
 
9fdd31e
 
9a91292
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
9a91292
 
 
 
 
 
9768e46
 
9a91292
 
 
c79f542
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
127da28
 
 
9768e46
127da28
 
 
 
9a91292
 
 
127da28
 
 
 
 
 
 
 
 
 
09b1f6b
 
 
 
 
 
 
127da28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
3ccd3f5
9768e46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ccd3f5
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127da28
 
9fdd31e
 
127da28
9fdd31e
127da28
9fdd31e
127da28
9fdd31e
127da28
9fdd31e
127da28
9fdd31e
127da28
9fdd31e
127da28
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
4530018
09b1f6b
9fdd31e
4530018
298111d
4530018
 
 
 
 
298111d
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baae1a3
 
9fdd31e
baae1a3
9fdd31e
 
baae1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4530018
09b1f6b
4530018
 
09b1f6b
298111d
9fdd31e
 
baae1a3
9fdd31e
baae1a3
09b1f6b
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298111d
4530018
09b1f6b
 
4530018
298111d
4530018
 
 
 
 
09b1f6b
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baae1a3
9fdd31e
 
 
 
baae1a3
9fdd31e
baae1a3
9fdd31e
 
 
 
baae1a3
9fdd31e
baae1a3
9fdd31e
 
 
baae1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
9fdd31e
 
 
 
 
 
 
 
9151c0c
baae1a3
 
9fdd31e
 
 
baae1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
 
baae1a3
9fdd31e
 
 
baae1a3
9fdd31e
baae1a3
 
9fdd31e
 
baae1a3
9fdd31e
 
 
baae1a3
 
9fdd31e
 
 
 
baae1a3
 
 
9fdd31e
 
 
baae1a3
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9768e46
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
 
 
5afdc5e
589c5f2
9151c0c
9fdd31e
d3908cc
9151c0c
9fdd31e
9151c0c
9fdd31e
9a91292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09b1f6b
9151c0c
9fdd31e
 
 
 
 
 
 
 
127da28
 
 
 
 
 
 
 
 
 
 
09b1f6b
127da28
 
 
 
9a91292
 
298111d
09b1f6b
127da28
 
 
 
09b1f6b
9fdd31e
589c5f2
9fdd31e
 
 
 
 
 
 
 
 
 
9151c0c
9a91292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
 
 
 
127da28
9fdd31e
 
 
 
9151c0c
9fdd31e
 
 
9151c0c
9fdd31e
 
 
 
 
 
ae8a640
9fdd31e
9151c0c
127da28
9a91292
 
127da28
9151c0c
589c5f2
 
 
9fdd31e
589c5f2
127da28
 
 
9a91292
 
9151c0c
 
9fdd31e
9151c0c
9fdd31e
 
127da28
9fdd31e
9151c0c
5afdc5e
9fdd31e
 
 
 
 
 
 
 
 
127da28
4530018
9fdd31e
 
 
 
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baae1a3
9fdd31e
 
 
 
 
 
 
589c5f2
9fdd31e
 
9151c0c
589c5f2
9fdd31e
 
 
 
 
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
9fdd31e
9151c0c
127da28
 
9fdd31e
 
 
127da28
 
9a91292
9fdd31e
 
 
 
9151c0c
9fdd31e
 
 
 
 
127da28
9fdd31e
 
 
 
9151c0c
 
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127da28
 
 
 
 
9a91292
127da28
 
09b1f6b
127da28
 
 
 
 
 
 
 
4a9487a
127da28
4a9487a
 
 
9768e46
 
4a9487a
127da28
 
 
 
 
 
 
 
4a9487a
127da28
4a9487a
127da28
4a9487a
127da28
 
 
 
 
 
 
 
 
9fdd31e
4a9487a
9fdd31e
baae1a3
 
 
 
 
 
 
 
 
 
 
 
4530018
baae1a3
9fdd31e
baae1a3
 
 
 
 
9fdd31e
09b1f6b
 
4530018
 
 
 
 
 
 
09b1f6b
 
 
4530018
 
9fdd31e
baae1a3
9fdd31e
 
 
baae1a3
9fdd31e
baae1a3
 
9fdd31e
baae1a3
 
 
 
 
 
 
 
 
9fdd31e
 
baae1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
baae1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fdd31e
baae1a3
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127da28
 
9a91292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127da28
9151c0c
 
589c5f2
9fdd31e
 
 
 
127da28
589c5f2
127da28
 
4a9487a
127da28
9a91292
c79f542
 
 
9151c0c
 
 
 
 
9fdd31e
 
 
 
 
 
9151c0c
9fdd31e
 
9151c0c
9fdd31e
 
 
 
9151c0c
9fdd31e
9151c0c
9a91292
 
 
9151c0c
589c5f2
9fdd31e
589c5f2
9fdd31e
 
 
 
 
 
9151c0c
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
9fdd31e
 
5afdc5e
9fdd31e
9151c0c
9a91292
 
 
9fdd31e
 
127da28
9fdd31e
 
9151c0c
127da28
 
9fdd31e
 
 
 
127da28
 
 
 
9fdd31e
 
 
9151c0c
9fdd31e
9151c0c
9fdd31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
c79f542
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9151c0c
 
 
9fdd31e
589c5f2
9151c0c
9fdd31e
 
 
9768e46
589c5f2
9151c0c
9fdd31e
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
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996

import os
import io
import base64
import json
import logging
import threading
import time
from datetime import datetime, timedelta, timezone
from uuid import uuid4
import random
import string
import queue

from flask import Flask, render_template_string, request, redirect, url_for, flash, jsonify, Response
from PIL import Image
import google.generativeai as genai
import numpy as np
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
from werkzeug.utils import secure_filename
from dotenv import load_dotenv
import requests

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from webdriver_manager.chrome import ChromeDriverManager


load_dotenv()

app = Flask(__name__)
app.secret_key = 'your_unique_secret_key_gippo_312_shop_54321_no_login'
DATA_FILE = 'data.json'

SYNC_FILES = [DATA_FILE]

REPO_ID = "Kgshop/metastoretest"
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")

DOWNLOAD_RETRIES = 3
DOWNLOAD_DELAY = 5

ALMATY_TZ = timezone(timedelta(hours=6))

CURRENCIES = {
    'KGS': 'Кыргызский сом',
    'KZT': 'Казахстанский тенге',
    'UAH': 'Украинская гривна',
    'RUB': 'Российский рубль',
    'USD': 'Доллар США',
    'EUR': 'Евро'
}

COLOR_SCHEMES = {
    'default': 'Бирюзовый (по умолч.)',
    'forest': 'Лесной зеленый',
    'ocean': 'Глубокий синий',
    'sunset': 'Закатный оранжевый',
    'lavender': 'Лавандовый',
    'vintage': 'Винтажный',
    'dark': 'Полночь (тёмная)',
    'cosmic': 'Космическая ночь',
    'minty': 'Свежая мята',
    'mocha': 'Кофейный мокко',
    'crimson': 'Багровый рассвет',
    'solar': 'Солнечная вспышка',
    'cyberpunk': 'Киберпанк неон'
}

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

driver = None
whatsapp_thread = None
whatsapp_env_id = None
whatsapp_queues = {
    'incoming': queue.Queue(),
    'outgoing': queue.Queue()
}
whatsapp_active = threading.Event()

def whatsapp_bot_thread(env_id):
    global driver, whatsapp_env_id
    whatsapp_env_id = env_id
    
    try:
        chrome_options = ChromeOptions()
        user_data_dir = os.path.join(os.getcwd(), "whatsapp_profile")
        os.makedirs(user_data_dir, exist_ok=True)
        chrome_options.add_argument(f"--user-data-dir={user_data_dir}")
        chrome_options.add_argument("--headless=new")
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--disable-dev-shm-usage")
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

        try:
            service = ChromeService(ChromeDriverManager().install())
            driver = webdriver.Chrome(service=service, options=chrome_options)
        except Exception as e:
            logging.error(f"Could not start WebDriver with manager: {e}. Falling back to default.")
            driver = webdriver.Chrome(options=chrome_options)

        driver.get("https://web.whatsapp.com")
        logging.info("WhatsApp Web page opened. Please scan the QR code if required.")

        wait = WebDriverWait(driver, 60)
        wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="side"]/div[1]/div/div[2]/div[2]/div/div[1]/p'))) # Wait for search bar
        logging.info("WhatsApp Web is logged in and ready.")
        whatsapp_active.set()
        
        processor = threading.Thread(target=process_whatsapp_queues, daemon=True)
        processor.start()

        last_processed_messages = {}

        while whatsapp_active.is_set():
            try:
                unread_chats = driver.find_elements(By.XPATH, '//span[@data-testid="icon-unread-count"]')
                for chat in unread_chats:
                    try:
                        parent_element = chat.find_element(By.XPATH, './ancestor::div[contains(@class, "_aou8")]')
                        parent_element.click()
                        time.sleep(1) 

                        chat_title_element = driver.find_element(By.XPATH, '//header//span[@dir="auto"]')
                        chat_name = chat_title_element.text
                        
                        messages = driver.find_elements(By.XPATH, '//div[contains(@class, "message-in")]')
                        if messages:
                            last_message = messages[-1]
                            message_text_element = last_message.find_element(By.XPATH, './/span[contains(@class, "selectable-text")]/span')
                            message_text = message_text_element.text
                            
                            if last_processed_messages.get(chat_name) != message_text:
                                logging.info(f"New message from '{chat_name}': {message_text}")
                                whatsapp_queues['incoming'].put({'sender': chat_name, 'message': message_text})
                                last_processed_messages[chat_name] = message_text

                    except (NoSuchElementException, StaleElementReferenceException):
                        continue
                time.sleep(5)
            except Exception as e:
                logging.error(f"Error in WhatsApp listener loop: {e}")
                time.sleep(10)

    except TimeoutException:
        logging.error("Timed out waiting for WhatsApp Web to load. Please scan the QR code faster or check your connection.")
    except Exception as e:
        logging.error(f"An error occurred in the WhatsApp bot thread: {e}")
    finally:
        if driver:
            driver.quit()
        driver = None
        whatsapp_active.clear()
        logging.info("WhatsApp bot thread has stopped.")


def process_whatsapp_queues():
    while whatsapp_active.is_set():
        try:
            # Process incoming messages
            if not whatsapp_queues['incoming'].empty():
                data = whatsapp_queues['incoming'].get()
                sender = data['sender']
                message = data['message']
                
                # Simple chat history management (in-memory for this example)
                # For a real app, this should be persisted in data.json
                if 'whatsapp_chats' not in app.config:
                    app.config['whatsapp_chats'] = {}
                if sender not in app.config['whatsapp_chats']:
                    app.config['whatsapp_chats'][sender] = []

                history = app.config['whatsapp_chats'][sender]

                ai_response = generate_chat_response(message, history, whatsapp_env_id)
                
                history.append({'role': 'user', 'text': message})
                history.append({'role': 'ai', 'text': ai_response})
                # Trim history to keep it from growing too large
                app.config['whatsapp_chats'][sender] = history[-20:]

                whatsapp_queues['outgoing'].put({'recipient': sender, 'message': ai_response})

            # Process outgoing messages
            if not whatsapp_queues['outgoing'].empty():
                data = whatsapp_queues['outgoing'].get()
                send_whatsapp_message(data['recipient'], data['message'])

            time.sleep(1)
        except Exception as e:
            logging.error(f"Error processing WhatsApp queues: {e}")


def send_whatsapp_message(recipient, message):
    if not driver or not whatsapp_active.is_set():
        logging.warning("WhatsApp driver not ready, cannot send message.")
        return

    try:
        search_box = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//*[@id="side"]/div[1]/div/div[2]/div[2]/div/div[1]/p'))
        )
        search_box.clear()
        search_box.send_keys(recipient)
        time.sleep(2)

        chat = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, f'//span[@title="{recipient}"]'))
        )
        chat.click()
        time.sleep(1)

        message_box = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]/p'))
        )

        for line in message.split('\n'):
            message_box.send_keys(line)
            message_box.send_keys(Keys.SHIFT, Keys.ENTER)
        
        message_box.send_keys(Keys.ENTER)
        logging.info(f"Message sent to '{recipient}'.")

    except TimeoutException:
        logging.error(f"Could not find chat or message box for '{recipient}'.")
    except Exception as e:
        logging.error(f"Failed to send WhatsApp message to '{recipient}': {e}")


def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY):
    if not HF_TOKEN_READ and not HF_TOKEN_WRITE:
        logging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.")

    token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE

    files_to_download = [specific_file] if specific_file else SYNC_FILES
    all_successful = True

    for file_name in files_to_download:
        success = False
        for attempt in range(retries + 1):
            try:
                local_path = hf_hub_download(
                    repo_id=REPO_ID,
                    filename=file_name,
                    repo_type="dataset",
                    token=token_to_use,
                    local_dir=".",
                    local_dir_use_symlinks=False,
                    force_download=True,
                    resume_download=False
                )
                success = True
                break
            except RepositoryNotFoundError:
                 return False
            except HfHubHTTPError as e:
                if e.response.status_code == 404:
                    if attempt == 0 and not os.path.exists(file_name):
                        try:
                            if file_name == DATA_FILE:
                                with open(file_name, 'w', encoding='utf-8') as f:
                                    json.dump({}, f)
                        except Exception as create_e:
                            pass
                    success = False
                    break
                else:
                    pass
            except requests.exceptions.RequestException as e:
                 pass
            except Exception as e:
                 pass

            if attempt < retries:
                time.sleep(delay)

        if not success:
            all_successful = False

    return all_successful

def upload_db_to_hf(specific_file=None):
    if not HF_TOKEN_WRITE:
        return
    try:
        api = HfApi()
        files_to_upload = [specific_file] if specific_file else SYNC_FILES

        for file_name in files_to_upload:
            if os.path.exists(file_name):
                try:
                    api.upload_file(
                        path_or_fileobj=file_name,
                        path_in_repo=file_name,
                        repo_id=REPO_ID,
                        repo_type="dataset",
                        token=HF_TOKEN_WRITE,
                        commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
                    )
                except Exception as e:
                     pass
            else:
                pass
    except Exception as e:
        pass

def periodic_backup():
    backup_interval = 1800
    while True:
        time.sleep(backup_interval)
        upload_db_to_hf()

def load_data():
    try:
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            data = json.load(f)
        if not isinstance(data, dict):
            data = {}
    except (FileNotFoundError, json.JSONDecodeError):
        if download_db_from_hf(specific_file=DATA_FILE):
            try:
                with open(DATA_FILE, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                if not isinstance(data, dict):
                    data = {}
            except (FileNotFoundError, json.JSONDecodeError):
                data = {}
        else:
            data = {}
    return data

def save_data(data):
    try:
        with open(DATA_FILE, 'w', encoding='utf-8') as file:
            json.dump(data, file, ensure_ascii=False, indent=4)
        upload_db_to_hf(specific_file=DATA_FILE)
    except Exception as e:
        pass

def is_chat_active(env_id):
    data = get_env_data(env_id)
    settings = data.get('settings', {})
    
    if not settings.get('chat_activated', False):
        return False
        
    expires_str = settings.get('chat_activation_expires')
    if not expires_str:
        return False

    try:
        expires_dt = datetime.fromisoformat(expires_str)
        if expires_dt > datetime.now(ALMATY_TZ):
            return True
    except (ValueError, TypeError):
        return False
        
    return False

def get_env_data(env_id):
    all_data = load_data()
    default_organization_info = {
        "about_us": "Мы — надежный партнер в мире уникальных товаров. Мы предлагаем широкий ассортимент продукции, от электроники до товаров для дома, всегда стремясь к качеству и доступности. Наша миссия — сделать ваш шопинг приятным и удобным, предлагая только лучшие товары, тщательно отобранные для вас.",
        "shipping": "Доставка осуществляется по всему Кыргызстану. Стоимость и сроки доставки зависят от региона и веса товара. По Бишкеку доставка возможна в течение 1-2 рабочих дней, в регионы — от 3 до 7 дней. Для уточнения деталей свяжитесь с нами.",
        "returns": "Возврат и обмен товара возможен в течение 14 дней с момента покупки, при условии сохранения товарного вида, упаковки и чека. Некоторые категории товаров могут иметь особые условия возврата. Пожалуйста, свяжитесь с нами для оформления возврата или обмена.",
        "contact": f"Наш магазин находится по адресу: Рынок Кербен, 6 ряд , 43 контейнер. Связаться с нами можно по телефону или через WhatsApp. Мы работаем ежедневно с 9:00 до 18:00."
    }
    default_settings = {
        "organization_name": "Gippo312",
        "whatsapp_number": "+996701202013",
        "currency_code": "KGS",
        "chat_name": "EVA",
        "chat_avatar": None,
        "color_scheme": "default",
        "chat_activated": False,
        "chat_activation_expires": None,
        "business_type": "combined"
    }

    env_data = all_data.get(env_id, {})
    if not env_data:
        env_data = {
            'products': [], 'categories': [], 'orders': {}, 'chats': {},
            'organization_info': default_organization_info,
            'settings': default_settings
        }

    if 'products' not in env_data: env_data['products'] = []
    if 'categories' not in env_data: env_data['categories'] = []
    if 'orders' not in env_data: env_data['orders'] = {}
    if 'organization_info' not in env_data: env_data['organization_info'] = default_organization_info
    if 'chats' not in env_data: env_data['chats'] = {}
    if 'settings' not in env_data: env_data['settings'] = default_settings
    
    settings_changed = False
    for key, value in default_settings.items():
        if key not in env_data['settings']:
            env_data['settings'][key] = value
            settings_changed = True

    products_changed = False
    for product in env_data['products']:
        if 'product_id' not in product:
            product['product_id'] = uuid4().hex
            products_changed = True
        if 'sizes' not in product:
            product['sizes'] = []
            products_changed = True
        if 'variant_prices' not in product:
            product['variant_prices'] = {}
            products_changed = True
        if 'wholesale_price' not in product:
            product['wholesale_price'] = None
            products_changed = True
        if 'min_wholesale_quantity' not in product:
            product['min_wholesale_quantity'] = None
            products_changed = True

    if products_changed or settings_changed:
        save_env_data(env_id, env_data)

    return env_data


def save_env_data(env_id, env_data):
    all_data = load_data()
    all_data[env_id] = env_data
    save_data(all_data)

def configure_gemini():
    if not GOOGLE_API_KEY:
        return False
    try:
        genai.configure(api_key=GOOGLE_API_KEY)
        return True
    except Exception as e:
        return False

def generate_ai_description_from_image(image_data, language):
    if not configure_gemini():
        raise ValueError("Google AI API не настроен.")

    try:
        if not image_data:
             raise ValueError("Файл изображения не найден.")
        image_stream = io.BytesIO(image_data)
        image = Image.open(image_stream).convert('RGB')
    except Exception as e:
        raise ValueError(f"Не удалось обработать изображение. Убедитесь, что это действительный файл изображения.")

    base_prompt = "Напиши большой и красивый, содержательный рекламный пост минимум на 1000 символов со смайликами и 25 тематических хэштегов с ключевыми словами разных вариантов, чтобы мои клиенты могли найти меня в поиске Instagram, Google и т.д. по ключевым словам. Пост пиши исключительно под товар, который на фото, без адресов и номеров телефона."

    lang_suffix = ""
    if language == "Русский":
        lang_suffix = " Пиши на русском языке."
    elif language == "Кыргызский":
        lang_suffix = " Пиши на кыргызском языке."
    elif language == "Казахский":
        lang_suffix = " Пиши на казахском языке."
    elif language == "Узбекский":
        lang_suffix = " Пиши на узбекском языке."

    final_prompt = f"{base_prompt}{lang_suffix}"

    try:
        model = genai.GenerativeModel('gemma-3-27b-it')

        response = model.generate_content([final_prompt, image])

        if hasattr(response, 'text'):
            return response.text
        else:
            if response.parts:
                 return "".join(part.text for part in response.parts if hasattr(part, 'text'))
            else:
                response.resolve()
                return response.text

    except Exception as e:
        if "API key not valid" in str(e):
             raise ValueError("Внутренняя ошибка конфигурации API.")
        elif " Billing account not found" in str(e):
             raise ValueError("Проблема с биллингом аккаунта Google Cloud. Проверьте ваш аккаунт.")
        elif "Could not find model" in str(e):
             raise ValueError(f"Модель 'learnlm-2.0-flash-experimental' не найдена или недоступна.")
        elif "resource has been exhausted" in str(e).lower():
             raise ValueError("Квота запросов исчерпана. Попробуйте позже.")
        elif "content has been blocked" in str(e).lower():
             reason = "неизвестна"
             if hasattr(e, 'response') and hasattr(e.response, 'prompt_feedback') and e.response.prompt_feedback.block_reason:
                reason = e.response.prompt_feedback.block_reason
             raise ValueError(f"Генерация контента заблокирована из-за политики безопасности (причина: {reason}). Попробуйте другое изображение или запрос.)")
        else:
             raise ValueError(f"Ошибка при генерации контента: {e}")

def generate_chat_response(message, chat_history_from_client, env_id):
    if not is_chat_active(env_id):
        return "Извините, чат в данный момент неактивен. Пожалуйста, свяжитесь с нами другим способом."
    
    if not configure_gemini():
        return "Извините, сервис чата временно недоступен. Пожалуйста, попробуйте позже."

    data = get_env_data(env_id)
    products = data.get('products', [])
    categories = data.get('categories', [])
    organization_info = data.get('organization_info', {})
    settings = data.get('settings', {})
    currency_code = settings.get('currency_code', 'KGS')
    chat_name = settings.get('chat_name', 'EVA')
    org_name = settings.get('organization_name', 'Gippo312')
    business_type = settings.get('business_type', 'combined')

    product_info_list = []
    for p in products:
        if p.get('in_stock', True):
            price_display = f"{p.get('price', 0):.2f}".replace('.00', '')
            
            wholesale_info = ""
            if business_type in ['wholesale', 'combined'] and p.get('wholesale_price') and p.get('min_wholesale_quantity'):
                wholesale_price_display = f"{p['wholesale_price']:.2f}".replace('.00', '')
                wholesale_info = (f", Оптовая цена: {wholesale_price_display} {currency_code} "
                                  f"(от {p['min_wholesale_quantity']} шт.)")

            colors_str = f"Цвета: {', '.join(p.get('colors', []))}" if p.get('colors') else ""
            sizes_str = f"Размеры: {', '.join(p.get('sizes', []))}" if p.get('sizes') else ""
            
            options_str = ""
            if colors_str or sizes_str:
                options_str = f", Варианты: ({' '.join(filter(None, [colors_str, sizes_str]))})"
            
            variant_prices_str = ""
            if p.get('variant_prices'):
                variant_prices_list = [f"{k.replace('-', ' ')} - {v} {currency_code}" for k, v in p['variant_prices'].items()]
                if variant_prices_list:
                    variant_prices_str = f", Особые цены: [{'; '.join(variant_prices_list)}]"

            product_info_list.append(
                f"- [ID_ТОВАРА: {p.get('product_id', 'N/A')} Название: {p.get('name', 'Без названия')}], "
                f"Категория: {p.get('category', 'Без категории')}, "
                f"Розничная цена: {price_display} {currency_code}"
                f"{wholesale_info}"
                f"{options_str}{variant_prices_str}, "
                f"Описание: {p.get('description', '')[:100]}..."
            )
    product_list_str = "\n".join(product_info_list) if product_info_list else "В данный момент нет товаров в наличии."

    category_list_str = ", ".join(categories) if categories else "Категорий пока нет."

    org_info_str = ""
    if organization_info:
        org_info_str += "\n\nИнформация о магазине:\n"
        if organization_info.get("about_us"):
            org_info_str += f"О нас: {organization_info['about_us']}\n"
        if organization_info.get("shipping"):
            org_info_str += f"Доставка: {organization_info['shipping']}\n"
        if organization_info.get("returns"):
            org_info_str += f"Возврат и обмен: {organization_info['returns']}\n"
        if organization_info.get("contact"):
            org_info_str += f"Контактная информация: {organization_info['contact']}\n"
    
    
    base_prompt = (
        f"Ты — первоклассный виртуальный консультант-продажник по имени {chat_name} для магазина {org_name}. "
        "Говори на любом языке, на котором к тебе обращается клиент. Будь энергичным, убедительным и проактивным. "
        "Твоя речь должна быть живой, с использованием эмодзи, чтобы располагать к себе клиента. "
        "Никогда не выдумывай товары, категории или характеристики, которых нет в предоставленных списках. "
        "Когда ты предлагаешь товар, всегда указывай его название и ID, используя *точный формат*: [ID_ТОВАРА: <product_id> Название: <product_name>]. Это *критически важно* для клиента. "
        "Если пользователь спрашивает цену на конкретный вариант (цвет или размер), найди ее в 'Особые цены'. Если там нет, используй базовую цену. "
        "Создавай ощущение срочности: 'Эта модель сейчас очень популярна, осталось всего несколько штук!'. "
        "Работай с возражениями: если клиент говорит 'дорого', расскажи о качестве, гарантии и уникальных особенностях товара."
    )

    if business_type == 'retail':
        business_specific_prompt = (
            "Твоя главная цель — продавать розничным клиентам. Помогай пользователям находить товары, мастерски отвечай на вопросы о них, предлагай лучшие варианты, создавай ценность и закрывай сделку. "
            "Активно предлагай сопутствующие товары или более дорогие аналоги (апсейл). Например: 'Отличный выбор! К этому телефону идеально подойдут наши новые беспроводные наушники. Хотите взглянуть?'. "
        )
    elif business_type == 'wholesale':
        business_specific_prompt = (
            "Твоя главная цель — продавать товары оптом для бизнес-клиентов. "
            "Всегда уточняй, какой объем интересует клиента. Если клиент спрашивает цену, всегда предлагай оптовую цену и условия (минимальное количество). "
            "Подчеркивай выгоду больших партий и возможность долгосрочного сотрудничества. Например: 'При покупке от 50 единиц цена будет значительно ниже. Какой объем вас интересует для вашего бизнеса?'. "
            "Твоя задача — находить крупных клиентов и заключать большие сделки."
        )
    else: 
        business_specific_prompt = (
            "Твоя главная цель — продавать товары как в розницу, так и оптом. В начале диалога вежливо уточни у клиента, интересует ли его розничная или оптовая покупка, чтобы сделать наилучшее предложение. "
            "Для розничных клиентов: предлагай сопутствующие товары, рассказывай о преимуществах. "
            "Для оптовых клиентов: сообщай об оптовых ценах и минимальном количестве для заказа. Подчеркивай выгоду крупных партий. "
            "Четко разделяй предложения для разных типов клиентов. Например: 'Вас интересует покупка для себя или для бизнеса? У нас есть отличные условия для оптовиков!'. "
        )


    system_instruction_content = (
        f"{base_prompt}\n{business_specific_prompt}\n\n"
        f"Список доступных категорий: {category_list_str}.\n\n"
        f"Список доступных товаров в магазине (используй эту информацию для ответов):\n"
        f"{product_list_str}"
        f"{org_info_str}\n\n"
        "Если пользователь спрашивает про товары, которых нет, вежливо сообщи об этом и немедленно предложи лучшую альтернативу из имеющихся. "
        "Если вопрос касается общей информации о магазине (доставка, возврат), используй данные из блока 'Информация о магазине' и сразу после ответа возвращай разговор к покупкам: 'Кстати, я могу помочь вам подобрать что-нибудь еще?'. "
        "Твоя конечная цель — довольный клиент, который совершил покупку. Действуй!"
    )


    generated_text = ""
    response = None

    try:
        model = genai.GenerativeModel('gemma-3-27b-it')

        model_chat_history_for_gemini = [
            {'role': 'user', 'parts': [{'text': system_instruction_content}]}
        ]
        for entry in chat_history_from_client:
            gemini_role = 'model' if entry['role'] == 'ai' else 'user'
            model_chat_history_for_gemini.append({
                'role': gemini_role,
                'parts': [{'text': entry['text']}]
            })

        chat = model.start_chat(history=model_chat_history_for_gemini)

        response = chat.send_message(message, generation_config={'max_output_tokens': 1000})

        if hasattr(response, 'text'):
            generated_text = response.text
        elif response.parts:
            generated_text = "".join(part.text for part in response.parts if hasattr(part, 'text'))
        else:
            response.resolve()
            if hasattr(response, 'text'):
                generated_text = response.text
            else:
                raise ValueError("AI did not return a valid text response.")

        return generated_text

    except Exception as e:
        if "API key not valid" in str(e):
             return "Внутренняя ошибка конфигурации API."
        elif " Billing account not found" in str(e):
             return "Проблема с биллингом аккаунта Google Cloud."
        elif "Could not find model" in str(e):
             return "Модель AI не найдена или недоступна."
        elif "resource has been exhausted" in str(e).lower():
             return "Квота запросов исчерпана. Попробуйте позже."
        elif "content has been blocked" in str(e).lower() or (response is not None and hasattr(response, 'prompt_feedback') and response.prompt_feedback.block_reason):
             reason = response.prompt_feedback.block_reason if (response and hasattr(response, 'prompt_feedback')) else "неизвестна"
             return f"Извините, Ваш запрос был заблокирован из-за политики безопасности (причина: {reason}). Пожалуйста, переформулируйте его."
        else:
             return f"Извините, произошла ошибка: {e}"

LANDING_PAGE_TEMPLATE = '''
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> MetaStore - AI система для Вашего Бизнеса</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            overflow: hidden;
        }
        iframe {
            border: none;
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <iframe src="https://v0-ai-agent-landing-page-smoky-six.vercel.app/"></iframe>
</body>
</html>
'''

ADMHOSTO_TEMPLATE = '''
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Главная Админ-панель</title>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        :root {
            --bg-light: #f4f6f9;
            --bg-medium: #135D66;
            --accent: #48D1CC;
            --accent-hover: #77E4D8;
            --text-dark: #333;
            --text-on-accent: #003C43;
            --danger: #E57373;
            --warning: #ffcc80;
            --warning-text: #856404;
        }
        body { font-family: 'Montserrat', sans-serif; background-color: var(--bg-light); color: var(--text-dark); padding: 20px; }
        .container { max-width: 900px; margin: 0 auto; background-color: #fff; padding: 25px; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.05); }
        h1 { font-weight: 600; color: var(--bg-medium); margin-bottom: 25px; text-align: center; }
        .section { margin-bottom: 30px; }
        .add-env-form { margin-bottom: 20px; text-align: center; }
        #search-env {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            box-sizing: border-box;
            font-size: 1rem;
            font-family: 'Montserrat', sans-serif;
        }
        .button { padding: 10px 18px; border: none; border-radius: 6px; background-color: var(--accent); color: var(--text-on-accent); font-weight: 600; cursor: pointer; transition: background-color 0.3s ease; text-decoration: none; display: inline-flex; align-items: center; gap: 5px; }
        .button:hover { background-color: var(--accent-hover); }
        .button:disabled { background-color: #ccc; cursor: not-allowed; }
        .env-list { list-style: none; padding: 0; }
        .env-item { background: #fdfdff; border: 1px solid #e0e0e0; border-radius: 8px; padding: 15px; margin-bottom: 10px; display: grid; grid-template-columns: 1fr auto; align-items: center; gap: 15px; }
        .env-details { display: flex; flex-direction: column; }
        .env-id { font-weight: 600; color: var(--bg-medium); font-size: 1.2rem; }
        .env-status { font-size: 0.85rem; color: #666; }
        .env-status .expires-soon { color: var(--danger); font-weight: bold; }
        .env-actions { display: flex; gap: 10px; flex-wrap: wrap; justify-content: flex-end;}
        .delete-button { background-color: var(--danger); color: white; }
        .activate-button { background-color: #66BB6A; color: white; }
        .message { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; text-align: center; }
        .message.success { background-color: #d4edda; color: #155724; }
        .message.error { background-color: #f8d7da; color: #721c24; }
        @media (max-width: 768px) {
            .env-item {
                grid-template-columns: 1fr;
            }
            .env-actions {
                justify-content: flex-start;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1><i class="fas fa-server"></i> Управление Средами</h1>
        
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="message {{ category }}">{{ message }}</div>
                {% endfor %}
            {% endif %}
        {% endwith %}

        <div class="section">
            <form method="POST" action="{{ url_for('create_environment') }}" class="add-env-form">
                <button type="submit" class="button"><i class="fas fa-plus-circle"></i> Создать новую среду</button>
            </form>
        </div>

        <div class="section">
            <input type="text" id="search-env" placeholder="Поиск по ID среды...">
        </div>

        <div class="section">
            <h2><i class="fas fa-list-ul"></i> Существующие среды</h2>
            {% if environments %}
            <ul class="env-list">
                {% for env in environments %}
                <li class="env-item">
                    <div class="env-details">
                        <span class="env-id">{{ env.id }}</span>
                        <div class="env-status">
                            {% if env.chat_active %}
                                Активирован до: <span class="{{ 'expires-soon' if env.expires_soon else '' }}">{{ env.expires_date }}</span>
                            {% else %}
                                Чат не активирован
                            {% endif %}
                        </div>
                    </div>
                    <div class="env-actions">
                        <a href="{{ url_for('admin', env_id=env.id) }}" class="button" target="_blank"><i class="fas fa-tools"></i> Админ</a>
                        <a href="{{ url_for('catalog', env_id=env.id) }}" class="button" target="_blank"><i class="fas fa-store"></i> Каталог</a>
                        <form method="POST" action="{{ url_for('activate_chat', env_id=env.id) }}" style="display:inline-flex; gap: 5px; align-items: center;">
                           <select name="period" style="padding: 10px; border-radius: 4px; border: 1px solid #ccc; height: 100%;">
                               <option value="month">1 месяц</option>
                               <option value="half_year">6 месяцев</option>
                               <option value="year">1 год</option>
                           </select>
                           <button type="submit" class="button activate-button">
                                <i class="fas fa-check-circle"></i> {{ 'Продлить' if env.chat_active else 'Активировать' }}
                           </button>
                        </form>
                        <form method="POST" action="{{ url_for('delete_environment', env_id=env.id) }}" style="display:inline;" onsubmit="return confirm('Вы уверены, что хотите удалить среду {{ env.id }}? Это действие необратимо.');">
                            <button type="submit" class="button delete-button"><i class="fas fa-trash-alt"></i></button>
                        </form>
                    </div>
                </li>
                {% endfor %}
            </ul>
            {% else %}
            <p>Пока не создано ни одной среды.</p>
            {% endif %}
        </div>
    </div>
    <script>
        document.getElementById('search-env').addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase().trim();
            const envItems = document.querySelectorAll('.env-item');
            envItems.forEach(item => {
                const envId = item.querySelector('.env-id').textContent.toLowerCase();
                if (envId.includes(searchTerm)) {
                    item.style.display = 'grid';
                } else {
                    item.style.display = 'none';
                }
            });
        });
    </script>
</body>
</html>
'''

CATALOG_TEMPLATE = '''
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>{{ settings.organization_name }} - Каталог</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
    <style>
        {% if settings.color_scheme == 'forest' %}
        :root { --bg-dark: #2F4F4F; --bg-medium: #556B2F; --accent: #8FBC8F; --accent-hover: #98FB98; --text-light: #F5F5DC; --text-dark: #FFFFFF; --danger: #CD5C5C; --danger-hover: #F08080; }
        {% elif settings.color_scheme == 'ocean' %}
        :root { --bg-dark: #000080; --bg-medium: #1E90FF; --accent: #87CEEB; --accent-hover: #ADD8E6; --text-light: #F0F8FF; --text-dark: #000000; --danger: #FF6347; --danger-hover: #FF4500; }
        {% elif settings.color_scheme == 'sunset' %}
        :root { --bg-dark: #8B4513; --bg-medium: #D2691E; --accent: #FFA500; --accent-hover: #FFB733; --text-light: #FFF8DC; --text-dark: #000000; --danger: #DC143C; --danger-hover: #FF0000; }
        {% elif settings.color_scheme == 'lavender' %}
        :root { --bg-dark: #483D8B; --bg-medium: #8A2BE2; --accent: #D8BFD8; --accent-hover: #E6E6FA; --text-light: #F0F8FF; --text-dark: #000000; --danger: #DB7093; --danger-hover: #FFC0CB; }
        {% elif settings.color_scheme == 'vintage' %}
        :root { --bg-dark: #5D4037; --bg-medium: #8D6E63; --accent: #D7CCC8; --accent-hover: #EFEBE9; --text-light: #F5F5F5; --text-dark: #3E2723; --danger: #BF360C; --danger-hover: #F4511E; }
        {% elif settings.color_scheme == 'dark' %}
        :root { --bg-dark: #121212; --bg-medium: #1E1E1E; --accent: #BB86FC; --accent-hover: #A764FC; --text-light: #E1E1E1; --text-dark: #121212; --danger: #CF6679; --danger-hover: #D98899; }
        {% elif settings.color_scheme == 'cosmic' %}
        :root { --bg-dark: #1A237E; --bg-medium: #303F9F; --accent: #536DFE; --accent-hover: #7986CB; --text-light: #FFFFFF; --text-dark: #FFFFFF; --danger: #F50057; --danger-hover: #FF4081; }
        {% elif settings.color_scheme == 'minty' %}
        :root { --bg-dark: #004D40; --bg-medium: #00796B; --accent: #4DB6AC; --accent-hover: #80CBC4; --text-light: #E0F2F1; --text-dark: #FFFFFF; --danger: #ef5350; --danger-hover: #e57373; }
        {% elif settings.color_scheme == 'mocha' %}
        :root { --bg-dark: #3e2723; --bg-medium: #5d4037; --accent: #a1887f; --accent-hover: #bcaaa4; --text-light: #efebe9; --text-dark: #3e2723; --danger: #d32f2f; --danger-hover: #e57373; }
        {% elif settings.color_scheme == 'crimson' %}
        :root { --bg-dark: #6A1B9A; --bg-medium: #9C27B0; --accent: #CE93D8; --accent-hover: #E1BEE7; --text-light: #FFFFFF; --text-dark: #FFFFFF; --danger: #E91E63; --danger-hover: #F06292; }
        {% elif settings.color_scheme == 'solar' %}
        :root { --bg-dark: #E65100; --bg-medium: #FB8C00; --accent: #FFCA28; --accent-hover: #FFD54F; --text-light: #212121; --text-dark: #212121; --danger: #d32f2f; --danger-hover: #e57373; }
        {% elif settings.color_scheme == 'cyberpunk' %}
        :root { --bg-dark: #000000; --bg-medium: #0d0221; --accent: #00f0ff; --accent-hover: #81f5ff; --text-light: #ffffff; --text-dark: #000000; --danger: #f50057; --danger-hover: #ff4081; }
        {% else %}
        :root { --bg-dark: #003C43; --bg-medium: #135D66; --accent: #48D1CC; --accent-hover: #77E4D8; --text-light: #E3FEF7; --text-dark: #003C43; --danger: #E57373; --danger-hover: #EF5350; }
        {% endif %}

        * { margin: 0; padding: 0; box-sizing: border-box; }
        html { -webkit-tap-highlight-color: transparent; }
        body {
            font-family: 'Montserrat', sans-serif;
            background-color: var(--bg-dark);
            color: var(--text-light);
            line-height: 1.6;
        }
        .container {
            max-width: 1300px;
            margin: 0 auto;
            padding: 0 0 100px 0;
        }
        .top-bar {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            gap: 15px;
            position: sticky;
            top: 0;
            background-color: var(--bg-dark);
            z-index: 999;
            border-bottom: 1px solid var(--bg-medium);
        }
        .logo {
            flex-shrink: 0;
        }
        .logo img {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            border: 2px solid var(--accent);
        }
        .search-wrapper {
            flex-grow: 1;
            position: relative;
        }
        #search-input {
            width: 100%;
            padding: 12px 20px 12px 45px;
            font-size: 1rem;
            border: none;
            border-radius: 25px;
            outline: none;
            background-color: var(--bg-medium);
            color: var(--text-light);
            transition: all 0.3s ease;
        }
        #search-input::placeholder { color: rgba(227, 254, 247, 0.6); }
        .search-wrapper .fa-search {
            position: absolute;
            top: 50%;
            left: 18px;
            transform: translateY(-50%);
            color: rgba(227, 254, 247, 0.6);
            font-size: 1rem;
        }
        .category-section {
            margin-top: 20px;
        }
        .category-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
            margin-bottom: 15px;
        }
        .category-header h2 {
            font-size: 1.5rem;
            font-weight: 600;
        }
        .category-header .view-all-arrow {
            font-size: 1.8rem;
            color: var(--accent);
            text-decoration: none;
            font-weight: 300;
        }
        .product-carousel {
            display: flex;
            overflow-x: auto;
            gap: 16px;
            padding: 10px 20px;
            -webkit-overflow-scrolling: touch;
            scrollbar-width: none;
        }
        .product-carousel::-webkit-scrollbar { display: none; }
        .product-card {
            width: 170px;
            height: 170px;
            background: white;
            border-radius: 16px;
            flex-shrink: 0;
            overflow: hidden;
            cursor: pointer;
            transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
            position: relative;
        }
        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
        }
        .product-card:active { transform: scale(0.96); }
        .product-image-container {
            width: 100%;
            height: 100%;
        }
        .product-image-container img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .product-info-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(to top, rgba(0, 0, 0, 0.85) 0%, transparent 100%);
            padding: 20px 12px 10px;
            color: #fff;
            pointer-events: none;
        }
        .product-price {
            font-size: 1rem;
            font-weight: 600;
        }
        .top-product-indicator {
            position: absolute;
            top: 8px;
            right: 8px;
            background-color: var(--accent);
            color: var(--text-dark);
            padding: 2px 8px;
            font-size: 0.7rem;
            border-radius: 10px;
            font-weight: bold;
            z-index: 10;
        }
        .no-results-message { padding: 40px 20px; text-align: center; font-size: 1.1rem; color: #ccc; }
        .floating-buttons-container {
            position: fixed;
            bottom: 25px;
            right: 25px;
            display: flex;
            flex-direction: column;
            gap: 15px;
            z-index: 1000;
        }
        .floating-button {
            background-color: var(--accent);
            color: var(--text-dark);
            border: none;
            border-radius: 50%;
            width: 55px;
            height: 55px;
            font-size: 1.5rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 15px rgba(72, 209, 204, 0.4);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            text-decoration: none;
        }
        .floating-button:hover {
            background-color: var(--accent-hover);
            transform: translateY(-3px);
        }
        #cart-button { position: relative; }
        #cart-count {
            position: absolute;
            top: -2px;
            right: -2px;
            background-color: var(--danger);
            color: white;
            border-radius: 50%;
            padding: 2px 6px;
            font-size: 0.7rem;
            font-weight: bold;
            border: 2px solid var(--accent);
        }
        .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); backdrop-filter: blur(5px); overflow-y: auto; }
        .modal-content { background: #ffffff; color: var(--text-dark); margin: 5% auto; padding: 25px; border-radius: 15px; width: 90%; max-width: 700px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); animation: slideIn 0.3s ease-out; position: relative; }
        .dark-theme .modal-content { background: #2a2a2a; color: var(--text-light); }
        @keyframes slideIn { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
        .close { position: absolute; top: 15px; right: 15px; font-size: 1.8rem; color: #aaa; cursor: pointer; transition: color 0.3s; line-height: 1; }
        .close:hover { color: #666; }
        .modal-content h2 { margin-top: 0; margin-bottom: 20px; color: var(--bg-medium); display: flex; align-items: center; gap: 10px;}
        .cart-item { display: grid; grid-template-columns: 60px 1fr auto auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #e0e0e0; }
        .dark-theme .cart-item { border-bottom-color: #444; }
        .cart-item:last-child { border-bottom: none; }
        .cart-item img { width: 60px; height: 60px; object-fit: cover; border-radius: 8px; }
        .cart-item-details { grid-column: 2 / span 2; }
        .cart-item-details strong { display: block; margin-bottom: 5px; font-size: 1rem; }
        .dark-theme .cart-item-details strong { color: var(--text-light); }
        .cart-item-details .variant-info { font-size: 0.85rem; color: #666; }
        .dark-theme .cart-item-details .variant-info { color: #ccc; }
        .cart-item-price { font-size: 0.9rem; color: #666; }
        .dark-theme .cart-item-price { color: #ccc; }
        .cart-item-price .wholesale-label { color: var(--bg-medium); font-weight: bold; }
        .cart-item-quantity { display: flex; align-items: center; gap: 8px; grid-column: 1; grid-row: 2;}
        .quantity-btn { background-color: #eee; border: 1px solid #ddd; border-radius: 50%; width: 28px; height: 28px; cursor: pointer; font-size: 1.1rem; line-height: 1; display: flex; align-items: center; justify-content: center; }
        .dark-theme .quantity-btn { background-color: #444; border-color: #555; color: #fff; }
        .cart-item-total { font-weight: bold; text-align: right; grid-column: 3 / span 2; grid-row: 2; font-size: 1rem; color: var(--bg-medium);}
        .cart-item-remove { grid-column: 4; grid-row: 1; justify-self: end; background:none; border:none; color: var(--danger); cursor:pointer; font-size: 1.3em; padding: 5px; line-height: 1; }
        .cart-item-remove:hover { color: var(--danger-hover); }
        .quantity-input, .options-select { width: 100%; max-width: 180px; padding: 10px; border: 1px solid #e0e0e0; border-radius: 8px; font-size: 1rem; margin: 10px 0; box-sizing: border-box; }
        .dark-theme .quantity-input, .dark-theme .options-select { background-color: #333; color: #fff; border-color: #555; }
        .quantity-input:focus, .options-select:focus { border-color: var(--accent); outline: none; box-shadow: 0 0 0 2px rgba(72, 209, 204, 0.2); }
        .cart-summary { margin-top: 20px; text-align: right; border-top: 1px solid #e0e0e0; padding-top: 15px; }
        .dark-theme .cart-summary { border-top-color: #444; }
        .cart-summary strong { font-size: 1.2rem; color: var(--bg-medium);}
        .cart-actions { margin-top: 25px; display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
        .product-button { display: block; width: auto; flex-grow: 1; padding: 10px; border: none; border-radius: 8px; color: var(--text-dark); font-size: 0.9rem; font-weight: 500; cursor: pointer; transition: all 0.3s ease; text-align: center; text-decoration: none; }
        .product-button i { margin-right: 5px; }
        .clear-cart { background-color: #6c757d; color: white;}
        .clear-cart:hover { background-color: #5a6268; }
        .formulate-order-button { background-color: var(--accent); color: var(--text-dark); }
        .formulate-order-button:hover { background-color: var(--accent-hover); }
        .notification { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background-color: var(--accent); color: var(--text-dark); padding: 10px 20px; border-radius: 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.2); z-index: 1002; opacity: 0; transition: opacity 0.5s ease; font-size: 0.9rem;}
        .notification.show { opacity: 1;}
        .chat-product-card { background-color: #f0f2f5; border-radius: 12px; padding: 10px; margin-top: 8px; display: flex; align-items: center; gap: 12px; border: 1px solid #e0e0e0; }
        .chat-product-card img { width: 50px; height: 50px; object-fit: cover; border-radius: 8px; flex-shrink: 0; }
        .chat-product-card-info { flex-grow: 1; }
        .chat-product-card-info strong { display: block; font-size: 0.9rem; color: var(--text-dark); margin-bottom: 2px; }
        .chat-product-card-info span { font-size: 0.85rem; color: var(--bg-medium); font-weight: 500; }
        .chat-product-card-actions { display: flex; flex-direction: column; gap: 5px; }
        .chat-product-link, .chat-add-to-cart { display: inline-block; background-color: #E0F2F1; color: var(--bg-medium); padding: 5px 10px; border-radius: 15px; cursor: pointer; font-size: 0.85rem; text-decoration: none; transition: background-color 0.2s; font-weight: 500; text-align: center; width: 100%; }
        .chat-product-link:hover, .chat-add-to-cart:hover { background-color: #B2DFDB; }
        @media (max-width: 480px) {
            .cart-item { grid-template-columns: 60px 1fr auto; }
            .cart-item-details { grid-column: 2; }
            .cart-item-remove { grid-column: 3; }
            .cart-item-quantity { grid-column: 2; grid-row: 2; justify-self: start; }
            .cart-item-total { grid-column: 3; grid-row: 2; }
        }
    </style>
</head>
<body class="{{ 'dark-theme' if settings.color_scheme == 'dark' else '' }}">
    <div class="container">
        <div class="top-bar">
            <a href="{{ url_for('catalog', env_id=env_id) }}" class="logo">
                <img src="{{ chat_avatar_url }}" alt="Logo">
            </a>
            <div class="search-wrapper">
                <i class="fas fa-search"></i>
                <input type="text" id="search-input" placeholder="Искать товары">
            </div>
        </div>

        <div id="catalog-content">
            {% set has_products = False %}
            {% for category_name in ordered_categories %}
                {% if products_by_category[category_name] %}
                    {% set has_products = True %}
                    <div class="category-section" data-category-name="{{ category_name }}">
                        <div class="category-header">
                            <h2>{{ category_name }}</h2>
                            <a class="view-all-arrow" href="#">&gt;</a>
                        </div>
                        <div class="product-carousel">
                            {% for product in products_by_category[category_name] %}
                                <div class="product-card"
                                     data-product-id="{{ product.get('product_id', '') }}"
                                     data-name="{{ product.name|lower }}"
                                     data-description="{{ product.get('description', '')|lower }}"
                                     onclick="openModalById('{{ product.get('product_id', '') }}')">
                                    {% if product.get('is_top', False) %}
                                        <span class="top-product-indicator"><i class="fas fa-star"></i></span>
                                    {% endif %}
                                    <div class="product-image-container">
                                        {% if product.get('photos') and product['photos']|length > 0 %}
                                            <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}"
                                                 alt="{{ product.name }}"
                                                 loading="lazy">
                                        {% else %}
                                            <img src="https://via.placeholder.com/170x170.png?text={{ settings.organization_name }}" alt="No Image" loading="lazy">
                                        {% endif %}
                                    </div>
                                    <div class="product-info-overlay">
                                        <span class="product-price">
                                            {% if settings.business_type == 'wholesale' and product.wholesale_price is not none %}
                                                {{ "%.0f"|format(product.wholesale_price) }} {{ currency_code }}
                                            {% else %}
                                                {{ "%.0f"|format(product.price) }} {{ currency_code }}
                                            {% endif %}
                                        </span>
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                    </div>
                {% endif %}
            {% endfor %}

            {% if not has_products %}
                <p class="no-results-message">Товары пока не добавлены.</p>
            {% endif %}
            <p id="no-results-message" class="no-results-message" style="display: none;">По вашему запросу ничего не найдено.</p>
        </div>
    </div>

    <div id="productModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('productModal')" aria-label="Закрыть">×</span>
            <div id="modalContent">Загрузка...</div>
        </div>
    </div>

    <div id="quantityModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('quantityModal')" aria-label="Закрыть">×</span>
            <h2>Укажите опции и количество</h2>
            <div id="quantityModalOptions"></div>
            <label for="quantityInput">Количество:</label>
            <input type="number" id="quantityInput" class="quantity-input" min="1" value="1" oninput="updatePriceOnQuantityChange()">
            <p id="wholesale-info" style="font-size: 0.9em; color: var(--bg-medium); margin-bottom: 10px;"></p>
            <button class="product-button formulate-order-button" style="width:100%;" onclick="confirmAddToCart()"><i class="fas fa-check"></i> Добавить в корзину</button>
        </div>
    </div>

    <div id="cartModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('cartModal')" aria-label="Закрыть">×</span>
            <h2><i class="fas fa-shopping-cart"></i> Ваша корзина</h2>
            <div id="cartContent"><p style="text-align: center; padding: 20px;">Ваша корзина пуста.</p></div>
            <div class="cart-summary">
                <strong>Итого: <span id="cartTotal">0.00</span> {{ currency_code }}</strong>
            </div>
            <div class="cart-actions">
                <button class="product-button clear-cart" onclick="clearCart()">
                   <i class="fas fa-trash"></i> Очистить корзину
                </button>
                <button class="product-button formulate-order-button" onclick="formulateOrder()">
                   <i class="fas fa-file-alt"></i> Сформировать заказ
                </button>
            </div>
        </div>
    </div>

    <div class="floating-buttons-container">
        {% if chat_is_active %}
        <a href="{{ url_for('chat_page', env_id=env_id) }}" id="chat-open-button" class="floating-button" aria-label="Открыть чат">
           <i class="fas fa-comment-dots"></i>
        </a>
        {% endif %}
        <button id="cart-button" class="floating-button" onclick="openCartModal()" aria-label="Открыть корзину">
           <i class="fas fa-shopping-cart"></i>
           <span id="cart-count">0</span>
        </button>
    </div>

    <div id="notification-placeholder"></div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
    <script>
        const allProducts = {{ products_json|safe }};
        const repoId = '{{ repo_id }}';
        const currencyCode = '{{ currency_code }}';
        const envId = '{{ env_id }}';
        const businessType = '{{ settings.business_type }}';
        let selectedProductId = null;
        let cart = JSON.parse(localStorage.getItem(`mekaCart_${envId}`) || '[]');

        function getProductById(productId) {
            return allProducts.find(p => p.product_id === productId);
        }

        function getProductIndexById(productId) {
            return allProducts.findIndex(p => p.product_id === productId);
        }

        function openModalById(productId) {
            const productIndex = getProductIndexById(productId);
            if (productIndex === -1) {
                alert("Ошибка: товар не найден или отсутствует в наличии.");
                return;
            }
            loadProductDetails(productIndex);
            const modal = document.getElementById('productModal');
            if (modal) {
                modal.style.display = "block";
                document.body.style.overflow = 'hidden';
            }
        }

        function closeModal(modalId) {
            const modal = document.getElementById(modalId);
             if (modal) {
                 modal.style.display = "none";
             }
             const anyModalOpen = document.querySelector('.modal[style*="display: block"]');
             if (!anyModalOpen) {
                document.body.style.overflow = 'auto';
             }
        }

        function loadProductDetails(index) {
            const modalContent = document.getElementById('modalContent');
            if (!modalContent) return;
            modalContent.innerHTML = '<p style="text-align:center; padding: 40px;">Загрузка...</p>';
            fetch(`/${envId}/product/${index}`)
                .then(response => {
                    if (!response.ok) throw new Error(`Ошибка ${response.status}: ${response.statusText}`);
                    return response.text();
                })
                .then(data => {
                    modalContent.innerHTML = data;
                    initializeSwiper();
                    attachOptionListeners();
                })
                .catch(error => {
                    console.error('Ошибка загрузки деталей продукта:', error);
                    modalContent.innerHTML = `<p style="color: var(--danger); text-align:center; padding: 40px;">Не удалось загрузить информацию о товаре. ${error.message}</p>`;
                });
        }
        
        function attachOptionListeners() {
            const product = getProductById(selectedProductId);
            if (!product) return;
            const priceEl = document.getElementById('variantPrice');
            const colorSelect = document.getElementById('colorSelect');
            const sizeSelect = document.getElementById('sizeSelect');

            const updatePrice = () => {
                if (!priceEl || businessType === 'wholesale') return;
                let color = colorSelect ? colorSelect.value : null;
                let size = sizeSelect ? sizeSelect.value : null;
                let key = [color, size].filter(Boolean).join('-');
                
                let currentPrice = product.price;
                if (key && product.variant_prices && product.variant_prices[key]) {
                    currentPrice = product.variant_prices[key];
                }
                priceEl.textContent = `${parseFloat(currentPrice).toFixed(0)} ${currencyCode}`;
            };
            
            if (colorSelect) colorSelect.addEventListener('change', updatePrice);
            if (sizeSelect) sizeSelect.addEventListener('change', updatePrice);
        }

        function initializeSwiper() {
            const swiperContainer = document.querySelector('#productModal .swiper-container');
            if (swiperContainer) {
                new Swiper(swiperContainer, {
                    slidesPerView: 1,
                    spaceBetween: 20,
                    loop: true,
                    grabCursor: true,
                    pagination: { el: '.swiper-pagination', clickable: true },
                    navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
                    zoom: { maxRatio: 3, containerClass: 'swiper-zoom-container' },
                    autoplay: { delay: 5000, disableOnInteraction: true, },
                });
            }
        }
        
        function updatePriceOnQuantityChange() {
            const product = getProductById(selectedProductId);
            const quantity = parseInt(document.getElementById('quantityInput').value || 1);
            const wholesaleInfoEl = document.getElementById('wholesale-info');
            if (!product || !wholesaleInfoEl) return;
            
            wholesaleInfoEl.textContent = '';
            if (businessType === 'wholesale') {
                if (product.wholesale_price && product.min_wholesale_quantity) {
                     wholesaleInfoEl.textContent = `Минимальный заказ: ${product.min_wholesale_quantity} шт.`;
                }
            } else if (businessType === 'combined') {
                if (product.wholesale_price && product.min_wholesale_quantity) {
                    if (quantity >= product.min_wholesale_quantity) {
                        wholesaleInfoEl.textContent = `Активирована оптовая цена: ${product.wholesale_price.toFixed(2)} ${currencyCode}`;
                    } else {
                        const needed = product.min_wholesale_quantity - quantity;
                        wholesaleInfoEl.textContent = `Добавьте еще ${needed} шт. для оптовой цены (${product.wholesale_price.toFixed(2)} ${currencyCode})`;
                    }
                }
            }
        }

        function openQuantityModalById(productId) {
            selectedProductId = productId;
            const product = getProductById(productId);
            if (!product) {
                alert("Ошибка: товар не найден.");
                return;
            }
            const optionsContainer = document.getElementById('quantityModalOptions');
            optionsContainer.innerHTML = '';
            
            if (product.colors && product.colors.length > 0) {
                let colorHtml = '<label for="qColorSelect">Цвет/Вариант:</label><select id="qColorSelect" class="options-select">';
                product.colors.forEach(c => colorHtml += `<option value="${c}">${c}</option>`);
                colorHtml += '</select>';
                optionsContainer.innerHTML += colorHtml;
            }
            if (product.sizes && product.sizes.length > 0) {
                let sizeHtml = '<label for="qSizeSelect">Размер/Объем:</label><select id="qSizeSelect" class="options-select">';
                product.sizes.forEach(s => sizeHtml += `<option value="${s}">${s}</option>`);
                sizeHtml += '</select>';
                optionsContainer.innerHTML += sizeHtml;
            }
            
            let minQty = 1;
            if(businessType === 'wholesale' && product.min_wholesale_quantity) {
                minQty = product.min_wholesale_quantity;
            }
            document.getElementById('quantityInput').value = minQty;
            document.getElementById('quantityInput').min = minQty;
            updatePriceOnQuantityChange();
            const modal = document.getElementById('quantityModal');
             if(modal) {
                modal.style.display = "block";
                document.body.style.overflow = 'hidden';
             }
        }

        function confirmAddToCart() {
            if (selectedProductId === null) return;
            const quantityInput = document.getElementById('quantityInput');
            const quantity = parseInt(quantityInput.value);
            
            const colorSelect = document.getElementById('qColorSelect');
            const sizeSelect = document.getElementById('qSizeSelect');
            
            const color = colorSelect ? colorSelect.value : 'N/A';
            const size = sizeSelect ? sizeSelect.value : 'N/A';
            
            if (isNaN(quantity) || quantity <= 0) {
                alert("Пожалуйста, укажите корректное количество (больше 0).");
                quantityInput.focus();
                return;
            }
            const product = getProductById(selectedProductId);
             if (!product) {
                alert("Ошибка добавления: товар не найден.");
                return;
             }
             
            if (businessType === 'wholesale') {
                if (!product.min_wholesale_quantity || quantity < product.min_wholesale_quantity) {
                    const minQty = product.min_wholesale_quantity || 1;
                    const needed = minQty - quantity;
                    if (needed > 0) {
                        showNotification(`Минимальный заказ ${minQty} шт. Добавьте еще ${needed} шт.`, 5000);
                    } else {
                         showNotification(`Минимальный заказ для этого товара - ${minQty} шт.`, 5000);
                    }
                    return;
                }
            }
            
            let price;
            if (businessType === 'wholesale') {
                price = product.wholesale_price;
            } else {
                price = product.price;
                let variantKey = [color, size].filter(v => v !== 'N/A').join('-');
                if (variantKey && product.variant_prices && product.variant_prices[variantKey]) {
                    price = product.variant_prices[variantKey];
                }
                if (businessType === 'combined' && product.wholesale_price && product.min_wholesale_quantity && quantity >= product.min_wholesale_quantity) {
                     price = product.wholesale_price;
                }
            }

            const cartItemId = `${product.product_id}-${color}-${size}`;
            const existingItemIndex = cart.findIndex(item => item.id === cartItemId);
            if (existingItemIndex > -1) {
                cart[existingItemIndex].quantity += quantity;
                const newQuantity = cart[existingItemIndex].quantity;
                if (businessType === 'combined' && product.wholesale_price && product.min_wholesale_quantity) {
                    cart[existingItemIndex].price = newQuantity >= product.min_wholesale_quantity ? product.wholesale_price : product.price;
                }
            } else {
                cart.push({
                    id: cartItemId,
                    product_id: product.product_id,
                    name: product.name,
                    price: price,
                    photo: product.photos && product.photos.length > 0 ? product.photos[0] : null,
                    quantity: quantity,
                    color: color,
                    size: size
                });
            }
            localStorage.setItem(`mekaCart_${envId}`, JSON.stringify(cart));
            closeModal('quantityModal');
            updateCartButton();
            showNotification(`${product.name} добавлен в корзину!`);
        }

        function updateCartButton() {
             const cartCountElement = document.getElementById('cart-count');
             const cartButton = document.getElementById('cart-button');
             if (!cartCountElement || !cartButton) return;
             let totalItems = 0;
             cart.forEach(item => { totalItems += item.quantity; });
             if (totalItems > 0) {
                 cartCountElement.textContent = totalItems;
                 cartCountElement.style.display = 'flex';
                 cartButton.style.display = 'flex';
             } else {
                 cartCountElement.style.display = 'none';
             }
        }

        function openCartModal() {
            const cartContent = document.getElementById('cartContent');
            const cartTotalElement = document.getElementById('cartTotal');
            if (!cartContent || !cartTotalElement) return;
            let total = 0;
            if (cart.length === 0) {
                cartContent.innerHTML = '<p style="text-align: center; padding: 20px;">Ваша корзина пуста.</p>';
                cartTotalElement.textContent = '0.00';
            } else {
                cartContent.innerHTML = cart.map(item => {
                    const product = getProductById(item.product_id);
                    let isWholesale = false;
                    if (businessType === 'wholesale') {
                        isWholesale = true;
                    } else if (product && product.wholesale_price && product.min_wholesale_quantity && item.quantity >= product.min_wholesale_quantity) {
                        isWholesale = true;
                        item.price = product.wholesale_price;
                    } else if (product) {
                        item.price = product.price;
                    }

                    const itemTotal = item.price * item.quantity;
                    total += itemTotal;
                    const photoUrl = item.photo
                        ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}`
                        : 'https://via.placeholder.com/60x60.png?text=N/A';
                    
                    let variantInfo = [];
                    if (item.color && item.color !== 'N/A') variantInfo.push(`Цвет: ${item.color}`);
                    if (item.size && item.size !== 'N/A') variantInfo.push(`Размер: ${item.size}`);
                    
                    return `
                        <div class="cart-item">
                            <img src="${photoUrl}" alt="${item.name}">
                            <div class="cart-item-details">
                                <strong>${item.name}</strong>
                                <p class="variant-info">${variantInfo.join(', ')}</p>
                                <p class="cart-item-price">${isWholesale ? '<span class="wholesale-label">Опт: </span>' : ''}${item.price.toFixed(2)} ${currencyCode}</p>
                            </div>
                            <div class="cart-item-quantity">
                                <button class="quantity-btn" onclick="decrementCartItem('${item.id}')">-</button>
                                <span>${item.quantity}</span>
                                <button class="quantity-btn" onclick="incrementCartItem('${item.id}')">+</button>
                            </div>
                            <span class="cart-item-total">${itemTotal.toFixed(2)}</span>
                            <button class="cart-item-remove" onclick="removeFromCart('${item.id}')" title="Удалить товар"><i class="fas fa-trash-alt"></i></button>
                        </div>
                    `;
                }).join('');
                cartTotalElement.textContent = total.toFixed(2);
            }
             const modal = document.getElementById('cartModal');
             if (modal) {
                modal.style.display = "block";
                document.body.style.overflow = 'hidden';
             }
        }

        function incrementCartItem(itemId) {
            const itemIndex = cart.findIndex(item => item.id === itemId);
            if (itemIndex > -1) {
                cart[itemIndex].quantity++;
                localStorage.setItem(`mekaCart_${envId}`, JSON.stringify(cart));
                openCartModal();
                updateCartButton();
            }
        }

        function decrementCartItem(itemId) {
            const itemIndex = cart.findIndex(item => item.id === itemId);
            if (itemIndex > -1) {
                const product = getProductById(cart[itemIndex].product_id);
                let minQty = 1;
                if(businessType === 'wholesale' && product && product.min_wholesale_quantity) {
                   minQty = product.min_wholesale_quantity;
                }

                if (cart[itemIndex].quantity - 1 < minQty) {
                    if (confirm("Количество меньше минимального. Удалить товар из корзины?")) {
                         cart.splice(itemIndex, 1);
                    } else {
                        return;
                    }
                } else {
                    cart[itemIndex].quantity--;
                }
                
                if (cart[itemIndex] && cart[itemIndex].quantity <= 0) {
                    cart.splice(itemIndex, 1);
                }
                localStorage.setItem(`mekaCart_${envId}`, JSON.stringify(cart));
                openCartModal();
                updateCartButton();
            }
        }

        function removeFromCart(itemId) {
            cart = cart.filter(item => item.id !== itemId);
            localStorage.setItem(`mekaCart_${envId}`, JSON.stringify(cart));
            openCartModal();
            updateCartButton();
        }

        function clearCart() {
            if (confirm("Вы уверены, что хотите очистить корзину?")) {
                cart = [];
                localStorage.removeItem(`mekaCart_${envId}`);
                openCartModal();
                updateCartButton();
            }
        }

        function formulateOrder() {
            if (cart.length === 0) {
                alert("Корзина пуста! Добавьте товары перед формированием заказа.");
                return;
            }
            const orderData = { cart: cart };
            const formulateButton = document.querySelector('.formulate-order-button');
            if (formulateButton) formulateButton.disabled = true;
            showNotification("Формируем заказ...", 5000);
            fetch(`/${envId}/create_order`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(orderData)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => { throw new Error(err.error || 'Не удалось создать заказ'); });
                }
                return response.json();
            })
            .then(data => {
                if (data.order_id) {
                    localStorage.removeItem(`mekaCart_${envId}`);
                    cart = [];
                    updateCartButton();
                    closeModal('cartModal');
                    window.location.href = `/${envId}/order/${data.order_id}`;
                } else {
                    throw new Error('Не получен ID заказа от сервера.');
                }
            })
            .catch(error => {
                console.error('Ошибка при формировании заказа:', error);
                alert(`Ошибка: ${error.message}`);
                 if (formulateButton) formulateButton.disabled = false;
            });
        }

        function filterProducts() {
            const searchTerm = document.getElementById('search-input').value.toLowerCase().trim();
            const allCategorySections = document.querySelectorAll('.category-section');
            const noResultsEl = document.getElementById('no-results-message');
            let totalResults = 0;

            allCategorySections.forEach(section => {
                const productCards = section.querySelectorAll('.product-card');
                let categoryHasVisibleProducts = false;
                productCards.forEach(card => {
                    const name = card.dataset.name || '';
                    const description = card.dataset.description || '';
                    if (searchTerm === '' || name.includes(searchTerm) || description.includes(searchTerm)) {
                        card.style.display = 'inline-block';
                        categoryHasVisibleProducts = true;
                    } else {
                        card.style.display = 'none';
                    }
                });
                if (categoryHasVisibleProducts) {
                    section.style.display = 'block';
                    totalResults++;
                } else {
                    section.style.display = 'none';
                }
            });

            if (totalResults === 0 && searchTerm !== '') {
                if (noResultsEl) noResultsEl.style.display = 'block';
            } else {
                if (noResultsEl) noResultsEl.style.display = 'none';
            }
        }

        function showNotification(message, duration = 3000) {
            const placeholder = document.getElementById('notification-placeholder');
            if (!placeholder) return;
            const notification = document.createElement('div');
            notification.className = 'notification';
            notification.textContent = message;
            placeholder.appendChild(notification);
            void notification.offsetWidth;
            notification.classList.add('show');
            setTimeout(() => {
                notification.classList.remove('show');
                notification.addEventListener('transitionend', () => notification.remove());
            }, duration);
        }

        document.addEventListener('DOMContentLoaded', () => {
            updateCartButton();
            document.getElementById('search-input').addEventListener('input', filterProducts);
            window.addEventListener('click', function(event) {
                if (event.target.classList.contains('modal')) { closeModal(event.target.id); }
            });
            window.addEventListener('keydown', function(event) {
                if (event.key === 'Escape') {
                     document.querySelectorAll('.modal[style*="display: block"]').forEach(modal => {
                         closeModal(modal.id);
                     });
                }
            });
        });
    </script>
</body>
</html>
'''

CHAT_TEMPLATE = '''
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>{{ settings.organization_name }} - Чат с {{ settings.chat_name }}</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css">
    <style>
        {% if settings.color_scheme == 'forest' %}
        :root { --bg-dark: #2F4F4F; --bg-medium: #556B2F; --accent: #8FBC8F; --accent-hover: #98FB98; --text-light: #F5F5DC; --text-dark: #FFFFFF; --danger: #CD5C5C; --danger-hover: #F08080; --chat-bg: #F5F5DC; }
        {% elif settings.color_scheme == 'ocean' %}
        :root { --bg-dark: #000080; --bg-medium: #1E90FF; --accent: #87CEEB; --accent-hover: #ADD8E6; --text-light: #F0F8FF; --text-dark: #000000; --danger: #FF6347; --danger-hover: #FF4500; --chat-bg: #F0F8FF; }
        {% elif settings.color_scheme == 'sunset' %}
        :root { --bg-dark: #8B4513; --bg-medium: #D2691E; --accent: #FFA500; --accent-hover: #FFB733; --text-light: #FFF8DC; --text-dark: #000000; --danger: #DC143C; --danger-hover: #FF0000; --chat-bg: #FFF8DC; }
        {% elif settings.color_scheme == 'lavender' %}
        :root { --bg-dark: #483D8B; --bg-medium: #8A2BE2; --accent: #D8BFD8; --accent-hover: #E6E6FA; --text-light: #F0F8FF; --text-dark: #000000; --danger: #DB7093; --danger-hover: #FFC0CB; --chat-bg: #F8F8FF; }
        {% elif settings.color_scheme == 'vintage' %}
        :root { --bg-dark: #5D4037; --bg-medium: #8D6E63; --accent: #D7CCC8; --accent-hover: #EFEBE9; --text-light: #F5F5F5; --text-dark: #3E2723; --danger: #BF360C; --danger-hover: #F4511E; --chat-bg: #EFEBE9; }
        {% elif settings.color_scheme == 'dark' %}
        :root { --bg-dark: #1F1F1F; --bg-medium: #333333; --accent: #BB86FC; --accent-hover: #A764FC; --text-light: #E1E1E1; --text-dark: #FFFFFF; --danger: #CF6679; --danger-hover: #D98899; --chat-bg: #121212; }
        {% elif settings.color_scheme == 'cosmic' %}
        :root { --bg-dark: #1A237E; --bg-medium: #303F9F; --accent: #536DFE; --accent-hover: #7986CB; --text-light: #FFFFFF; --text-dark: #FFFFFF; --danger: #F50057; --danger-hover: #FF4081; --chat-bg: #E8EAF6; }
        {% elif settings.color_scheme == 'minty' %}
        :root { --bg-dark: #004D40; --bg-medium: #00796B; --accent: #4DB6AC; --accent-hover: #80CBC4; --text-light: #E0F2F1; --text-dark: #FFFFFF; --danger: #ef5350; --danger-hover: #e57373; --chat-bg: #f1f8e9; }
        {% elif settings.color_scheme == 'mocha' %}
        :root { --bg-dark: #3e2723; --bg-medium: #5d4037; --accent: #a1887f; --accent-hover: #bcaaa4; --text-light: #efebe9; --text-dark: #3e2723; --danger: #d32f2f; --danger-hover: #e57373; --chat-bg: #d7ccc8; }
        {% elif settings.color_scheme == 'crimson' %}
        :root { --bg-dark: #6A1B9A; --bg-medium: #9C27B0; --accent: #CE93D8; --accent-hover: #E1BEE7; --text-light: #FFFFFF; --text-dark: #FFFFFF; --danger: #E91E63; --danger-hover: #F06292; --chat-bg: #F3E5F5; }
        {% elif settings.color_scheme == 'solar' %}
        :root { --bg-dark: #E65100; --bg-medium: #FB8C00; --accent: #FFCA28; --accent-hover: #FFD54F; --text-light: #212121; --text-dark: #212121; --danger: #d32f2f; --danger-hover: #e57373; --chat-bg: #fff8e1; }
        {% elif settings.color_scheme == 'cyberpunk' %}
        :root { --bg-dark: #000000; --bg-medium: #0d0221; --accent: #00f0ff; --accent-hover: #81f5ff; --text-light: #ffffff; --text-dark: #000000; --danger: #f50057; --danger-hover: #ff4081; --chat-bg: #0a0116; }
        {% else %}
        :root { --bg-dark: #003C43; --bg-medium: #135D66; --accent: #48D1CC; --accent-hover: #77E4D8; --text-light: #E3FEF7; --text-dark: #003C43; --danger: #E57373; --danger-hover: #EF5350; --chat-bg: #f0f2f5; }
        {% endif %}

        * { margin: 0; padding: 0; box-sizing: border-box; }
        html { -webkit-tap-highlight-color: transparent; height: 100%; }
        body {
            font-family: 'Montserrat', sans-serif;
            background-color: var(--chat-bg);
            color: var(--text-dark);
            display: flex;
            flex-direction: column;
            height: 100%;
            overflow: hidden;
        }
        .chat-container {
            display: flex;
            flex-direction: column;
            height: 100%;
            width: 100%;
            max-width: 800px;
            margin: 0 auto;
            background: #fff;
            box-shadow: 0 0 20px rgba(0,0,0,0.05);
        }
        body.dark-theme .chat-container { background: var(--chat-bg); color: var(--text-light); }
        .chat-header {
            display: flex;
            align-items: center;
            padding: 10px 15px;
            background: var(--bg-dark);
            color: var(--text-light);
            flex-shrink: 0;
        }
        .chat-header a { color: var(--text-light); font-size: 1.2rem; text-decoration: none; }
        .chat-header .logo { width: 40px; height: 40px; border-radius: 50%; margin: 0 15px; border: 2px solid var(--accent); }
        .chat-header h1 { font-size: 1.2rem; font-weight: 600; }
        #chat-messages {
            flex-grow: 1;
            overflow-y: auto;
            padding: 20px 15px;
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        .chat-message {
            display: flex;
            flex-direction: column;
            max-width: 85%;
            animation: message-appear 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards;
        }
        @keyframes message-appear {
            from { opacity: 0; transform: translateY(15px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .message-bubble {
            padding: 10px 15px;
            border-radius: 18px;
            line-height: 1.5;
            word-wrap: break-word;
        }
        .chat-message.user { align-self: flex-end; }
        .chat-message.user .message-bubble {
            background-color: var(--bg-medium);
            color: var(--text-light);
            border-bottom-right-radius: 4px;
        }
        .chat-message.ai { align-self: flex-start; }
        .chat-message.ai .message-bubble {
            background-color: #e6e6e6;
            color: #333;
            border-bottom-left-radius: 4px;
        }
        body.dark-theme .chat-message.ai .message-bubble { background-color: #333; color: var(--text-light); }
        .chat-input-container {
            padding: 15px;
            background: #fff;
            border-top: 1px solid #ddd;
            display: flex;
            gap: 10px;
            align-items: center;
            flex-shrink: 0;
        }
        body.dark-theme .chat-input-container { background: var(--bg-dark); border-top: 1px solid #444;}
        #chat-input {
            flex-grow: 1;
            padding: 12px 18px;
            border: 1px solid #e0e0e0;
            border-radius: 24px;
            font-size: 1rem;
            outline: none;
            transition: border-color 0.3s, box-shadow 0.3s;
        }
        body.dark-theme #chat-input { background-color: #333; color: var(--text-light); border-color: #555; }
        #chat-input:focus {
            border-color: var(--bg-medium);
            box-shadow: 0 0 0 3px rgba(19, 93, 102, 0.15);
        }
        #chat-send-button {
            background-color: var(--bg-medium);
            color: var(--text-light);
            border: none;
            border-radius: 50%;
            width: 48px;
            height: 48px;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.2s;
            flex-shrink: 0;
            font-size: 1.2rem;
        }
        #chat-send-button:hover { background-color: var(--bg-dark); }
        #chat-send-button:active { transform: scale(0.9); }
        #chat-send-button:disabled { background-color: #cccccc; cursor: not-allowed; }
        .floating-buttons-container { position: fixed; bottom: 25px; right: 25px; z-index: 1000; }
        .floating-button { background-color: var(--accent); color: var(--text-dark); border: none; border-radius: 50%; width: 55px; height: 55px; font-size: 1.5rem; cursor: pointer; display: none; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(72, 209, 204, 0.4); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
        .floating-button:hover { background-color: var(--accent-hover); transform: translateY(-3px); }
        #cart-button { position: relative; }
        #cart-count { position: absolute; top: -2px; right: -2px; background-color: var(--danger); color: white; border-radius: 50%; padding: 2px 6px; font-size: 0.7rem; font-weight: bold; border: 2px solid var(--accent); }
        .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); backdrop-filter: blur(5px); overflow-y: auto; }
        .modal-content { background: #ffffff; color: var(--text-dark); margin: 5% auto; padding: 25px; border-radius: 15px; width: 90%; max-width: 700px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); animation: slideIn 0.3s ease-out; position: relative; }
        body.dark-theme .modal-content { background-color: #2a2a2a; color: var(--text-light); }
        @keyframes slideIn { from { transform: translateY(-30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
        .close { position: absolute; top: 15px; right: 15px; font-size: 1.8rem; color: #aaa; cursor: pointer; transition: color 0.3s; line-height: 1; }
        .close:hover { color: #666; }
        .modal-content h2 { margin-top: 0; margin-bottom: 20px; color: var(--bg-medium); display: flex; align-items: center; gap: 10px;}
        .cart-item { display: grid; grid-template-columns: 60px 1fr auto auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #e0e0e0; }
        body.dark-theme .cart-item { border-bottom-color: #444; }
        .cart-item:last-child { border-bottom: none; }
        .cart-item img { width: 60px; height: 60px; object-fit: cover; border-radius: 8px; }
        .cart-item-details strong { display: block; margin-bottom: 5px; font-size: 1rem; color: var(--text-dark);}
        body.dark-theme .cart-item-details strong { color: var(--text-light); }
        .cart-item-quantity { display: flex; align-items: center; gap: 8px; }
        .quantity-btn { background-color: #eee; border: 1px solid #ddd; border-radius: 50%; width: 28px; height: 28px; cursor: pointer; }
        body.dark-theme .quantity-btn { background-color: #444; border-color: #555; color: #fff; }
        .cart-item-total { font-weight: bold; text-align: right; font-size: 1rem; color: var(--bg-medium);}
        .cart-item-remove { background:none; border:none; color: var(--danger); cursor:pointer; font-size: 1.3em; }
        .quantity-input, .options-select { width: 100%; max-width: 180px; padding: 10px; border: 1px solid #e0e0e0; border-radius: 8px; font-size: 1rem; margin: 10px 0; }
        body.dark-theme .quantity-input, body.dark-theme .options-select { background-color: #333; color: #fff; border-color: #555; }
        .cart-summary { margin-top: 20px; text-align: right; border-top: 1px solid #e0e0e0; padding-top: 15px; }
        body.dark-theme .cart-summary { border-top-color: #444; }
        .cart-actions { margin-top: 25px; display: flex; justify-content: space-between; }
        .product-button { display: block; width: auto; flex-grow: 1; padding: 10px; border: none; border-radius: 8px; cursor: pointer; text-align: center; text-decoration: none; }
        .clear-cart { background-color: #6c757d; color: white;}
        .formulate-order-button { background-color: var(--accent); color: var(--text-dark); }
        .notification { position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%); background-color: var(--accent); color: var(--text-dark); padding: 10px 20px; border-radius: 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.2); z-index: 1002; opacity: 0; transition: opacity 0.5s ease; font-size: 0.9rem;}
        .notification.show { opacity: 1;}
        .chat-product-card { background-color: #f0f2f5; border-radius: 12px; padding: 10px; margin-top: 8px; display: flex; align-items: center; gap: 12px; border: 1px solid #e0e0e0; }
        body.dark-theme .chat-product-card { background-color: #333; border-color: #555; }
        .chat-product-card img { width: 50px; height: 50px; object-fit: cover; border-radius: 8px; flex-shrink: 0; }
        .chat-product-card-info { flex-grow: 1; }
        .chat-product-card-info strong { display: block; font-size: 0.9rem; margin-bottom: 2px; }
        body.dark-theme .chat-product-card-info strong { color: var(--text-light); }
        .chat-product-card-info span { font-size: 0.85rem; color: var(--bg-medium); font-weight: 500; }
        .chat-product-card-actions { display: flex; flex-direction: column; gap: 5px; }
        .chat-product-link, .chat-add-to-cart { display: inline-block; background-color: #E0F2F1; color: var(--bg-medium); padding: 5px 10px; border-radius: 15px; cursor: pointer; font-size: 0.85rem; text-decoration: none; transition: background-color 0.2s; font-weight: 500; text-align: center; width: 100%; }
        .chat-product-link:hover, .chat-add-to-cart:hover { background-color: #B2DFDB; }
        body.dark-theme .chat-product-link, body.dark-theme .chat-add-to-cart { background-color: #444; color: var(--accent); }
    </style>
</head>
<body class="{{ 'dark-theme' if settings.color_scheme == 'dark' else '' }}">
    <div class="chat-container">
        <div class="chat-header">
            <a href="{{ url_for('catalog', env_id=env_id) }}"><i class="fas fa-arrow-left"></i></a>
            <img src="{{ chat_avatar_url }}" alt="Logo" class="logo">
            <h1>Чат с {{ settings.chat_name }}</h1>
        </div>
        <div id="chat-messages"></div>
        <div class="chat-input-container">
            <input type="text" id="chat-input" placeholder="Напишите сообщение..." autocomplete="off">
            <button id="chat-send-button"><i class="fas fa-paper-plane"></i></button>
        </div>
    </div>
    
    <div class="floating-buttons-container">
        <button id="cart-button" class="floating-button" onclick="openCartModal()" aria-label="Открыть корзину">
           <i class="fas fa-shopping-cart"></i>
           <span id="cart-count">0</span>
        </button>
    </div>

    <div id="productModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('productModal')">×</span>
            <div id="modalContent"></div>
        </div>
    </div>
    <div id="quantityModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('quantityModal')">×</span>
            <h2>Укажите опции и количество</h2>
            <div id="quantityModalOptions"></div>
            <label for="quantityInput">Количество:</label>
            <input type="number" id="quantityInput" class="quantity-input" min="1" value="1">
            <button class="product-button formulate-order-button" onclick="confirmAddToCart()">Добавить в корзину</button>
        </div>
    </div>
    <div id="cartModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('cartModal')">×</span>
            <h2><i class="fas fa-shopping-cart"></i> Ваша корзина</h2>
            <div id="cartContent"></div>
            <div class="cart-summary">
                <strong>Итого: <span id="cartTotal">0.00</span> {{ currency_code }}</strong>
            </div>
            <div class="cart-actions">
                <button class="product-button clear-cart" onclick="clearCart()">Очистить</button>
                <button class="product-button formulate-order-button" onclick="formulateOrder()">Сформировать</button>
            </div>
        </div>
    </div>
    <div id="notification-placeholder"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script>
    <script>
        const allProducts = {{ products_json|safe }};
        const repoId = '{{ repo_id }}';
        const currencyCode = '{{ currency_code }}';
        const envId = '{{ env_id }}';
        const businessType = '{{ settings.business_type }}';
        let selectedProductId = null;
        let cart = JSON.parse(localStorage.getItem(`mekaCart_${envId}`) || '[]');
        let chatHistory = [];
        let chatId = sessionStorage.getItem(`gippoChatId_${envId}`);
        if (!chatId) {
            chatId = 'chat_' + new Date().getTime() + '_' + Math.random().toString(36).substr(2, 9);
            sessionStorage.setItem(`gippoChatId_${envId}`, chatId);
        }

        const chatMessagesDiv = document.getElementById('chat-messages');
        const chatInput = document.getElementById('chat-input');
        const chatSendButton = document.getElementById('chat-send-button');

        function getProductById(productId) { return allProducts.find(p => p.product_id === productId); }
        function getProductIndexById(productId) { return allProducts.findIndex(p => p.product_id === productId); }
        function openModalById(productId) {
            const productIndex = getProductIndexById(productId);
            if (productIndex === -1) return;
            loadProductDetails(productIndex);
            document.getElementById('productModal').style.display = "block";
            document.body.style.overflow = 'hidden';
        }
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = "none";
            if (!document.querySelector('.modal[style*="display: block"]')) {
                document.body.style.overflow = 'auto';
            }
        }
        function loadProductDetails(index) {
            const modalContent = document.getElementById('modalContent');
            modalContent.innerHTML = '<p>Загрузка...</p>';
            fetch(`/${envId}/product/${index}`)
                .then(response => response.text())
                .then(data => {
                    modalContent.innerHTML = data;
                    initializeSwiper();
                }).catch(error => modalContent.innerHTML = `<p>Не удалось загрузить информацию о товаре.</p>`);
        }
        function initializeSwiper() {
            if (document.querySelector('#productModal .swiper-container')) {
                new Swiper('#productModal .swiper-container', { loop: true, pagination: { el: '.swiper-pagination' }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' } });
            }
        }
        function openQuantityModalById(productId) {
            selectedProductId = productId;
            const product = getProductById(productId);
            if (!product) return;
            const optionsContainer = document.getElementById('quantityModalOptions');
            optionsContainer.innerHTML = '';
            
            if (product.colors && product.colors.length > 0) {
                let colorHtml = '<label for="qColorSelect">Цвет/Вариант:</label><select id="qColorSelect" class="options-select">';
                product.colors.forEach(c => colorHtml += `<option value="${c}">${c}</option>`);
                colorHtml += '</select>';
                optionsContainer.innerHTML += colorHtml;
            }
            if (product.sizes && product.sizes.length > 0) {
                let sizeHtml = '<label for="qSizeSelect">Размер/Объем:</label><select id="qSizeSelect" class="options-select">';
                product.sizes.forEach(s => sizeHtml += `<option value="${s}">${s}</option>`);
                sizeHtml += '</select>';
                optionsContainer.innerHTML += sizeHtml;
            }
            document.getElementById('quantityInput').value = 1;
            document.getElementById('quantityModal').style.display = "block";
        }
        function confirmAddToCart() {
            const quantity = parseInt(document.getElementById('quantityInput').value);
            const colorSelect = document.getElementById('qColorSelect');
            const sizeSelect = document.getElementById('qSizeSelect');
            
            const color = colorSelect ? colorSelect.value : 'N/A';
            const size = sizeSelect ? sizeSelect.value : 'N/A';

            if (isNaN(quantity) || quantity <= 0) {
                alert("Укажите корректное количество.");
                return;
            }
            const product = getProductById(selectedProductId);
            
            if (businessType === 'wholesale') {
                if (!product.min_wholesale_quantity || quantity < product.min_wholesale_quantity) {
                    const minQty = product.min_wholesale_quantity || 1;
                    const needed = minQty - quantity;
                    if (needed > 0) {
                        showNotification(`Минимальный заказ ${minQty} шт. Добавьте еще ${needed} шт.`, 5000);
                    } else {
                         showNotification(`Минимальный заказ для этого товара - ${minQty} шт.`, 5000);
                    }
                    return;
                }
            }
            
            let price;
            if (businessType === 'wholesale') {
                price = product.wholesale_price;
            } else {
                price = product.price;
                let variantKey = [color, size].filter(v => v !== 'N/A').join('-');
                if (variantKey && product.variant_prices && product.variant_prices[variantKey]) {
                    price = product.variant_prices[variantKey];
                }
                if (businessType === 'combined' && product.wholesale_price && product.min_wholesale_quantity && quantity >= product.min_wholesale_quantity) {
                     price = product.wholesale_price;
                }
            }


            const cartItemId = `${product.product_id}-${color}-${size}`;
            const existingItem = cart.find(item => item.id === cartItemId);
            if (existingItem) {
                existingItem.quantity += quantity;
            } else {
                cart.push({ id: cartItemId, product_id: product.product_id, name: product.name, price: price, photo: product.photos ? product.photos[0] : null, quantity, color, size });
            }
            localStorage.setItem(`mekaCart_${envId}`, JSON.stringify(cart));
            closeModal('quantityModal');
            updateCartButton();
            showNotification(`${product.name} добавлен в корзину!`);
        }
        function updateCartButton() {
            const cartCountEl = document.getElementById('cart-count');
            const cartButton = document.getElementById('cart-button');
            const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
            if (totalItems > 0) {
                cartCountEl.textContent = totalItems;
                cartCountEl.style.display = 'flex';
                cartButton.style.display = 'flex';
            } else {
                cartCountEl.style.display = 'none';
                cartButton.style.display = 'none';
            }
        }
        function openCartModal() {
            const cartContent = document.getElementById('cartContent');
            const cartTotalEl = document.getElementById('cartTotal');
            let total = 0;
            if (cart.length === 0) {
                cartContent.innerHTML = '<p>Ваша корзина пуста.</p>';
                cartTotalEl.textContent = '0.00';
            } else {
                cartContent.innerHTML = cart.map(item => {
                    const itemTotal = item.price * item.quantity;
                    total += itemTotal;
                    let variantInfo = [];
                    if (item.color && item.color !== 'N/A') variantInfo.push(`Цвет: ${item.color}`);
                    if (item.size && item.size !== 'N/A') variantInfo.push(`Размер: ${item.size}`);
                    return `<div class="cart-item">
                                <img src="${item.photo ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${item.photo}` : ''}" alt="${item.name}">
                                <div><strong>${item.name}</strong><p>${variantInfo.join(', ')}</p><p>${item.price.toFixed(2)} ${currencyCode}</p></div>
                                <div class="cart-item-quantity"><button class="quantity-btn" onclick="decrementCartItem('${item.id}')">-</button><span>${item.quantity}</span><button class="quantity-btn" onclick="incrementCartItem('${item.id}')">+</button></div>
                                <span class="cart-item-total">${itemTotal.toFixed(2)}</span>
                                <button class="cart-item-remove" onclick="removeFromCart('${item.id}')"><i class="fas fa-trash-alt"></i></button>
                            </div>`;
                }).join('');
                cartTotalEl.textContent = total.toFixed(2);
            }
            document.getElementById('cartModal').style.display = 'block';
        }
        function incrementCartItem(itemId) {
            const item = cart.find(i => i.id === itemId);
            if (item) item.quantity++;
            localStorage.setItem(`mekaCart_${envId}`, JSON.stringify(cart));
            openCartModal();
            updateCartButton();
        }
        function decrementCartItem(itemId) {
            const itemIndex = cart.findIndex(i => i.id === itemId);
            if (itemIndex > -1) {
                cart[itemIndex].quantity--;
                if (cart[itemIndex].quantity <= 0) cart.splice(itemIndex, 1);
                localStorage.setItem(`mekaCart_${envId}`, JSON.stringify(cart));
                openCartModal();
                updateCartButton();
            }
        }
        function removeFromCart(itemId) {
            cart = cart.filter(item => item.id !== itemId);
            localStorage.setItem(`mekaCart_${envId}`, JSON.stringify(cart));
            openCartModal();
            updateCartButton();
        }
        function clearCart() {
            if (confirm("Очистить корзину?")) {
                cart = [];
                localStorage.removeItem(`mekaCart_${envId}`);
                openCartModal();
                updateCartButton();
            }
        }
        function formulateOrder() {
            if (cart.length === 0) return;
            fetch(`/${envId}/create_order`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cart }) })
                .then(res => res.json())
                .then(data => {
                    if (data.order_id) {
                        localStorage.removeItem(`mekaCart_${envId}`);
                        cart = [];
                        updateCartButton();
                        closeModal('cartModal');
                        window.location.href = `/${envId}/order/${data.order_id}`;
                    }
                });
        }
        function showNotification(message, duration = 3000) {
            const el = document.createElement('div');
            el.className = 'notification';
            el.textContent = message;
            document.getElementById('notification-placeholder').appendChild(el);
            setTimeout(() => {
                el.classList.add('show');
                setTimeout(() => {
                    el.classList.remove('show');
                    el.addEventListener('transitionend', () => el.remove());
                }, duration);
            }, 10);
        }
        
        function addMessageToChatUI(text, role) {
            const messageElement = document.createElement('div');
            messageElement.className = `chat-message ${role}`;
            
            const productRegex = /\[ID_ТОВАРА:\\s*([a-fA-F0-9]+)\\s*Название:\\s*([^\]]+)\]/g;
            let lastIndex = 0;
            const contentFragment = document.createDocumentFragment();
            let match;

            const sanitizedText = text.replace(/</g, "&lt;").replace(/>/g, "&gt;");

            while ((match = productRegex.exec(sanitizedText)) !== null) {
                if (match.index > lastIndex) {
                    const textNode = document.createElement('div');
                    textNode.className = 'message-bubble';
                    textNode.innerHTML = sanitizedText.substring(lastIndex, match.index).replace(/\\n/g, '<br>');
                    messageElement.appendChild(textNode);
                }
                const productId = match[1];
                const product = getProductById(productId);
                if (product) {
                    const photoUrl = product.photos && product.photos.length > 0 ? `https://huggingface.co/datasets/${repoId}/resolve/main/photos/${product.photos[0]}` : '';
                    const card = document.createElement('div');
                    card.className = 'chat-product-card';
                    card.innerHTML = `<img src="${photoUrl}" alt="${product.name}">
                        <div class="chat-product-card-info">
                            <strong>${product.name}</strong>
                            <span>${product.price.toFixed(0)} ${currencyCode}</span>
                        </div>
                        <div class="chat-product-card-actions">
                            <a href="#" class="chat-product-link" data-id="${productId}">Обзор</a>
                            <a href="#" class="chat-add-to-cart" data-id="${productId}"><i class="fas fa-cart-plus"></i></a>
                        </div>`;
                    messageElement.appendChild(card);
                }
                lastIndex = match.index + match[0].length;
            }

            if (lastIndex < sanitizedText.length) {
                const textNode = document.createElement('div');
                textNode.className = 'message-bubble';
                textNode.innerHTML = sanitizedText.substring(lastIndex).replace(/\\n/g, '<br>');
                messageElement.appendChild(textNode);
            }
            
            chatMessagesDiv.appendChild(messageElement);
            chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
        }

        async function sendMessage() {
            const message = chatInput.value.trim();
            if (!message) return;
            addMessageToChatUI(message, 'user');
            chatHistory.push({ role: 'user', text: message });
            chatInput.value = '';
            chatSendButton.disabled = true;

            try {
                const response = await fetch(`/${envId}/chat_with_ai`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message: message, history: chatHistory.slice(0, -1), chat_id: chatId })
                });
                const result = await response.json();
                if (!response.ok) throw new Error(result.error);
                addMessageToChatUI(result.text, 'ai');
                chatHistory.push({ role: 'ai', text: result.text });
            } catch (error) {
                addMessageToChatUI(`Ошибка: ${error.message}`, 'ai');
            } finally {
                chatSendButton.disabled = false;
                chatInput.focus();
            }
        }
        
        chatSendButton.addEventListener('click', sendMessage);
        chatInput.addEventListener('keypress', e => { if (e.key === 'Enter') sendMessage(); });
        
        chatMessagesDiv.addEventListener('click', e => {
            if(e.target.closest('.chat-product-link')) {
                e.preventDefault();
                openModalById(e.target.closest('.chat-product-link').dataset.id);
            }
            if(e.target.closest('.chat-add-to-cart')) {
                e.preventDefault();
                openQuantityModalById(e.target.closest('.chat-add-to-cart').dataset.id);
            }
        });
        
        document.addEventListener('DOMContentLoaded', () => {
            updateCartButton();
            window.addEventListener('click', e => { if (e.target.classList.contains('modal')) closeModal(e.target.id); });
            window.addEventListener('keydown', e => { if (e.key === 'Escape') document.querySelectorAll('.modal').forEach(m => closeModal(m.id)); });
            
            addMessageToChatUI('👋 Здравствуйте! Я ваш виртуальный помощник {{ settings.chat_name }}. Чем могу помочь?', 'ai');
            chatHistory.push({ role: 'ai', text: 'Здравствуйте! Я ваш виртуальный помощник {{ settings.chat_name }}. Чем могу помочь?' });
        });
    </script>
</body>
</html>
'''

PRODUCT_DETAIL_TEMPLATE = '''
    <div style="padding: 10px;" data-product-id="{{ product.get('product_id') }}">
        <h2 style="font-size: 1.6rem; font-weight: 600; margin-bottom: 15px; text-align: center; color: #135D66;">{{ product['name'] }}</h2>
        <div class="swiper-container" style="max-width: 450px; margin: 0 auto 20px; border-radius: 10px; overflow: hidden; background-color: #fff; border: 1px solid #e0e0e0;">
            <div class="swiper-wrapper">
                {% if product.get('photos') and product['photos']|length > 0 %}
                    {% for photo in product['photos'] %}
                    <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center; padding: 10px;">
                         <div class="swiper-zoom-container">
                             <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}"
                                  alt="{{ product['name'] }} - фото {{ loop.index }}"
                                  style="max-width: 100%; max-height: 400px; object-fit: contain; display: block; margin: auto; cursor: grab;">
                         </div>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="swiper-slide" style="display: flex; justify-content: center; align-items: center;">
                         <img src="https://via.placeholder.com/400x400.png?text=No+Image" alt="Изображение отсутствует" style="max-width: 100%; max-height: 400px; object-fit: contain;">
                    </div>
                {% endif %}
            </div>
            {% if product.get('photos') and product['photos']|length > 1 %}
            <div class="swiper-pagination" style="position: relative; bottom: 5px;"></div>
            <div class="swiper-button-next" style="color: #135D66;"></div>
            <div class="swiper-button-prev" style="color: #135D66;"></div>
            {% endif %}
        </div>
        
        <div style="margin-top: 20px; padding: 0 10px;">
            {% if product.get('colors') and product.colors|select('ne', '')|list|length > 0 %}
                <div style="margin-bottom: 15px;">
                    <label for="colorSelect" style="display: block; margin-bottom: 5px; font-weight: 500;">Цвет/Вариант:</label>
                    <select id="colorSelect" class="options-select">
                        {% for color in product.colors|select('ne', '')|list %}
                        <option value="{{ color }}">{{ color }}</option>
                        {% endfor %}
                    </select>
                </div>
            {% endif %}
            {% if product.get('sizes') and product.sizes|select('ne', '')|list|length > 0 %}
                <div style="margin-bottom: 15px;">
                    <label for="sizeSelect" style="display: block; margin-bottom: 5px; font-weight: 500;">Размер/Объем:</label>
                    <select id="sizeSelect" class="options-select">
                        {% for size in product.sizes|select('ne', '')|list %}
                        <option value="{{ size }}">{{ size }}</option>
                        {% endfor %}
                    </select>
                </div>
            {% endif %}
        </div>

        <div style="text-align:center; margin-top:20px; padding: 0 10px;">
            {% if settings.business_type == 'wholesale' %}
                <p style="font-size: 1.5rem; font-weight: bold; color: #135D66; margin-bottom: 5px;">
                    <strong>Цена:</strong> <span id="variantPrice">{{ "%.0f"|format(product.wholesale_price) }} {{ currency_code }}</span>
                </p>
                <p style="font-size: 1rem; color: #555; margin-top: 0; margin-bottom: 15px;">
                    Минимальный заказ: {{ product.min_wholesale_quantity }} шт.
                </p>
            {% else %}
                 <p style="font-size: 1.5rem; font-weight: bold; color: #135D66; margin-bottom: 15px;">
                    <strong>Цена:</strong> <span id="variantPrice">{{ "%.0f"|format(product.price) }} {{ currency_code }}</span>
                 </p>
                 {% if product.wholesale_price and product.min_wholesale_quantity and settings.business_type == 'combined' %}
                    <p style="font-size: 1rem; color: #555; margin-top: -10px; margin-bottom: 15px;">
                        Опт: {{ "%.0f"|format(product.wholesale_price) }} {{ currency_code }} от {{ product.min_wholesale_quantity }} шт.
                    </p>
                 {% endif %}
            {% endif %}

            <button class="product-button formulate-order-button" style="padding: 12px 30px; width: 100%; max-width: 300px;" onclick="closeModal('productModal'); openQuantityModalById('{{ product.get('product_id', '') }}')">
                <i class="fas fa-cart-plus"></i> В корзину
            </button>
        </div>

        <div style="margin-top: 20px; font-size: 1rem; line-height: 1.7; color: #333; padding: 0 10px;">
            <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
            <p><strong>Описание:</strong><br> {{ product.get('description', 'Описание отсутствует.')|replace('\\n', '<br>')|safe }}</p>
        </div>
    </div>
    <script>
        selectedProductId = '{{ product.get("product_id") }}';
        attachOptionListeners();
    </script>
'''

ORDER_TEMPLATE = '''
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Заказ №{{ order.id }} - {{ settings.organization_name }}</title>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        :root {
            --bg-light: #f4f6f9;
            --bg-medium: #135D66;
            --accent: #48D1CC;
            --text-dark: #333;
            --text-light: #E3FEF7;
        }
        body { font-family: 'Montserrat', sans-serif; background: var(--bg-light); color: var(--text-dark); line-height: 1.6; padding: 20px; }
        .container { max-width: 800px; margin: 20px auto; padding: 30px; background: #fff; border-radius: 15px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); border: 1px solid #e0e0e0; }
        h1 { text-align: center; color: var(--bg-medium); margin-bottom: 25px; font-size: 1.8rem; font-weight: 600; }
        h2 { color: var(--bg-medium); margin-top: 30px; margin-bottom: 15px; font-size: 1.4rem; border-bottom: 1px solid #e0e0e0; padding-bottom: 8px;}
        .order-meta { font-size: 0.9rem; color: #999; margin-bottom: 20px; text-align: center; }
        .order-item { display: grid; grid-template-columns: 60px 1fr auto; gap: 15px; align-items: center; padding: 15px 0; border-bottom: 1px solid #f0f0f0; }
        .order-item:last-child { border-bottom: none; }
        .order-item img { width: 60px; height: 60px; object-fit: cover; border-radius: 8px; }
        .item-details { grid-column: 2; }
        .item-details strong { display: block; margin-bottom: 5px; font-size: 1.05rem; color: var(--text-dark);}
        .item-details span { font-size: 0.9rem; color: #666; display: block;}
        .item-quantity-total { grid-column: 3; text-align: right; }
        .item-quantity { display: flex; align-items: center; justify-content: flex-end; gap: 8px; margin-bottom: 5px;}
        .quantity-btn { background-color: #eee; border: 1px solid #ddd; border-radius: 50%; width: 28px; height: 28px; cursor: pointer; font-size: 1.1rem; line-height: 1; display: flex; align-items: center; justify-content: center; }
        .quantity-btn:hover { background-color: #e0e0e0; }
        .item-total { font-weight: bold; font-size: 1rem; color: var(--bg-medium);}
        .order-summary { margin-top: 30px; padding-top: 20px; border-top: 2px solid var(--accent); text-align: right; }
        .order-summary p { margin-bottom: 10px; font-size: 1.1rem; }
        .order-summary strong { font-size: 1.3rem; color: var(--bg-medium); }
        .customer-info { margin-top: 30px; background-color: #f9f9f9; padding: 20px; border-radius: 8px; border: 1px solid #e0e0e0;}
        .customer-info p { margin-bottom: 8px; font-size: 0.95rem; }
        .customer-info strong { color: var(--bg-medium); }
        .actions { margin-top: 30px; text-align: center; }
        .button { padding: 12px 25px; border: none; border-radius: 8px; background-color: var(--accent); color: var(--text-dark); font-weight: 600; cursor: pointer; transition: background-color 0.3s ease, transform 0.1s ease; font-size: 1rem; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; }
        .button:hover { background-color: #77E4D8; }
        .button:active { transform: scale(0.98); }
        .button i { font-size: 1.2rem; }
        .catalog-link { display: block; text-align: center; margin-top: 25px; color: var(--bg-medium); text-decoration: none; font-size: 0.9rem; }
        .catalog-link:hover { text-decoration: underline; }
        .not-found { text-align: center; color: #dc3545; font-size: 1.2rem; padding: 40px 0;}
        @media (max-width: 600px) {
            .order-item { grid-template-columns: 60px 1fr; }
            .item-quantity-total { grid-column: 1 / -1; grid-row: 2; text-align: left; margin-top: 10px; display: flex; justify-content: space-between; align-items: center; }
        }
    </style>
</head>
<body>
    <div class="container">
        {% if order %}
            <h1><i class="fas fa-receipt"></i> Ваш Заказ №<span id="orderId">{{ order.id }}</span></h1>
            <p class="order-meta">Дата создания: {{ order.created_at }}</p>

            <h2><i class="fas fa-shopping-bag"></i> Товары в заказе</h2>
            <div id="orderItems"></div>

            <div class="order-summary">
                <p><strong>ИТОГО К ОПЛАТЕ: <span id="orderTotal">{{ "%.2f"|format(order.total_price) }}</span> {{ currency_code }}</strong></p>
            </div>

            <div class="customer-info">
                 <h2><i class="fas fa-info-circle"></i> Статус заказа</h2>
                 <p>Этот заказ был оформлен без входа в систему. Вы можете скорректировать его и отправить в WhatsApp.</p>
                 <p>Пожалуйста, свяжитесь с нами по WhatsApp для подтверждения и уточнения деталей.</p>
            </div>

            <div class="actions">
                 <button class="button" onclick="sendOrderViaWhatsApp()"><i class="fab fa-whatsapp"></i> Отправить заказ</button>
            </div>

            <a href="{{ url_for('catalog', env_id=env_id) }}" class="catalog-link">← Вернуться в каталог</a>

            <script>
                let order = {{ order|tojson|safe }};

                function renderOrderItems() {
                    const container = document.getElementById('orderItems');
                    if (!container) return;
                    
                    if (order.cart.length === 0) {
                        container.innerHTML = '<p style="text-align:center; padding: 20px;">Заказ пуст.</p>';
                        document.querySelector('.actions .button').disabled = true;
                    } else {
                        container.innerHTML = order.cart.map((item, index) => {
                            let variantInfo = [];
                            if (item.color && item.color !== 'N/A') variantInfo.push(`Цвет: ${item.color}`);
                            if (item.size && item.size !== 'N/A') variantInfo.push(`Размер: ${item.size}`);

                            return `
                            <div class="order-item">
                                <img src="${item.photo_url}" alt="${item.name}">
                                <div class="item-details">
                                    <strong>${item.name}</strong>
                                    <span>${variantInfo.join(', ')}</span>
                                    <span>${item.price.toFixed(2)} {{ currency_code }}</span>
                                </div>
                                <div class="item-quantity-total">
                                    <div class="item-quantity">
                                        <button class="quantity-btn" onclick="decrementItem(${index})">-</button>
                                        <span>${item.quantity}</span>
                                        <button class="quantity-btn" onclick="incrementItem(${index})">+</button>
                                    </div>
                                    <div class="item-total">
                                        ${(item.price * item.quantity).toFixed(2)} {{ currency_code }}
                                    </div>
                                </div>
                            </div>
                        `}).join('');
                        document.querySelector('.actions .button').disabled = false;
                    }
                    updateOrderTotal();
                }

                function updateOrderTotal() {
                    const totalElement = document.getElementById('orderTotal');
                    if (!totalElement) return;
                    const total = order.cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
                    order.total_price = total;
                    totalElement.textContent = total.toFixed(2);
                }

                function incrementItem(index) {
                    if (order.cart[index]) {
                        order.cart[index].quantity++;
                        renderOrderItems();
                    }
                }

                function decrementItem(index) {
                    if (order.cart[index]) {
                        order.cart[index].quantity--;
                        if (order.cart[index].quantity <= 0) {
                            if (confirm(`Удалить "${order.cart[index].name}" из заказа?`)) {
                                order.cart.splice(index, 1);
                            } else {
                                order.cart[index].quantity = 1;
                            }
                        }
                        renderOrderItems();
                    }
                }

                function sendOrderViaWhatsApp() {
                    if (order.cart.length === 0) {
                        alert("Нельзя отправить пустой заказ.");
                        return;
                    }
                    const orderId = document.getElementById('orderId').textContent;
                    const whatsappNumber = "{{ whatsapp_number }}".replace(/[^0-9]/g, '');
                    let message = `Здравствуйте! Хочу подтвердить или изменить свой заказ в магазине {{ settings.organization_name }}:%0A%0A`;
                    message += `*Номер заказа:* ${orderId}%0A%0A`;
                    
                    order.cart.forEach(item => {
                        let variantInfo = [];
                        if (item.color && item.color !== 'N/A') variantInfo.push(item.color);
                        if (item.size && item.size !== 'N/A') variantInfo.push(item.size);
                        let variantText = variantInfo.length > 0 ? ` (${variantInfo.join(', ')})` : '';

                        message += `*${item.name}*${variantText}%0A`;
                        message += `  - Количество: ${item.quantity}%0A`;
                        message += `  - Цена: ${item.price.toFixed(2)} {{ currency_code }}%0A`;
                    });

                    message += `%0A*Итоговая сумма:* ${order.total_price.toFixed(2)} {{ currency_code }}%0A%0A`;
                    message += `Пожалуйста, свяжитесь со мной для уточнения деталей.`;

                    const whatsappUrl = `https://api.whatsapp.com/send?phone=${whatsappNumber}&text=${message}`;
                    window.open(whatsappUrl, '_blank');
                }
                
                document.addEventListener('DOMContentLoaded', renderOrderItems);
            </script>
        {% else %}
            <h1 style="color: #dc3545;"><i class="fas fa-exclamation-triangle"></i> Ошибка</h1>
            <p class="not-found">Заказ с таким ID не найден.</p>
            <a href="{{ url_for('catalog', env_id=env_id) }}" class="catalog-link">← Вернуться в каталог</a>
        {% endif %}
    </div>
</body>
</html>
'''

ADMIN_TEMPLATE = '''
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Админ-панель - {{ settings.organization_name }}</title>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
        <style>
            :root {
                --bg-light: #f4f6f9;
                --bg-medium: #135D66;
                --accent: #48D1CC;
                --accent-hover: #77E4D8;
                --text-dark: #333;
                --text-on-accent: #003C43;
                --danger: #E57373;
                --danger-hover: #EF5350;
            }
            body { font-family: 'Montserrat', sans-serif; background-color: var(--bg-light); color: var(--text-dark); padding: 20px; line-height: 1.6; }
            .container { max-width: 1200px; margin: 0 auto; background-color: #fff; padding: 25px; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.05); }
            .header { padding-bottom: 15px; margin-bottom: 25px; border-bottom: 1px solid #e0e0e0; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;}
            .header .logo-title-container img { height: 50px; width: 50px; border-radius: 50%; object-fit: cover; border: 2px solid var(--bg-medium);}
            h1, h2, h3 { font-weight: 600; color: var(--bg-medium); margin-bottom: 15px; }
            h1 { font-size: 1.8rem; }
            h2 { font-size: 1.5rem; margin-top: 30px; display: flex; align-items: center; gap: 8px; }
            h3 { font-size: 1.2rem; color: #004D40; margin-top: 20px; }
            .section { margin-bottom: 30px; padding: 20px; background-color: #fdfdff; border: 1px solid #e0e0e0; border-radius: 8px; }
            form { margin-bottom: 20px; }
            label { font-weight: 500; margin-top: 10px; display: block; color: #666; font-size: 0.9rem;}
            input[type="text"], input[type="number"], input[type="password"], input[type="tel"], textarea, select { width: 100%; padding: 10px 12px; margin-top: 5px; border: 1px solid #e0e0e0; border-radius: 6px; font-size: 0.95rem; box-sizing: border-box; transition: border-color 0.3s ease; background-color: #fff; }
            input:focus, textarea:focus, select:focus { border-color: var(--bg-medium); outline: none; box-shadow: 0 0 0 2px rgba(19, 93, 102, 0.1); }
            textarea { min-height: 80px; resize: vertical; }
            input[type="file"] { padding: 8px; background-color: #ffffff; cursor: pointer; border: 1px solid #e0e0e0;}
            input[type="file"]::file-selector-button { padding: 5px 10px; border-radius: 4px; background-color: #f0f0f0; border: 1px solid #e0e0e0; cursor: pointer; margin-right: 10px;}
            input[type="checkbox"] { margin-right: 5px; vertical-align: middle; }
            label.inline-label { display: inline-block; margin-top: 10px; font-weight: normal; }
            button, .button { padding: 10px 18px; border: none; border-radius: 6px; background-color: var(--accent); color: var(--text-on-accent); font-weight: 600; cursor: pointer; transition: background-color 0.3s ease, transform 0.1s ease; margin-top: 15px; font-size: 0.95rem; display: inline-flex; align-items: center; gap: 5px; text-decoration: none; line-height: 1.2;}
            button:hover, .button:hover { background-color: var(--accent-hover); }
            button:active, .button:active { transform: scale(0.98); }
            button[type="submit"] { min-width: 120px; justify-content: center; }
            .delete-button { background-color: var(--danger); color: white; }
            .delete-button:hover { background-color: var(--danger-hover); }
            .add-button { background-color: var(--bg-medium); color: white; }
            .add-button:hover { background-color: #003C43; }
            .item-list { display: grid; gap: 20px; }
            .item { background: #fff; padding: 15px 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.03); border: 1px solid #f0f0f0; }
            .item p { margin: 5px 0; font-size: 0.9rem; color: #666; }
            .item strong { color: var(--text-dark); }
            .item .description { font-size: 0.85rem; color: #999; max-height: 60px; overflow: hidden; text-overflow: ellipsis; }
            .item-actions { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
            .edit-form-container { margin-top: 15px; padding: 20px; background: #E0F2F1; border: 1px dashed #B2DFDB; border-radius: 6px; display: none; }
            details { background-color: #fdfdff; border: 1px solid #e0e0e0; border-radius: 8px; margin-bottom: 20px; }
            details > summary { cursor: pointer; font-weight: 600; color: var(--bg-medium); display: block; padding: 15px; list-style: none; position: relative; font-size: 1.2rem; }
            details > summary:hover { background-color: #fafafa; }
            details > summary::after { content: '\\f078'; font-family: 'Font Awesome 6 Free'; font-weight: 900; position: absolute; right: 20px; top: 50%; transform: translateY(-50%); transition: transform 0.2s ease; color: var(--bg-medium); }
            details[open] > summary::after { transform: translateY(-50%) rotate(180deg); }
            details[open] > summary { border-bottom: 1px solid #e0e0e0; }
            details .form-content { padding: 20px; }
            .option-input-group { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
            .option-input-group input { flex-grow: 1; margin: 0; }
            .remove-option-btn { background-color: var(--danger); color: white; padding: 6px 10px; font-size: 0.8rem; margin-top: 0; line-height: 1; }
            .remove-option-btn:hover { background-color: var(--danger-hover); }
            .add-option-btn { background-color: #B2DFDB; color: var(--bg-medium); border: 1px solid #e0e0e0; }
            .add-option-btn:hover { background-color: var(--bg-medium); color: white; border-color: var(--bg-medium); }
            .photo-preview img { max-width: 70px; max-height: 70px; border-radius: 5px; margin: 5px 5px 0 0; border: 1px solid #e0e0e0; object-fit: cover;}
            .sync-buttons { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
            .download-hf-button { background-color: #6c757d; color: white; }
            .download-hf-button:hover { background-color: #5a6268; }
            .flex-container { display: flex; flex-wrap: wrap; gap: 20px; }
            .flex-item { flex: 1; min-width: 350px; }
            .message { padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; font-size: 0.9rem;}
            .message.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;}
            .message.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;}
            .message.warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
            .status-indicator { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem; font-weight: 500; margin-left: 10px; vertical-align: middle; }
            .status-indicator.in-stock { background-color: #d4edda; color: #155724; }
            .status-indicator.out-of-stock { background-color: #f8d7da; color: #721c24; }
            .status-indicator.top-product { background-color: #FFF9C4; color: #F57F17; margin-left: 5px;}
            .status-indicator.expires-soon { background-color: var(--danger); color: white; }
            .ai-generate-button { background-color: #8D6EC8; color: white; margin-top: 5px; margin-bottom: 10px; }
            .ai-generate-button:hover { background-color: #7B4DB5; }
            .chat-log-item { padding: 10px; border: 1px solid #eee; border-radius: 5px; cursor: pointer; transition: background-color 0.2s; }
            .chat-log-item:hover { background-color: #f7f7f7; }
            .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); }
            .modal-content { background: #fff; margin: 10% auto; padding: 20px; border-radius: 8px; width: 90%; max-width: 600px; }
            .chat-message-viewer { max-height: 60vh; overflow-y: auto; }
            .chat-message.user { text-align: right; margin: 5px 0; }
            .chat-message.ai { text-align: left; margin: 5px 0; }
            .chat-message .bubble { display: inline-block; padding: 8px 12px; border-radius: 15px; max-width: 80%; }
            .chat-message.user .bubble { background-color: #dcf8c6; }
            .chat-message.ai .bubble { background-color: #f1f1f1; }
            .current-avatar { max-width: 60px; max-height: 60px; border-radius: 50%; vertical-align: middle; margin-left: 10px; border: 2px solid var(--bg-medium);}
            .variant-price-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 10px; background-color: #f7f9fa; padding: 10px; border-radius: 5px; margin-top: 10px; border: 1px solid #e0e0e0; }
            .variant-price-item { display: flex; align-items: center; gap: 8px; font-size: 0.9em; }
            .variant-price-item label { margin-top: 0; white-space: nowrap; }
            .variant-price-item input { margin-top: 0; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <div class="logo-title-container" style="display: flex; align-items: center; gap: 15px;">
                     <img src="{{ chat_avatar_url }}" alt="Logo">
                    <h1><i class="fas fa-tools"></i> Админ-панель {{ settings.organization_name }} (Среда: {{ env_id }})</h1>
                </div>
                <a href="{{ url_for('catalog', env_id=env_id) }}" class="button" style="background-color: var(--bg-medium); color: white;"><i class="fas fa-store"></i> Перейти в каталог</a>
            </div>

            {% with messages = get_flashed_messages(with_categories=true) %}
                {% if messages %}
                    {% for category, message in messages %}
                        <div class="message {{ category }}">{{ message }}</div>
                    {% endfor %}
                {% endif %}
            {% endwith %}

            <div class="section">
                 <h2><i class="fas fa-robot"></i> Статус активации чата</h2>
                 {% if chat_status.active %}
                     <p>Чат <strong>активен</strong>. Срок действия истекает: <strong class="{{ 'status-indicator expires-soon' if chat_status.expires_soon else '' }}">{{ chat_status.expires_date }}</strong></p>
                 {% else %}
                     <p>Чат <strong>неактивен</strong>. {% if chat_status.expires_date %}Срок действия истек: {{ chat_status.expires_date }}{% endif %}</p>
                     <p style="color: var(--danger);">Для активации чат-бота, пожалуйста, свяжитесь с администратором.</p>
                     <a href="https://wa.me/77472479197" target="_blank" class="button add-button" style="margin-top: 10px;"><i class="fab fa-whatsapp"></i> Написать администратору</a>
                 {% endif %}
            </div>

            <div class="section">
                <h2><i class="fab fa-whatsapp"></i> Интеграция с WhatsApp</h2>
                {% if whatsapp_is_active %}
                    <p style="color: green;">WhatsApp бот активен для среды <strong>{{ whatsapp_env_id }}</strong>.</p>
                    <a href="{{ url_for('stop_whatsapp_bot', env_id=env_id) }}" class="button delete-button">Остановить WhatsApp Бота</a>
                {% else %}
                    <p>Запустите ИИ-консультанта в WhatsApp. После запуска, откроется браузер. Если потребуется, отсканируйте QR-код.</p>
                    <a href="{{ url_for('start_whatsapp_bot', env_id=env_id) }}" class="button add-button" style="background-color: #25D366; color: white;"><i class="fab fa-whatsapp"></i> Запустить WhatsApp Бота</a>
                {% endif %}
            </div>

            <div class="section">
                <h2><i class="fas fa-sync-alt"></i> Синхронизация с Датацентром</h2>
                <div class="sync-buttons">
                    <form method="POST" action="{{ url_for('force_upload', env_id=env_id) }}" style="display: inline;" onsubmit="return confirm('Вы уверены, что хотите принудительно загрузить локальные данные на сервер? Это перезапишет данные на сервере.');">
                        <button type="submit" class="button add-button" title="Загрузить локальные файлы на Hugging Face"><i class="fas fa-upload"></i> Загрузить БД</button>
                    </form>
                    <form method="POST" action="{{ url_for('force_download', env_id=env_id) }}" style="display: inline;" onsubmit="return confirm('Вы уверены, что хотите принудительно скачать данные с сервера? Это перезапишет ваши локальные файлы.');">
                        <button type="submit" class="button download-hf-button" title="Скачать файлы  (перезапишет локальные)"><i class="fas fa-download"></i> Скачать БД</button>
                    </form>
                </div>
                 <p style="font-size: 0.85rem; color: #999;">Резервное копирование происходит автоматически каждые 30 минут, а также после каждого сохранения данных. Используйте эти кнопки для немедленной синхронизации.</p>
            </div>
            
            <div class="section">
                 <details>
                     <summary><i class="fas fa-cog"></i> Настройки магазина и чата</summary>
                     <div class="form-content">
                         <form method="POST" enctype="multipart/form-data">
                             <input type="hidden" name="action" value="update_settings">
                             
                             <label for="organization_name">Название организации:</label>
                             <input type="text" id="organization_name" name="organization_name" value="{{ settings.organization_name }}">

                             <label for="whatsapp_number">Номер WhatsApp для заказов:</label>
                             <input type="tel" id="whatsapp_number" name="whatsapp_number" value="{{ settings.whatsapp_number }}" placeholder="+996XXXXXXXXX">
                             
                             <label for="currency_code">Валюта магазина:</label>
                             <select id="currency_code" name="currency_code">
                                 {% for code, name in currencies.items() %}
                                 <option value="{{ code }}" {% if settings.currency_code == code %}selected{% endif %}>{{ name }} ({{ code }})</option>
                                 {% endfor %}
                             </select>
                             
                             <label for="business_type">Тип бизнеса:</label>
                             <select id="business_type" name="business_type">
                                <option value="retail" {% if settings.business_type == 'retail' %}selected{% endif %}>Розница</option>
                                <option value="wholesale" {% if settings.business_type == 'wholesale' %}selected{% endif %}>Опт</option>
                                <option value="combined" {% if settings.get('business_type', 'combined') == 'combined' %}selected{% endif %}>Опт и Розница</option>
                             </select>

                             <label for="chat_name">Имя чат-ассистента:</label>
                             <input type="text" id="chat_name" name="chat_name" value="{{ settings.chat_name }}">

                             <label for="chat_avatar">Аватар чата (загрузите новый, чтобы изменить):</label>
                             <input type="file" id="chat_avatar" name="chat_avatar" accept="image/png, image/jpeg, image/gif, image/webp">
                             {% if settings.chat_avatar %}
                                <p style="font-size: 0.85rem; margin-top: 5px;">Текущий аватар: <img src="{{ chat_avatar_url }}" class="current-avatar"></p>
                             {% endif %}

                             <label for="color_scheme">Цветовая схема каталога и чата:</label>
                             <select id="color_scheme" name="color_scheme">
                                 {% for key, name in color_schemes.items() %}
                                 <option value="{{ key }}" {% if settings.color_scheme == key %}selected{% endif %}>{{ name }}</option>
                                 {% endfor %}
                             </select>

                             <button type="submit" class="add-button"><i class="fas fa-save"></i> Сохранить настройки</button>
                         </form>
                     </div>
                 </details>
            </div>


            <div class="section">
                <details>
                    <summary><i class="fas fa-comments"></i> Диалоги с {{ settings.chat_name }}</summary>
                    <div class="form-content">
                        <div class="item-list">
                            {% if chats %}
                                {% for chat_id, chat_data in chats.items()|sort(reverse=True) %}
                                <div class="chat-log-item" onclick="viewChat('{{ chat_id }}')">
                                    <strong>ID Диалога:</strong> {{ chat_id }}
                                    <br>
                                    <small>Сообщений: {{ chat_data|length }} | Последнее сообщение: {{ chat_data[-1].timestamp if chat_data and 'timestamp' in chat_data[-1] else 'N/A' }}</small>
                                </div>
                                {% endfor %}
                            {% else %}
                                <p>Пока не было ни одного диалога.</p>
                            {% endif %}
                        </div>
                    </div>
                </details>
            </div>

            <div class="flex-container">
                 <div class="flex-item">
                     <div class="section">
                         <h2><i class="fas fa-tags"></i> Управление категориями</h2>
                          <details>
                              <summary><i class="fas fa-plus-circle"></i> Добавить новую категорию</summary>
                              <div class="form-content">
                                  <form method="POST">
                                      <input type="hidden" name="action" value="add_category">
                                      <label for="add_category_name">Название новой категории:</label>
                                      <input type="text" id="add_category_name" name="category_name" required>
                                      <button type="submit" class="add-button"><i class="fas fa-plus"></i> Добавить</button>
                                  </form>
                              </div>
                          </details>

                         <h3>Существующие категории:</h3>
                         {% if categories %}
                         <div class="item-list">
                             {% for category in categories %}
                             <div class="item" style="display: flex; justify-content: space-between; align-items: center;">
                                 <span>{{ category }}</span>
                                 <form method="POST" style="margin: 0;" onsubmit="return confirm('Вы уверены, что хотите удалить категорию \'{{ category }}\'? Товары этой категории будут помечены как \'Без категории\'.');">
                                     <input type="hidden" name="action" value="delete_category">
                                     <input type="hidden" name="category_name" value="{{ category }}">
                                     <button type="submit" class="delete-button" style="padding: 5px 10px; font-size: 0.8rem; margin: 0;"><i class="fas fa-trash-alt"></i></button>
                                 </form>
                             </div>
                             {% endfor %}
                         </div>
                         {% else %}
                         <p>Категорий пока нет.</p>
                         {% endif %}
                     </div>
                 </div>

                 <div class="flex-item">
                      <div class="section">
                        <h2><i class="fas fa-info-circle"></i> Информация о магазине</h2>
                        <details>
                            <summary><i class="fas fa-chevron-down"></i> Развернуть/Свернуть</summary>
                            <div class="form-content">
                                <form method="POST">
                                    <input type="hidden" name="action" value="update_org_info">
                                    <label for="about_us">О нас (для ИИ-ассистента):</label>
                                    <textarea id="about_us" name="about_us" rows="4">{{ organization_info.get('about_us', '') }}</textarea>
                                    <label for="shipping">Информация о доставке (для ИИ-ассистента):</label>
                                    <textarea id="shipping" name="shipping" rows="4">{{ organization_info.get('shipping', '') }}</textarea>
                                    <label for="returns">Информация о возврате/обмене (для ИИ-ассистента):</label>
                                    <textarea id="returns" name="returns" rows="4">{{ organization_info.get('returns', '') }}</textarea>
                                    <label for="contact">Контактная информация (для ИИ-ассистента):</label>
                                    <textarea id="contact" name="contact" rows="4">{{ organization_info.get('contact', '') }}</textarea>
                                    <button type="submit" class="add-button"><i class="fas fa-save"></i> Сохранить</button>
                                </form>
                                <p style="font-size: 0.85rem; color: #999;">Эта информация будет использоваться ИИ-ассистентом для ответов на вопросы о вашем магазине.</p>
                            </div>
                        </details>
                     </div>
                 </div>
            </div>

            <div class="section">
                <h2><i class="fas fa-box-open"></i> Управление товарами</h2>
                 <details>
                     <summary><i class="fas fa-plus-circle"></i> Добавить новый товар</summary>
                     <div class="form-content">
                         <form id="add-product-form" method="POST" enctype="multipart/form-data">
                             <input type="hidden" name="action" value="add_product">
                             <label for="add_name">Название товара *:</label>
                             <input type="text" id="add_name" name="name" required>
                             
                             {% if settings.get('business_type') != 'wholesale' %}
                             <label for="add_price">Розничная Цена ({{ currency_code }}) *:</label>
                             <input type="number" id="add_price" name="price" step="0.01" min="0" required>
                             {% endif %}

                             {% if settings.get('business_type') != 'retail' %}
                             <label for="add_wholesale_price">Оптовая Цена ({{ currency_code }}) {% if settings.get('business_type') == 'wholesale' %}*{% endif %}:</label>
                             <input type="number" id="add_wholesale_price" name="wholesale_price" step="0.01" min="0" {% if settings.get('business_type') == 'wholesale' %}required{% endif %}>
                             <label for="add_min_wholesale_quantity">Мин. кол-во для опта (шт.) {% if settings.get('business_type') == 'wholesale' %}*{% endif %}:</label>
                             <input type="number" id="add_min_wholesale_quantity" name="min_wholesale_quantity" min="1" {% if settings.get('business_type') == 'wholesale' %}required{% endif %}>
                             {% endif %}

                             <label for="add_photos">Фотографии (до 10 шт.):</label>
                             <input type="file" id="add_photos" name="photos" accept="image/*" multiple>
                             <label for="add_description">Описание:</label>
                             <textarea id="add_description" name="description" rows="4"></textarea>
                             <button type="button" class="button ai-generate-button" onclick="generateDescription('add_photos', 'add_description', 'add_gen_lang')"><i class="fas fa-magic"></i> Сгенерировать описание</button>
                             <label for="add_gen_lang">Язык генерации:</label>
                             <select id="add_gen_lang" name="gen_lang" style="width: auto; display: inline-block; margin-left: 10px;">
                                <option value="Русский">Русский</option>
                                <option value="Кыргызский">Кыргызский</option>
                                <option value="Казахский">Казахский</option>
                                <option value="Узбекский">Узбекский</option>
                             </select>
                             <label for="add_category">Категория:</label>
                             <select id="add_category" name="category">
                                 <option value="Без категории">Без категории</option>
                                 {% for category in categories %}
                                 <option value="{{ category }}">{{ category }}</option>
                                 {% endfor %}
                             </select>
                             <label>Цвета/Варианты (оставьте пустым, если нет):</label>
                             <div id="add-color-inputs" class="option-inputs" data-type="color">
                                 <div class="option-input-group">
                                     <input type="text" name="colors" placeholder="Например: Розовый">
                                     <button type="button" class="remove-option-btn" onclick="removeOptionInput(this)"><i class="fas fa-times"></i></button>
                                 </div>
                             </div>
                             <button type="button" class="button add-option-btn" style="margin-top: 5px;" onclick="addOptionInput('add-color-inputs', 'colors')"><i class="fas fa-palette"></i> Добавить поле</button>
                             
                             <label style="margin-top: 15px;">Размеры/Объем (оставьте пустым, если нет):</label>
                             <div id="add-size-inputs" class="option-inputs" data-type="size">
                                 <div class="option-input-group">
                                     <input type="text" name="sizes" placeholder="Например: 42 или 50ml">
                                     <button type="button" class="remove-option-btn" onclick="removeOptionInput(this)"><i class="fas fa-times"></i></button>
                                 </div>
                             </div>
                             <button type="button" class="button add-option-btn" style="margin-top: 5px;" onclick="addOptionInput('add-size-inputs', 'sizes')"><i class="fas fa-ruler-combined"></i> Добавить поле</button>

                             <h3 style="margin-top: 20px;">Особые цены для вариантов</h3>
                             <p style="font-size:0.85em; color:#666;">Здесь можно указать цену для конкретного сочетания цвета и размера. Если цена не указана, будет использоваться базовая.</p>
                             <div id="add-variant-prices-container" class="variant-price-grid"></div>

                             <br>
                             <div style="margin-top: 15px;">
                                 <input type="checkbox" id="add_in_stock" name="in_stock" checked>
                                 <label for="add_in_stock" class="inline-label">В наличии</label>
                             </div>
                             <div style="margin-top: 5px;">
                                 <input type="checkbox" id="add_is_top" name="is_top">
                                 <label for="add_is_top" class="inline-label">Топ товар (показывать наверху)</label>
                             </div>
                             <br>
                             <button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Добавить товар</button>
                         </form>
                     </div>
                </details>

                <h3>Список товаров:</h3>
                {% if products %}
                <div class="item-list">
                    {% for product in products %}
                    <div class="item">
                        <div style="display: flex; gap: 15px; align-items: flex-start;">
                             <div class="photo-preview" style="flex-shrink: 0;">
                                {% if product.get('photos') %}
                                <a href="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" target="_blank" title="Посмотреть первое фото">
                                   <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" alt="Фото">
                                </a>
                                {% else %}
                                <img src="https://via.placeholder.com/70x70.png?text=N/A" alt="Нет фото">
                                {% endif %}
                            </div>
                            <div style="flex-grow: 1;">
                                <h3 style="margin-top: 0; margin-bottom: 5px; color: var(--text-dark);">
                                    {{ product['name'] }}
                                     {% if product.get('in_stock', True) %}
                                        <span class="status-indicator in-stock">В наличии</span>
                                     {% else %}
                                        <span class="status-indicator out-of-stock">Нет в наличии</span>
                                     {% endif %}
                                     {% if product.get('is_top', False) %}
                                        <span class="status-indicator top-product"><i class="fas fa-star"></i> Топ</span>
                                     {% endif %}
                                </h3>
                                <p><strong>Категория:</strong> {{ product.get('category', 'Без категории') }}</p>
                                {% if settings.get('business_type') != 'wholesale' %}
                                <p><strong>Цена:</strong> {{ "%.2f"|format(product.price) }} {{ currency_code }}</p>
                                {% endif %}
                                {% if settings.get('business_type') != 'retail' and product.get('wholesale_price') and product.get('min_wholesale_quantity') %}
                                <p><strong>Опт. цена:</strong> {{ "%.2f"|format(product.wholesale_price) }} {{ currency_code }} (от {{ product.min_wholesale_quantity }} шт.)</p>
                                {% endif %}
                                <p class="description" title="{{ product.get('description', '') }}"><strong>Описание:</strong> {{ product.get('description', 'N/A')[:150] }}{% if product.get('description', '')|length > 150 %}...{% endif %}</p>
                                {% set colors = product.get('colors', []) %}
                                {% set sizes = product.get('sizes', []) %}
                                <p><strong>Цвета/Вар-ты:</strong> {{ colors|select('ne', '')|join(', ') if colors|select('ne', '')|list|length > 0 else 'Нет' }}</p>
                                <p><strong>Размеры/Объем:</strong> {{ sizes|select('ne', '')|join(', ') if sizes|select('ne', '')|list|length > 0 else 'Нет' }}</p>

                                {% if product.get('photos') and product['photos']|length > 1 %}
                                    <p style="font-size: 0.8rem; color: #999;">(Всего фото: {{ product['photos']|length }})</p>
                                {% endif %}
                            </div>
                        </div>

                        <div class="item-actions">
                             <button type="button" class="button" onclick="toggleEditForm('edit-form-{{ loop.index0 }}')"><i class="fas fa-edit"></i> Редактировать</button>
                            <form method="POST" style="margin:0;" onsubmit="return confirm('Вы уверены, что хотите удалить товар \'{{ product['name'] }}\'?');">
                                <input type="hidden" name="action" value="delete_product">
                                <input type="hidden" name="product_id" value="{{ product.get('product_id', '') }}">
                                <button type="submit" class="delete-button"><i class="fas fa-trash-alt"></i> Удалить</button>
                            </form>
                        </div>

                        <div id="edit-form-{{ loop.index0 }}" class="edit-form-container">
                            <h4><i class="fas fa-edit"></i> Редактирование: {{ product['name'] }}</h4>
                            <form method="POST" enctype="multipart/form-data">
                                <input type="hidden" name="action" value="edit_product">
                                <input type="hidden" name="product_id" value="{{ product.get('product_id', '') }}">
                                <label>Название *:</label>
                                <input type="text" name="name" value="{{ product['name'] }}" required>
                                
                                {% if settings.get('business_type') != 'wholesale' %}
                                <label>Розничная Цена ({{ currency_code }}) *:</label>
                                <input type="number" name="price" step="0.01" min="0" value="{{ product['price'] }}" required>
                                {% endif %}

                                {% if settings.get('business_type') != 'retail' %}
                                <label>Оптовая Цена ({{ currency_code }}) {% if settings.get('business_type') == 'wholesale' %}*{% endif %}:</label>
                                <input type="number" name="wholesale_price" step="0.01" min="0" value="{{ product.get('wholesale_price', '') }}" {% if settings.get('business_type') == 'wholesale' %}required{% endif %}>
                                <label>Мин. кол-во для опта (шт.) {% if settings.get('business_type') == 'wholesale' %}*{% endif %}:</label>
                                <input type="number" name="min_wholesale_quantity" min="1" value="{{ product.get('min_wholesale_quantity', '') }}" {% if settings.get('business_type') == 'wholesale' %}required{% endif %}>
                                {% endif %}
                                
                                <label>Заменить фотографии (выберите новые файлы, до 10 шт.):</label>
                                <input type="file" id="edit_photos_{{ loop.index0 }}" name="photos" accept="image/*" multiple>
                                 {% if product.get('photos') %}
                                    <p style="font-size: 0.85rem; margin-top: 5px;">Текущие фото:</p>
                                    <div class="photo-preview">
                                        {% for photo in product['photos'] %}
                                        <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="Фото {{ loop.index }}">
                                        {% endfor %}
                                    </div>
                                {% endif %}
                                <label>Описание:</label>
                                <textarea id="edit_description_{{ loop.index0 }}" name="description" rows="4">{{ product.get('description', '') }}</textarea>
                                <button type="button" class="button ai-generate-button" onclick="generateDescription('edit_photos_{{ loop.index0 }}', 'edit_description_{{ loop.index0 }}', 'edit_gen_lang_{{ loop.index0 }}')"><i class="fas fa-magic"></i> Сгенерировать</button>
                                <label for="edit_gen_lang_{{ loop.index0 }}">Язык генерации:</label>
                                <select id="edit_gen_lang_{{ loop.index0 }}" name="gen_lang" style="width: auto; display: inline-block; margin-left: 10px;">
                                    <option value="Русский">Русский</option>
                                    <option value="Кыргызский">Кыргызский</option>
                                    <option value="Казахский">Казахский</option>
                                    <option value="Узбекский">Узбекский</option>
                                </select>
                                <label>Категория:</label>
                                <select name="category">
                                    <option value="Без категории" {% if product.get('category', 'Без категории') == 'Без категории' %}selected{% endif %}>Без категории</option>
                                    {% for category in categories %}
                                    <option value="{{ category }}" {% if product.get('category') == category %}selected{% endif %}>{{ category }}</option>
                                    {% endfor %}
                                </select>
                                <label>Цвета/Варианты:</label>
                                <div id="edit-color-inputs-{{ loop.index0 }}" class="option-inputs" data-type="color">
                                    {% set current_colors = product.get('colors', []) %}
                                    {% if current_colors and current_colors|select('ne', '')|list|length > 0 %}
                                        {% for color in current_colors %}
                                            {% if color.strip() %}
                                            <div class="option-input-group">
                                                <input type="text" name="colors" value="{{ color }}">
                                                <button type="button" class="remove-option-btn" onclick="removeOptionInput(this)"><i class="fas fa-times"></i></button>
                                            </div>
                                            {% endif %}
                                        {% endfor %}
                                     {% else %}
                                         <div class="option-input-group">
                                            <input type="text" name="colors" placeholder="Например: Цвет">
                                            <button type="button" class="remove-option-btn" onclick="removeOptionInput(this)"><i class="fas fa-times"></i></button>
                                         </div>
                                     {% endif %}
                                </div>
                                <button type="button" class="button add-option-btn" style="margin-top: 5px;" onclick="addOptionInput('edit-color-inputs-{{ loop.index0 }}', 'colors')"><i class="fas fa-palette"></i> Добавить поле</button>

                                <label style="margin-top: 15px;">Размеры/Объем:</label>
                                <div id="edit-size-inputs-{{ loop.index0 }}" class="option-inputs" data-type="size">
                                    {% set current_sizes = product.get('sizes', []) %}
                                    {% if current_sizes and current_sizes|select('ne', '')|list|length > 0 %}
                                        {% for size in current_sizes %}
                                            {% if size.strip() %}
                                            <div class="option-input-group">
                                                <input type="text" name="sizes" value="{{ size }}">
                                                <button type="button" class="remove-option-btn" onclick="removeOptionInput(this)"><i class="fas fa-times"></i></button>
                                            </div>
                                            {% endif %}
                                        {% endfor %}
                                     {% else %}
                                         <div class="option-input-group">
                                            <input type="text" name="sizes" placeholder="Например: L">
                                            <button type="button" class="remove-option-btn" onclick="removeOptionInput(this)"><i class="fas fa-times"></i></button>
                                         </div>
                                     {% endif %}
                                </div>
                                <button type="button" class="button add-option-btn" style="margin-top: 5px;" onclick="addOptionInput('edit-size-inputs-{{ loop.index0 }}', 'sizes')"><i class="fas fa-ruler-combined"></i> Добавить поле</button>

                                <h3 style="margin-top: 20px;">Особые цены для вариантов</h3>
                                <div id="edit-variant-prices-container-{{ loop.index0 }}" class="variant-price-grid"></div>

                                <br>
                                <div style="margin-top: 15px;">
                                     <input type="checkbox" id="edit_in_stock_{{ loop.index0 }}" name="in_stock" {% if product.get('in_stock', True) %}checked{% endif %}>
                                     <label for="edit_in_stock_{{ loop.index0 }}" class="inline-label">В наличии</label>
                                </div>
                                <div style="margin-top: 5px;">
                                     <input type="checkbox" id="edit_is_top_{{ loop.index0 }}" name="is_top" {% if product.get('is_top', False) %}checked{% endif %}>
                                     <label for="edit_is_top_{{ loop.index0 }}" class="inline-label">Топ товар</label>
                                </div>
                                <br>
                                <button type="submit" class="add-button" style="margin-top: 20px;"><i class="fas fa-save"></i> Сохранить</button>
                            </form>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <p>Товаров пока нет.</p>
                {% endif %}
            </div>
        </div>
        <div id="chat-modal" class="modal">
            <div class="modal-content">
                <span class="button delete-button" style="float:right;" onclick="closeModal('chat-modal')">&times;</span>
                <h2 id="chat-modal-title">Просмотр диалога</h2>
                <div id="chat-modal-body" class="chat-message-viewer"></div>
            </div>
        </div>

        <script>
            const allProductsForAdmin = {{ products|tojson|safe }};

            function toggleEditForm(formId) {
                const formContainer = document.getElementById(formId);
                if (formContainer) {
                    const isOpening = formContainer.style.display === 'none' || formContainer.style.display === '';
                    formContainer.style.display = isOpening ? 'block' : 'none';
                    if (isOpening) {
                        const index = parseInt(formId.split('-').pop());
                        const product = allProductsForAdmin[index];
                        const priceContainer = document.getElementById(`edit-variant-prices-container-${index}`);
                        const colorContainer = document.getElementById(`edit-color-inputs-${index}`);
                        const sizeContainer = document.getElementById(`edit-size-inputs-${index}`);

                        const updateVariantPrices = () => generateVariantPriceInputs(colorContainer, sizeContainer, priceContainer, product.variant_prices || {});
                        
                        colorContainer.addEventListener('input', updateVariantPrices);
                        sizeContainer.addEventListener('input', updateVariantPrices);
                        updateVariantPrices(); 
                    }
                }
            }
            
            function generateVariantPriceInputs(colorContainer, sizeContainer, priceContainer, existingPrices) {
                priceContainer.innerHTML = '';
                const colors = Array.from(colorContainer.querySelectorAll('input[name="colors"]')).map(i => i.value.trim()).filter(Boolean);
                const sizes = Array.from(sizeContainer.querySelectorAll('input[name="sizes"]')).map(i => i.value.trim()).filter(Boolean);

                if (colors.length === 0 && sizes.length > 0) {
                     sizes.forEach(size => {
                        const key = size;
                        const price = existingPrices[key] || '';
                        priceContainer.innerHTML += `
                            <div class="variant-price-item">
                                <label for="variant_price_${key}">${size}:</label>
                                <input type="number" step="0.01" name="variant_price_${key}" value="${price}" placeholder="Базовая цена">
                            </div>`;
                     });
                } else if (colors.length > 0 && sizes.length === 0) {
                     colors.forEach(color => {
                        const key = color;
                        const price = existingPrices[key] || '';
                        priceContainer.innerHTML += `
                            <div class="variant-price-item">
                                <label for="variant_price_${key}">${color}:</label>
                                <input type="number" step="0.01" name="variant_price_${key}" value="${price}" placeholder="Базовая цена">
                            </div>`;
                     });
                } else if (colors.length > 0 && sizes.length > 0) {
                     colors.forEach(color => {
                         sizes.forEach(size => {
                            const key = `${color}-${size}`;
                            const price = existingPrices[key] || '';
                            priceContainer.innerHTML += `
                                <div class="variant-price-item">
                                    <label for="variant_price_${key}">${color} - ${size}:</label>
                                    <input type="number" step="0.01" name="variant_price_${key}" value="${price}" placeholder="Базовая цена">
                                </div>`;
                         });
                     });
                }
            }

            function addOptionInput(containerId, name) {
                const container = document.getElementById(containerId);
                if (container) {
                    const newInputGroup = document.createElement('div');
                    newInputGroup.className = 'option-input-group';
                    newInputGroup.innerHTML = `
                        <input type="text" name="${name}" placeholder="Новый вариант">
                        <button type="button" class="remove-option-btn" onclick="removeOptionInput(this)"><i class="fas fa-times"></i></button>
                    `;
                    container.appendChild(newInputGroup);
                    newInputGroup.querySelector(`input[name="${name}"]`).focus();
                }
            }

            function removeOptionInput(button) {
                const group = button.closest('.option-input-group');
                if (group) {
                    const container = group.parentNode;
                    group.remove();
                    if (container && container.children.length === 0) {
                        const name = container.dataset.type === 'color' ? 'colors' : 'sizes';
                        const placeholder = container.dataset.type === 'color' ? 'Например: Цвет' : 'Например: L';
                        addOptionInput(container.id, name, placeholder);
                    }
                }
            }
            
            document.addEventListener('DOMContentLoaded', () => {
                const addForm = document.getElementById('add-product-form');
                const addColorContainer = document.getElementById('add-color-inputs');
                const addSizeContainer = document.getElementById('add-size-inputs');
                const addPriceContainer = document.getElementById('add-variant-prices-container');

                const updateAddFormPrices = () => generateVariantPriceInputs(addColorContainer, addSizeContainer, addPriceContainer, {});
                addColorContainer.addEventListener('input', updateAddFormPrices);
                addSizeContainer.addEventListener('input', updateAddFormPrices);
            });


            async function generateDescription(photoInputId, descriptionTextareaId, languageSelectId) {
                const photoInput = document.getElementById(photoInputId);
                const descriptionTextarea = document.getElementById(descriptionTextareaId);
                const languageSelect = document.getElementById(languageSelectId);
                const generateButton = descriptionTextarea.nextElementSibling; 

                if (!photoInput || !descriptionTextarea || !languageSelect || !generateButton) {
                    alert("Ошибка: Не найдены элементы формы для генерации.");
                    return;
                }

                if (!photoInput.files || photoInput.files.length === 0) {
                    alert("Пожалуйста, сначала загрузите фотографию товара.");
                    return;
                }

                const file = photoInput.files[0];
                if (!file.type.startsWith('image/')) {
                    alert("Выбранный файл не является изображением.");
                    return;
                }

                generateButton.disabled = true;
                const originalText = generateButton.innerHTML;
                generateButton.innerHTML = '<i class="fas fa-sync fa-spin"></i> Генерация...';
                descriptionTextarea.value = 'Генерация описания, пожалуйста подождите...';
                descriptionTextarea.disabled = true;

                const reader = new FileReader();
                reader.onload = async (e) => {
                    const base64Image = e.target.result.split(',')[1];
                    const language = languageSelect.value;

                    try {
                        const response = await fetch('/generate_description_ai', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ image: base64Image, language: language })
                        });
                        const result = await response.json();

                        if (!response.ok) {
                            throw new Error(result.error || `Ошибка сервера: ${response.status}`);
                        }
                        descriptionTextarea.value = result.text;
                    } catch (error) {
                        console.error("AI Generation Error:", error);
                        descriptionTextarea.value = `Ошибка генерации: ${error.message}`;
                        alert(`Ошибка генерации: ${error.message}`);
                    } finally {
                        generateButton.disabled = false;
                        generateButton.innerHTML = originalText;
                        descriptionTextarea.disabled = false;
                    }
                };
                reader.onerror = (e) => {
                    console.error("FileReader error:", e);
                    descriptionTextarea.value = "Ошибка чтения файла изображения.";
                    generateButton.disabled = false;
                    generateButton.innerHTML = originalText;
                    descriptionTextarea.disabled = false;
                };
                reader.readAsDataURL(file);
            }
            
            function openModal(modalId) {
                document.getElementById(modalId).style.display = 'block';
            }
            function closeModal(modalId) {
                document.getElementById(modalId).style.display = 'none';
            }

            async function viewChat(chatId) {
                const modalBody = document.getElementById('chat-modal-body');
                modalBody.innerHTML = 'Загрузка...';
                openModal('chat-modal');
                try {
                    const response = await fetch(`/${env_id}/get_chat/${chatId}`);
                    if(!response.ok) throw new Error('Chat not found');
                    const chatHistory = await response.json();
                    
                    modalBody.innerHTML = '';
                    chatHistory.forEach(msg => {
                        const msgDiv = document.createElement('div');
                        msgDiv.className = `chat-message ${msg.role}`;
                        
                        const bubble = document.createElement('div');
                        bubble.className = 'bubble';
                        bubble.innerText = msg.text;
                        
                        msgDiv.appendChild(bubble);
                        modalBody.appendChild(msgDiv);
                    });

                } catch (e) {
                    modalBody.innerHTML = 'Не удалось загрузить диалог.';
                }
            }
             window.onclick = function(event) {
                if (event.target.classList.contains('modal')) {
                    closeModal(event.target.id);
                }
            }
        </script>
    </body>
    </html>
'''

@app.route('/')
def index():
    return render_template_string(LANDING_PAGE_TEMPLATE)

@app.route('/admhosto', methods=['GET'])
def admhosto():
    data = load_data()
    environments_data = []
    
    for env_id, env_data in data.items():
        settings = env_data.get('settings', {})
        is_active = False
        expires_soon = False
        expires_date_str = "N/A"

        if settings.get('chat_activated', False):
            expires_str = settings.get('chat_activation_expires')
            if expires_str:
                try:
                    expires_dt = datetime.fromisoformat(expires_str)
                    now_almaty = datetime.now(ALMATY_TZ)
                    if expires_dt > now_almaty:
                        is_active = True
                        expires_date_str = expires_dt.strftime('%Y-%m-%d')
                        if (expires_dt - now_almaty).days <= 4:
                            expires_soon = True
                except (ValueError, TypeError):
                    pass
        
        environments_data.append({
            "id": env_id,
            "chat_active": is_active,
            "expires_soon": expires_soon,
            "expires_date": expires_date_str
        })
        
    environments_data.sort(key=lambda x: x['id'])
    return render_template_string(ADMHOSTO_TEMPLATE, environments=environments_data)

@app.route('/admhosto/create', methods=['POST'])
def create_environment():
    all_data = load_data()
    while True:
        new_id = ''.join(random.choices(string.digits, k=6))
        if new_id not in all_data:
            break
    
    all_data[new_id] = {
        'products': [],
        'categories': [],
        'orders': {},
        'organization_info': {
            "about_us": "Мы — Gippo312, ваш надежный партнер в мире уникальных товаров.",
            "shipping": "Доставка осуществляется по всему Кыргызстану.",
            "returns": "Возврат и обмен товара возможен в течение 14 дней.",
            "contact": "Наш магазин находится по адресу: ... Связаться с нами можно по телефону ..."
        },
        'settings': {
            "organization_name": "Gippo312",
            "whatsapp_number": "+996701202013",
            "currency_code": "KGS",
            "chat_name": "EVA",
            "chat_avatar": None,
            "color_scheme": "default",
            "chat_activated": False,
            "chat_activation_expires": None,
            "business_type": "combined"
        },
        'chats': {}
    }
    save_data(all_data)
    flash(f'Новая среда с ID {new_id} успешно создана.', 'success')
    return redirect(url_for('admhosto'))

@app.route('/admhosto/delete/<env_id>', methods=['POST'])
def delete_environment(env_id):
    all_data = load_data()
    if env_id in all_data:
        del all_data[env_id]
        save_data(all_data)
        flash(f'Среда {env_id} была удалена.', 'success')
    else:
        flash(f'Среда {env_id} не найдена.', 'error')
    return redirect(url_for('admhosto'))

@app.route('/admhosto/activate/<env_id>', methods=['POST'])
def activate_chat(env_id):
    period = request.form.get('period')
    
    if not period:
        flash('Не выбран период активации.', 'error')
        return redirect(url_for('admhosto'))

    delta = None
    if period == 'month':
        delta = timedelta(days=30)
    elif period == 'half_year':
        delta = timedelta(days=182)
    elif period == 'year':
        delta = timedelta(days=365)
    
    if not delta:
        flash('Неверный период активации.', 'error')
        return redirect(url_for('admhosto'))

    data = get_env_data(env_id)
    if not data:
        flash(f'Среда {env_id} не найдена.', 'error')
        return redirect(url_for('admhosto'))

    settings = data.get('settings', {})
    now_almaty = datetime.now(ALMATY_TZ)
    
    start_date = now_almaty
    expires_str = settings.get('chat_activation_expires')
    if expires_str:
        try:
            current_expires_dt = datetime.fromisoformat(expires_str)
            if current_expires_dt > now_almaty:
                start_date = current_expires_dt
        except (ValueError, TypeError):
            pass
    
    new_expires_date = start_date + delta
    
    settings['chat_activated'] = True
    settings['chat_activation_expires'] = new_expires_date.isoformat()
    data['settings'] = settings
    
    save_env_data(env_id, data)
    flash(f'Чат для среды {env_id} активирован/продлен до {new_expires_date.strftime("%Y-%m-%d")}.', 'success')
    return redirect(url_for('admhosto'))

@app.route('/<env_id>/catalog')
def catalog(env_id):
    data = get_env_data(env_id)
    all_products_raw = data.get('products', [])
    settings = data.get('settings', {})
    
    product_categories = set(p.get('category', 'Без категории') for p in all_products_raw)
    admin_categories = set(data.get('categories', []))
    all_cat_names = sorted(list(product_categories.union(admin_categories)))

    products_in_stock = [p for p in all_products_raw if p.get('in_stock', True)]
    
    products_sorted_for_js = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))

    products_by_category = {cat: [] for cat in all_cat_names}
    for product in products_in_stock:
        products_by_category[product.get('category', 'Без категории')].append(product)

    for category in products_by_category:
        products_by_category[category].sort(key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))
    
    ordered_categories = [cat for cat in all_cat_names if products_by_category.get(cat)]

    chat_avatar_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/avatars/{settings['chat_avatar']}" if settings.get('chat_avatar') else "https://huggingface.co/spaces/gippo312/admin/resolve/main/Picsart_25-11-04_12-02-21-390.png"
    
    chat_active = is_chat_active(env_id)

    return render_template_string(
        CATALOG_TEMPLATE,
        products_by_category=products_by_category,
        ordered_categories=ordered_categories,
        products_json=json.dumps(products_sorted_for_js),
        repo_id=REPO_ID,
        currency_code=settings.get('currency_code', 'KGS'),
        settings=settings,
        chat_avatar_url=chat_avatar_url,
        env_id=env_id,
        chat_is_active=chat_active
    )

@app.route('/<env_id>/product/<int:index>')
def product_detail(env_id, index):
    data = get_env_data(env_id)
    all_products_raw = data.get('products', [])
    settings = data.get('settings', {})
    products_in_stock = [p for p in all_products_raw if p.get('in_stock', True)]
    products_sorted = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))

    try:
        product = products_sorted[index]
    except IndexError:
        return "Товар не найден или отсутствует в наличии.", 404

    return render_template_string(
        PRODUCT_DETAIL_TEMPLATE,
        product=product,
        repo_id=REPO_ID,
        currency_code=settings.get('currency_code', 'KGS'),
        settings=settings,
        env_id=env_id
    )

@app.route('/<env_id>/create_order', methods=['POST'])
def create_order(env_id):
    order_data = request.get_json()

    if not order_data or 'cart' not in order_data or not order_data['cart']:
        return jsonify({"error": "Корзина пуста или не передана."}), 400

    cart_items = order_data['cart']

    total_price = 0
    processed_cart = []
    for item in cart_items:
        if not all(k in item for k in ('name', 'price', 'quantity')):
            return jsonify({"error": "Неверный формат товара в корзине."}), 400
        try:
            price = float(item['price'])
            quantity = int(item['quantity'])
            if price < 0 or quantity <= 0:
                raise ValueError("Invalid price or quantity")
            processed_cart.append({
                "product_id": item.get('product_id', 'N/A'),
                "name": item['name'],
                "price": price,
                "quantity": quantity,
                "color": item.get('color', 'N/A'),
                "size": item.get('size', 'N/A'),
                "photo": item.get('photo'),
                "photo_url": f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/photos/{item['photo']}" if item.get('photo') else "https://via.placeholder.com/60x60.png?text=N/A"
            })
            total_price += price * quantity
        except (ValueError, TypeError) as e:
            return jsonify({"error": "Неверная цена или количество в товаре."}), 400

    order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid4().hex[:6]}"
    order_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    new_order = {
        "id": order_id,
        "created_at": order_timestamp,
        "cart": processed_cart,
        "total_price": round(total_price, 2),
        "user_info": None,
        "status": "new"
    }

    try:
        data = get_env_data(env_id)
        if 'orders' not in data or not isinstance(data.get('orders'), dict):
            data['orders'] = {}

        data['orders'][order_id] = new_order
        save_env_data(env_id, data)
        return jsonify({"order_id": order_id}), 201

    except Exception as e:
        return jsonify({"error": "Ошибка сервера при сохранении заказа."}), 500

@app.route('/<env_id>/order/<order_id>')
def view_order(env_id, order_id):
    data = get_env_data(env_id)
    order = data.get('orders', {}).get(order_id)
    settings = data.get('settings', {})
    
    return render_template_string(ORDER_TEMPLATE,
                                  order=order,
                                  repo_id=REPO_ID,
                                  currency_code=settings.get('currency_code', 'KGS'),
                                  whatsapp_number=settings.get('whatsapp_number', ''),
                                  settings=settings,
                                  env_id=env_id)


@app.route('/<env_id>/admin', methods=['GET', 'POST'])
def admin(env_id):
    data = get_env_data(env_id)
    products = data.get('products', [])
    categories = data.get('categories', [])
    organization_info = data.get('organization_info', {})
    chats = data.get('chats', {})
    settings = data.get('settings', {})

    if 'orders' not in data or not isinstance(data.get('orders'), dict):
            data['orders'] = {}
            
    if request.method == 'POST':
        action = request.form.get('action')

        try:
            if action == 'add_category':
                category_name = request.form.get('category_name', '').strip()
                if category_name and category_name not in categories:
                    categories.append(category_name)
                    data['categories'] = categories
                    save_env_data(env_id, data)
                    flash(f"Категория '{category_name}' успешно добавлена.", 'success')
                elif not category_name:
                     flash("Название категории не может быть пустым.", 'error')
                else:
                     flash(f"Категория '{category_name}' уже существует.", 'error')

            elif action == 'delete_category':
                category_to_delete = request.form.get('category_name')
                if category_to_delete and category_to_delete in categories:
                    categories.remove(category_to_delete)
                    updated_count = 0
                    for product in products:
                        if product.get('category') == category_to_delete:
                            product['category'] = 'Без категории'
                            updated_count += 1
                    data['categories'] = categories
                    data['products'] = products
                    save_env_data(env_id, data)
                    flash(f"Категория '{category_to_delete}' удалена. {updated_count} товаров обновлено.", 'success')
                else:
                    flash(f"Не удалось удалить категорию '{category_to_delete}'.", 'error')

            elif action == 'update_org_info':
                organization_info['about_us'] = request.form.get('about_us', '').strip()
                organization_info['shipping'] = request.form.get('shipping', '').strip()
                organization_info['returns'] = request.form.get('returns', '').strip()
                organization_info['contact'] = request.form.get('contact', '').strip()
                data['organization_info'] = organization_info
                save_env_data(env_id, data)
                flash("Информация о магазине успешно обновлена.", 'success')
            
            elif action == 'update_settings':
                settings['organization_name'] = request.form.get('organization_name', 'Gippo312').strip()
                settings['whatsapp_number'] = request.form.get('whatsapp_number', '').strip()
                settings['currency_code'] = request.form.get('currency_code', 'KGS')
                settings['business_type'] = request.form.get('business_type', 'combined')
                settings['chat_name'] = request.form.get('chat_name', 'EVA').strip()
                settings['color_scheme'] = request.form.get('color_scheme', 'default')

                avatar_file = request.files.get('chat_avatar')
                if avatar_file and avatar_file.filename:
                    if HF_TOKEN_WRITE:
                        try:
                            api = HfApi()
                            
                            old_avatar = settings.get('chat_avatar')
                            if old_avatar:
                                try:
                                    api.delete_files(repo_id=REPO_ID, paths_in_repo=[f"avatars/{old_avatar}"], repo_type="dataset", token=HF_TOKEN_WRITE)
                                except Exception:
                                    pass

                            ext = os.path.splitext(avatar_file.filename)[1].lower()
                            avatar_filename = f"avatar_{env_id}_{int(time.time())}{ext}"
                            
                            uploads_dir = 'uploads_temp'
                            os.makedirs(uploads_dir, exist_ok=True)
                            temp_path = os.path.join(uploads_dir, avatar_filename)
                            avatar_file.save(temp_path)

                            api.upload_file(
                                path_or_fileobj=temp_path,
                                path_in_repo=f"avatars/{avatar_filename}",
                                repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE
                            )
                            settings['chat_avatar'] = avatar_filename
                            os.remove(temp_path)
                            flash("Аватар чата успешно обновлен.", 'success')
                        except Exception as e:
                            flash(f"Ошибка при загрузке аватара: {e}", 'error')
                    else:
                        flash("HF_TOKEN (write) не настроен. Аватар не был загружен.", "warning")

                data['settings'] = settings
                save_env_data(env_id, data)
                flash("Настройки магазина и чата успешно обновлены.", 'success')

            elif action == 'add_product' or action == 'edit_product':
                product_id = request.form.get('product_id')
                product_data = {}
                is_edit = action == 'edit_product'
                
                if is_edit:
                    product_data = next((p for p in products if p.get('product_id') == product_id), None)
                    if not product_data:
                        flash(f"Ошибка: товар с ID {product_id} не найден.", 'error')
                        return redirect(url_for('admin', env_id=env_id))
                
                product_data['name'] = request.form.get('name', '').strip()
                price_str = request.form.get('price', '0').replace(',', '.')
                product_data['description'] = request.form.get('description', '').strip()
                category = request.form.get('category')
                product_data['category'] = category if category in categories else 'Без категории'
                product_data['colors'] = sorted(list(set(c.strip() for c in request.form.getlist('colors') if c.strip())))
                product_data['sizes'] = sorted(list(set(s.strip() for s in request.form.getlist('sizes') if s.strip())))
                product_data['in_stock'] = 'in_stock' in request.form
                product_data['is_top'] = 'is_top' in request.form

                w_price_str = request.form.get('wholesale_price', '').replace(',', '.')
                w_quant_str = request.form.get('min_wholesale_quantity', '')
                
                if settings.get('business_type') == 'wholesale':
                    if not w_price_str or not w_quant_str:
                        flash("Для оптового типа бизнеса, оптовая цена и минимальное количество обязательны.", 'error')
                        return redirect(url_for('admin', env_id=env_id))
                    product_data['price'] = 0
                
                product_data['wholesale_price'] = float(w_price_str) if w_price_str else None
                product_data['min_wholesale_quantity'] = int(w_quant_str) if w_quant_str else None

                if not product_data['name']:
                    flash("Название товара обязательно.", 'error')
                    return redirect(url_for('admin', env_id=env_id))
                
                try:
                    price = round(float(price_str), 2)
                    if price < 0: price = 0
                    product_data['price'] = price
                except ValueError:
                    flash("Неверный формат цены.", 'error')
                    return redirect(url_for('admin', env_id=env_id))

                variant_prices = {}
                for key, value in request.form.items():
                    if key.startswith('variant_price_') and value:
                        variant_key = key.replace('variant_price_', '')
                        try:
                            variant_prices[variant_key] = round(float(value), 2)
                        except ValueError:
                            pass
                product_data['variant_prices'] = variant_prices

                photos_files = request.files.getlist('photos')
                if photos_files and any(f.filename for f in photos_files):
                    if HF_TOKEN_WRITE:
                        uploads_dir = 'uploads_temp'
                        os.makedirs(uploads_dir, exist_ok=True)
                        api = HfApi()
                        new_photos_list = []
                        photo_limit = 10
                        uploaded_count = 0
                        for photo in photos_files:
                            if uploaded_count >= photo_limit:
                                flash(f"Загружено только первые {photo_limit} фото.", "warning")
                                break
                            if photo and photo.filename:
                                try:
                                    ext = os.path.splitext(photo.filename)[1].lower()
                                    if ext not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
                                        flash(f"Файл {photo.filename} пропущен (не изображение).", "warning")
                                        continue

                                    safe_name = secure_filename(product_data['name'].replace(' ', '_'))[:50]
                                    photo_filename = f"{safe_name}_{uuid4().hex[:8]}{ext}"
                                    temp_path = os.path.join(uploads_dir, photo_filename)
                                    photo.save(temp_path)
                                    api.upload_file(path_or_fileobj=temp_path, path_in_repo=f"photos/{photo_filename}", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
                                    new_photos_list.append(photo_filename)
                                    os.remove(temp_path)
                                    uploaded_count += 1
                                except Exception as e:
                                    flash(f"Ошибка при загрузке фото {photo.filename}: {e}", 'error')
                        if new_photos_list and is_edit and product_data.get('photos'):
                            try:
                                api.delete_files(repo_id=REPO_ID, paths_in_repo=[f"photos/{p}" for p in product_data['photos']], repo_type="dataset", token=HF_TOKEN_WRITE)
                            except Exception: pass
                        if new_photos_list:
                             product_data['photos'] = new_photos_list
                    else:
                        flash("HF_TOKEN (write) не настроен. Фотографии не были загружены.", "warning")
                
                if is_edit:
                    product_index = next((i for i, p in enumerate(products) if p.get('product_id') == product_id), -1)
                    if product_index != -1:
                        products[product_index] = product_data
                        flash(f"Товар '{product_data['name']}' успешно обновлен.", 'success')
                else:
                    product_data['product_id'] = uuid4().hex
                    products.append(product_data)
                    flash(f"Товар '{product_data['name']}' успешно добавлен.", 'success')
                
                data['products'] = products
                save_env_data(env_id, data)


            elif action == 'delete_product':
                product_id = request.form.get('product_id')
                product_index = next((i for i, p in enumerate(products) if p.get('product_id') == product_id), -1)

                if product_index == -1:
                    flash(f"Ошибка удаления: товар с ID '{product_id}' не найден.", 'error')
                    return redirect(url_for('admin', env_id=env_id))

                deleted_product = products.pop(product_index)
                product_name = deleted_product.get('name', 'N/A')

                photos_to_delete = deleted_product.get('photos', [])
                if photos_to_delete and HF_TOKEN_WRITE:
                    try:
                        api = HfApi()
                        api.delete_files(
                            repo_id=REPO_ID,
                            paths_in_repo=[f"photos/{p}" for p in photos_to_delete],
                            repo_type="dataset",
                            token=HF_TOKEN_WRITE,
                            commit_message=f"Delete photos for deleted product {product_name}"
                        )
                    except Exception as e:
                         flash(f"Не удалось удалить фото для товара '{product_name}' с сервера. Товар удален локально.", "warning")
                elif photos_to_delete and not HF_TOKEN_WRITE:
                    flash(f"Товар '{product_name}' удален локально, но фото не удалены с сервера (токен не задан).", "warning")

                data['products'] = products
                save_env_data(env_id, data)
                flash(f"Товар '{product_name}' удален.", 'success')

            else:
                 flash(f"Неизвестное действие: {action}", 'warning')

            return redirect(url_for('admin', env_id=env_id))

        except Exception as e:
             flash(f"Произошла внутренняя ошибка при выполнении действия '{action}'. Подробности в логе сервера.", 'error')
             return redirect(url_for('admin', env_id=env_id))

    display_products = sorted(data.get('products', []), key=lambda p: p.get('name', '').lower())
    display_categories = sorted(data.get('categories', []))
    display_organization_info = data.get('organization_info', {})
    display_chats = data.get('chats', {})
    display_settings = data.get('settings', {})

    chat_status = { "active": False, "expires_soon": False, "expires_date": "N/A" }
    if display_settings.get('chat_activated'):
        expires_str = display_settings.get('chat_activation_expires')
        if expires_str:
            try:
                expires_dt = datetime.fromisoformat(expires_str)
                now_almaty = datetime.now(ALMATY_TZ)
                if expires_dt > now_almaty:
                    chat_status["active"] = True
                    chat_status["expires_date"] = expires_dt.strftime('%Y-%m-%d %H:%M:%S')
                    if (expires_dt - now_almaty).days <= 4:
                        chat_status["expires_soon"] = True
                else:
                    chat_status["expires_date"] = expires_dt.strftime('%Y-%m-%d %H:%M:%S')
            except (ValueError, TypeError):
                pass
                
    chat_avatar_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/avatars/{display_settings['chat_avatar']}" if display_settings.get('chat_avatar') else "https://huggingface.co/spaces/gippo312/admin/resolve/main/Picsart_25-11-04_12-02-21-390.png"

    return render_template_string(
        ADMIN_TEMPLATE,
        products=display_products,
        categories=display_categories,
        organization_info=display_organization_info,
        chats=display_chats,
        settings=display_settings,
        repo_id=REPO_ID,
        currency_code=display_settings.get('currency_code', 'KGS'),
        chat_avatar_url=chat_avatar_url,
        currencies=CURRENCIES,
        color_schemes=COLOR_SCHEMES,
        env_id=env_id,
        chat_status=chat_status,
        whatsapp_is_active=whatsapp_active.is_set(),
        whatsapp_env_id=whatsapp_env_id
    )

@app.route('/generate_description_ai', methods=['POST'])
def handle_generate_description_ai():
    request_data = request.get_json()
    base64_image = request_data.get('image')
    language = request_data.get('language', 'Русский')

    if not base64_image:
        return jsonify({"error": "Изображение не найдено в запросе."}), 400

    try:
        image_data = base64.b64decode(base64_image)
        result_text = generate_ai_description_from_image(image_data, language)
        return jsonify({"text": result_text})
    except ValueError as ve:
        return jsonify({"error": str(ve)}), 400
    except Exception as e:
        return jsonify({"error": f"Внутренняя ошибка сервера: {e}"}), 500

@app.route('/<env_id>/chat_with_ai', methods=['POST'])
def handle_chat_with_ai(env_id):
    if not is_chat_active(env_id):
        return jsonify({"error": "Чат неактивен."}), 403

    request_data = request.get_json()
    user_message = request_data.get('message')
    chat_history_from_client = request_data.get('history', [])
    chat_id = request_data.get('chat_id')

    if not user_message:
        return jsonify({"error": "Сообщение не может быть пустым."}), 400
    if not chat_id:
        return jsonify({"error": "ID чата не предоставлен."}), 400

    try:
        ai_response_text = generate_chat_response(user_message, chat_history_from_client, env_id)
        
        data = get_env_data(env_id)
        if 'chats' not in data:
            data['chats'] = {}
        if chat_id not in data['chats']:
            data['chats'][chat_id] = []
        
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        data['chats'][chat_id].append({'role': 'user', 'text': user_message, 'timestamp': timestamp})
        data['chats'][chat_id].append({'role': 'ai', 'text': ai_response_text, 'timestamp': timestamp})
        save_env_data(env_id, data)
        
        return jsonify({"text": ai_response_text})
    except Exception as e:
        return jsonify({"error": f"Ошибка чата: {e}"}), 500

@app.route('/<env_id>/chat')
def chat_page(env_id):
    if not is_chat_active(env_id):
        return "Чат для этой среды неактивен. Обратитесь к администратору.", 403
        
    data = get_env_data(env_id)
    all_products_raw = data.get('products', [])
    settings = data.get('settings', {})
    products_in_stock = [p for p in all_products_raw if p.get('in_stock', True)]
    products_sorted_for_js = sorted(products_in_stock, key=lambda p: (not p.get('is_top', False), p.get('name', '').lower()))

    chat_avatar_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/avatars/{settings['chat_avatar']}" if settings.get('chat_avatar') else "https://huggingface.co/spaces/gippo312/admin/resolve/main/Picsart_25-11-04_12-02-21-390.png"

    return render_template_string(
        CHAT_TEMPLATE,
        products_json=json.dumps(products_sorted_for_js),
        repo_id=REPO_ID,
        currency_code=settings.get('currency_code', 'KGS'),
        settings=settings,
        chat_avatar_url=chat_avatar_url,
        env_id=env_id
    )

@app.route('/<env_id>/get_chat/<chat_id>')
def get_chat_history(env_id, chat_id):
    data = get_env_data(env_id)
    chat_history = data.get('chats', {}).get(chat_id)
    if chat_history:
        return jsonify(chat_history)
    else:
        return jsonify({"error": "Chat not found"}), 404
        
@app.route('/<env_id>/force_upload', methods=['POST'])
def force_upload(env_id):
    try:
        upload_db_to_hf()
        flash("Данные успешно загружены на Hugging Face.", 'success')
    except Exception as e:
        flash(f"Ошибка при загрузке на Hugging Face: {e}", 'error')
    return redirect(url_for('admin', env_id=env_id))

@app.route('/<env_id>/force_download', methods=['POST'])
def force_download(env_id):
    try:
        if download_db_from_hf():
            flash("Данные успешно скачаны с Hugging Face. Локальные файлы обновлены.", 'success')
        else:
            flash("Не удалось скачать данные с Hugging Face после нескольких попыток. Проверьте логи.", 'error')
    except Exception as e:
        flash(f"Ошибка при скачивании с Hugging Face: {e}", 'error')
    return redirect(url_for('admin', env_id=env_id))

@app.route('/<env_id>/whatsapp/start')
def start_whatsapp_bot(env_id):
    global whatsapp_thread
    if whatsapp_thread and whatsapp_thread.is_alive():
        flash('WhatsApp бот уже запущен.', 'warning')
    else:
        whatsapp_thread = threading.Thread(target=whatsapp_bot_thread, args=(env_id,), daemon=True)
        whatsapp_thread.start()
        flash('Запуск WhatsApp бота... Пожалуйста, будьте готовы отсканировать QR-код в новом окне браузера.', 'success')
    return redirect(url_for('admin', env_id=env_id))

@app.route('/<env_id>/whatsapp/stop')
def stop_whatsapp_bot(env_id):
    global driver, whatsapp_thread
    if not (whatsapp_thread and whatsapp_thread.is_alive()):
        flash('WhatsApp бот не был запущен.', 'warning')
    else:
        whatsapp_active.clear()
        if driver:
            try:
                driver.quit()
            except:
                pass
        flash('WhatsApp бот остановлен.', 'success')
    return redirect(url_for('admin', env_id=env_id))


if __name__ == '__main__':
    configure_gemini()
    download_db_from_hf()
    load_data()

    if HF_TOKEN_WRITE:
        backup_thread = threading.Thread(target=periodic_backup, daemon=True)
        backup_thread.start()
    else:
        pass

    port = int(os.environ.get('PORT', 7860))
    app.run(debug=False, host='0.0.0.0', port=port)