File size: 27,081 Bytes
55db208
359498b
 
d3e00bc
359498b
55db208
 
 
359498b
55db208
359498b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55db208
359498b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55db208
359498b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3e00bc
27a053f
f8d1e08
 
55db208
 
 
 
27a053f
55db208
 
359498b
55db208
d3e00bc
27a053f
55db208
 
27a053f
359498b
 
 
 
 
 
27a053f
359498b
27a053f
 
 
55db208
 
e06abaf
55db208
d3e00bc
55db208
359498b
 
 
 
 
 
 
 
 
 
 
 
 
 
27a053f
359498b
 
 
27a053f
359498b
 
27a053f
359498b
 
 
27a053f
359498b
 
 
 
 
 
27a053f
359498b
 
27a053f
359498b
 
 
 
 
de03262
359498b
 
27a053f
 
359498b
 
de03262
359498b
 
27a053f
55db208
359498b
 
27a053f
55db208
359498b
27a053f
55db208
 
359498b
 
 
 
 
27a053f
55db208
359498b
55db208
359498b
55db208
 
359498b
27a053f
359498b
 
 
 
 
 
 
27a053f
359498b
 
27a053f
359498b
 
 
55db208
27a053f
359498b
 
27a053f
359498b
55db208
359498b
 
 
55db208
359498b
 
55db208
27a053f
359498b
 
 
 
 
 
27a053f
55db208
 
27a053f
55db208
 
359498b
 
55db208
359498b
 
27a053f
55db208
 
27a053f
55db208
359498b
 
 
27a053f
359498b
 
27a053f
7f3a24b
359498b
 
aafa1c0
359498b
27a053f
359498b
 
 
 
 
27a053f
359498b
 
 
 
 
 
27a053f
aafa1c0
 
359498b
 
aafa1c0
7f3a24b
359498b
27a053f
aafa1c0
359498b
27a053f
7f3a24b
359498b
 
 
27a053f
 
359498b
27a053f
 
f8d1e08
55db208
 
 
27a053f
7f3a24b
d3791e9
 
aafa1c0
d3791e9
55db208
d3791e9
55db208
 
359498b
55db208
 
 
 
 
d3e00bc
 
 
55db208
 
d3e00bc
 
55db208
 
 
359498b
55db208
 
 
 
 
 
 
359498b
 
55db208
 
 
 
359498b
 
 
27a053f
 
359498b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27a053f
359498b
 
 
 
 
 
 
27a053f
359498b
 
 
 
 
 
 
55db208
 
 
359498b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55db208
 
 
 
 
 
 
 
 
359498b
 
 
55db208
 
 
 
359498b
 
 
27a053f
 
359498b
 
 
 
 
 
 
 
 
 
 
 
27a053f
359498b
 
 
 
 
 
 
27a053f
359498b
 
 
 
 
 
 
55db208
 
 
 
d3791e9
 
 
 
1d6508e
359498b
d3e00bc
1d6508e
d3791e9
359498b
d3e00bc
1d6508e
d3791e9
1d6508e
359498b
d3e00bc
 
359498b
 
 
 
 
d3e00bc
 
 
 
 
 
359498b
 
 
1d6508e
d3e00bc
d3791e9
d3e00bc
d3791e9
d3e00bc
1d6508e
 
 
55db208
 
359498b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d6508e
 
359498b
7f3a24b
 
 
1d6508e
 
7f3a24b
 
d3e00bc
 
 
 
 
 
359498b
 
 
7f3a24b
 
f8d1e08
359498b
 
 
 
 
 
 
 
 
 
7f3a24b
 
 
359498b
 
 
 
 
 
 
 
 
 
 
 
 
 
27a053f
359498b
 
 
 
 
 
 
27a053f
359498b
 
 
 
 
7f3a24b
 
1d6508e
7f3a24b
359498b
1d6508e
55db208
7f3a24b
d3e00bc
359498b
 
 
 
 
 
 
 
 
 
 
 
d3e00bc
359498b
d3e00bc
 
359498b
 
 
d3e00bc
 
 
 
55db208
 
 
 
 
7f3a24b
55db208
 
359498b
55db208
 
7f3a24b
 
359498b
55db208
359498b
 
 
 
 
55db208
7f3a24b
55db208
 
1d6508e
55db208
 
 
359498b
55db208
359498b
7f3a24b
359498b
 
55db208
 
 
 
 
359498b
55db208
359498b
 
 
 
55db208
 
7f3a24b
 
359498b
7f3a24b
 
55db208
7f3a24b
55db208
359498b
 
 
 
 
 
 
 
55db208
 
27a053f
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
from flask import Flask, render_template_string, jsonify, request
import json
import os
import math
from datetime import datetime, timedelta

app = Flask(__name__)

# Инициализация файла JSON (если файла нет – создаётся пустой список)
def init_db():
    if not os.path.exists('markers.json'):
        with open('markers.json', 'w', encoding='utf-8') as f:
            json.dump([], f, ensure_ascii=False, indent=4)

# Загрузка меток из файла JSON
def load_markers():
    with open('markers.json', 'r', encoding='utf-8') as f:
        return json.load(f)

# Сохранение меток в файл JSON
def save_markers(markers):
    with open('markers.json', 'w', encoding='utf-8') as f:
        json.dump(markers, f, ensure_ascii=False, indent=4)

# Получение всех меток
def get_all_markers():
    return load_markers()

# Добавление новой метки в "базу" (JSON-файл)
def add_marker_to_db(name, description, telegram_link, logo_link, latitude, longitude, delete_password):
    markers = load_markers()
    new_id = max((marker["id"] for marker in markers), default=0) + 1
    new_marker = {
        "id": new_id,
        "name": name,
        "description": description,
        "telegram_link": telegram_link,
        "logo_link": logo_link,
        "latitude": latitude,
        "longitude": longitude,
        "delete_password": delete_password,
        "premium": 0,
        "premium_start_date": None
    }
    markers.append(new_marker)
    save_markers(markers)
    return new_id

# Удаление метки из JSON-файла
def remove_marker_from_db(marker_id):
    markers = load_markers()
    markers = [marker for marker in markers if marker["id"] != marker_id]
    save_markers(markers)

# Активация премиум-статуса для метки
def activate_premium(marker_id):
    markers = load_markers()
    current_date = datetime.now().isoformat()
    for marker in markers:
        if marker["id"] == marker_id:
            marker["premium"] = 1
            marker["premium_start_date"] = current_date
            break
    save_markers(markers)

# Проверка и сброс премиум-статуса по истечении 30 дней
def check_premium_status():
    markers = load_markers()
    updated = False
    for marker in markers:
        if marker["premium"] == 1 and marker["premium_start_date"]:
            premium_start_date = datetime.fromisoformat(marker["premium_start_date"])
            current_date = datetime.now()
            if (current_date - premium_start_date).days > 30:
                marker["premium"] = 0
                marker["premium_start_date"] = None
                updated = True
    if updated:
        save_markers(markers)

# HTML-шаблон с футуристическим дизайном
html_template = '''
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GeoGram 2070</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css">
    <style>
        /* Общие стили */
        body {
            font-family: 'Roboto', sans-serif;
            background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
            margin: 0;
            padding: 0;
            color: #fff;
            overflow-x: hidden;
        }
        h1 {
            text-align: center;
            padding: 20px;
            margin: 0;
            background: linear-gradient(135deg, #ff00cc, #333399);
            color: white;
            font-size: 32px;
            letter-spacing: 4px;
            text-shadow: 0 0 10px rgba(255, 0, 204, 0.8), 0 0 20px rgba(255, 0, 204, 0.8);
        }
        #map {
            height: 90vh;
            width: 100%;
            margin-bottom: 20px;
        }

        /* Поиск */
        #search-container {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 20px;
        }
        #search-input {
            padding: 15px;
            width: 300px;
            border: none;
            border-radius: 30px 0 0 30px;
            font-size: 16px;
            background: #24243e;
            color: #fff;
            outline: none;
            transition: background 0.3s ease;
            box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);
        }
        #search-input:focus {
            background: #302b63;
        }
        #search-button {
            padding: 15px 30px;
            background: linear-gradient(135deg, #ff00cc, #333399);
            color: white;
            border: none;
            border-radius: 0 30px 30px 0;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.3s ease;
            box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);
        }
        #search-button:hover {
            background: linear-gradient(135deg, #333399, #ff00cc);
        }

        /* Результаты поиска */
        #search-results {
            margin: 20px;
            text-align: center;
        }
        .result-item {
            background: linear-gradient(135deg, #24243e, #302b63);
            border: 1px solid rgba(255, 0, 204, 0.5);
            border-radius: 15px;
            margin: 10px auto;
            padding: 20px;
            max-width: 500px;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);
        }
        .result-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 0 20px rgba(255, 0, 204, 0.8);
        }
        .result-item b {
            color: #ff00cc;
            font-size: 18px;
        }
        .result-item p {
            color: #ecf0f1;
            margin: 5px 0;
        }
        .result-item a {
            color: #ff00cc;
            text-decoration: none;
            font-weight: bold;
        }
        .result-item a:hover {
            text-decoration: underline;
        }
        .result-item button {
            background: linear-gradient(135deg, #ff00cc, #333399);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 30px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s ease;
            box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);
        }
        .result-item button:hover {
            background: linear-gradient(135deg, #333399, #ff00cc);
        }

        /* Окно добавления метки */
        .popup-form {
            background: linear-gradient(135deg, #24243e, #302b63);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);
            width: 300px;
        }
        .popup-form input,
        .popup-form textarea {
            padding: 12px;
            margin-bottom: 10px;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            background: #302b63;
            color: #fff;
            outline: none;
            transition: background 0.3s ease;
        }
        .popup-form input:focus,
        .popup-form textarea:focus {
            background: #ff00cc;
        }
        .popup-form button {
            background: linear-gradient(135deg, #ff00cc, #333399);
            color: white;
            border: none;
            padding: 12px;
            border-radius: 30px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s ease;
            box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);
        }
        .popup-form button:hover {
            background: linear-gradient(135deg, #333399, #ff00cc);
        }

        /* Попапы на карте */
        .leaflet-popup-content-wrapper {
            background: linear-gradient(135deg, #24243e, #302b63);
            border-radius: 15px;
            padding: 15px;
            box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);
        }
        .leaflet-popup-content {
            color: #fff;
        }
        .leaflet-popup-content b {
            color: #ff00cc;
            font-size: 18px;
            display: block;
            margin-bottom: 5px;
        }
        .leaflet-popup-content a {
            color: #ff00cc;
            text-decoration: none;
        }
        .leaflet-popup-content a:hover {
            text-decoration: underline;
        }
        .leaflet-popup-content button {
            background: linear-gradient(135deg, #ff00cc, #333399);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 30px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s ease;
            box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);
        }
        .leaflet-popup-content button:hover {
            background: linear-gradient(135deg, #333399, #ff00cc);
        }

        /* Маркеры */
        .marker-logo {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            border: 2px solid #ff00cc;
            box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);
        }
    </style>
</head>
<body>
    <h1>GeoGram 2070</h1>
    <div id="search-container">
        <input type="text" id="search-input" placeholder="Поиск по названию или описанию" />
        <button id="search-button">Поиск</button>
    </div>
    <div id="search-results"></div>
    <div id="map"></div>

    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <script>
        const map = L.map('map').setView([55.75, 37.61], 13);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
        }).addTo(map);

        let userLatitude = 55.75;
        let userLongitude = 37.61;

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                userLatitude = position.coords.latitude;
                userLongitude = position.coords.longitude;
                map.setView([userLatitude, userLongitude], 13);

                L.marker([userLatitude, userLongitude]).addTo(map)
                    .bindPopup('<span style="color:white;">Вы находитесь здесь</span>').openPopup();
            }, function() {
                alert('Не удалось получить ваше местоположение.');
            });
        } else {
            alert('Ваш браузер не поддерживает геолокацию.');
        }

        let markersOnMap = {};

        fetch('/get_markers')
            .then(response => response.json())
            .then(data => {
                data.forEach(marker => {
                    const customIcon = L.divIcon({
                        className: 'custom-icon',
                        html: `<img src="${marker.logo_link || 'https://simpleicon.com/wp-content/uploads/map-marker-1.png'}" class="marker-logo"/>`,
                        iconSize: [30, 30],
                        iconAnchor: [15, 30]
                    });

                    const markerObj = L.marker([marker.latitude, marker.longitude], {icon: customIcon}).addTo(map);
                    markersOnMap[marker.id] = markerObj;

                    let premiumLabel = '';
                    if (marker.premium) {
                        const premiumStartDate = new Date(marker.premium_start_date);
                        const currentDate = new Date();
                        const daysLeft = Math.max(0, Math.floor((premiumStartDate.getTime() + (30 * 24 * 60 * 60 * 1000) - currentDate.getTime()) / (1000 * 60 * 60 * 24)));
                        premiumLabel = `<span style="color: gold;">Премиум метка (${daysLeft} дней осталось)</span><br>`;
                    }

                    markerObj.bindPopup(`
                        <div class="leaflet-popup-content">
                            ${premiumLabel}
                            <b>${marker.name}</b>
                            <p>${marker.description}</p>
                            <button style="background: linear-gradient(135deg, #ff00cc, #333399);
                                            color: white;
                                            border: none;
                                            padding: 10px 20px;
                                            border-radius: 30px;
                                            cursor: pointer;
                                            font-size: 14px;
                                            transition: background 0.3s ease;
                                            box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);" 
                                    onclick="window.open('https://t.me/${marker.telegram_link}', '_blank')">
                                Перейти в Telegram
                            </button><br>
                            <button onclick="buyPremium(${marker.id})">Купить премиум</button>
                            <button onclick="removeMarker(${marker.id}, '${marker.delete_password}')">Удалить</button>
                        </div>
                    `);
                });
            });

        function buyPremium(markerId) {
            const activationCode = prompt("Введите код активации премиума:");
            
            if (activationCode === "morshenadmin87132") {
                fetch('/activate_premium', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({id: markerId})
                }).then(() => {
                    alert("Премиум активирован!");
                    location.reload();
                });
            } else {
                alert("Неверный код активации!");
            }
        }

        function addMarker(name, description, telegram_link, logo_link, position) {
            const deletePassword = prompt("Введите пароль для удаления метки:");
            
            const finalLogoLink = logo_link || 'https://icons.veryicon.com/png/o/miscellaneous/high-icon-library/geo-fence.png';

            fetch('/add_marker', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    name: name,
                    description: description,
                    telegram_link: telegram_link,
                    logo_link: finalLogoLink,
                    position: [position.lat, position.lng],
                    delete_password: deletePassword
                })
            })
            .then(response => response.json())
            .then(data => {
                const customIcon = L.divIcon({
                    className: 'custom-icon',
                    html: `<img src="${data.logo_link}" class="marker-logo"/>`,
                    iconSize: [30, 30],
                    iconAnchor: [15, 30]
                });

                const markerObj = L.marker([data.latitude, data.longitude], {icon: customIcon}).addTo(map);
                markersOnMap[data.id] = markerObj;

                let premiumLabel = data.premium ? '<span style="color: gold;">Премиум метка</span><br>' : '';

                markerObj.bindPopup(`
                    <div class="leaflet-popup-content">
                        ${premiumLabel}
                        <b>${data.name}</b>
                        <p>${data.description}</p>
                        <button style="background: linear-gradient(135deg, #ff00cc, #333399);
                                        color: white;
                                        border: none;
                                        padding: 10px 20px;
                                        border-radius: 30px;
                                        cursor: pointer;
                                        font-size: 14px;
                                        transition: background 0.3s ease;
                                        box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);" 
                                onclick="window.open('https://t.me/${data.telegram_link}', '_blank')">
                            Перейти в Telegram
                        </button><br>
                        <button onclick="buyPremium(${data.id})">Купить премиум</button>
                        <button onclick="removeMarker(${data.id}, '${data.delete_password}')">Удалить</button>
                    </div>
                `);
            });
        }

        map.on('click', function(e) {
            const popupContent = document.createElement('div');
            popupContent.classList.add('popup-form');

            const inputName = document.createElement('input');
            inputName.type = 'text';
            inputName.placeholder = 'Название ';
            popupContent.appendChild(inputName);

            const inputDescription = document.createElement('textarea');
            inputDescription.placeholder = 'Ваши товары/услуги';
            popupContent.appendChild(inputDescription);

            const inputTelegram = document.createElement('input');
            inputTelegram.type = 'text';
            inputTelegram.placeholder = 'Telegram канал (без @)';
            popupContent.appendChild(inputTelegram);

            const inputLogoLink = document.createElement('input');
            inputLogoLink.type = 'text';
            inputLogoLink.placeholder = 'Ссылка на логотип (необязательно)';
            popupContent.appendChild(inputLogoLink);

            const submitButton = document.createElement('button');
            submitButton.textContent = 'Добавить метку';
            submitButton.onclick = function() {
                const name = inputName.value;
                const description = inputDescription.value;
                const telegram_link = inputTelegram.value;
                const logo_link = inputLogoLink.value;
                if(name && description && telegram_link) {
                    addMarker(name, description, telegram_link, logo_link, e.latlng);
                }
                map.closePopup();
            };
            popupContent.appendChild(submitButton);

            L.popup()
                .setLatLng(e.latlng)
                .setContent(popupContent)
                .openOn(map);
        });

        function removeMarker(markerId, markerPassword) {
            const universalPassword = "morshenadmin87132";
            const passwordInput = prompt("Введите пароль для удаления метки:");

            if (passwordInput === universalPassword || passwordInput === markerPassword) {
                fetch('/remove_marker', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({id: markerId})
                }).then(() => {
                    location.reload();
                });
            } else {
                alert("Неверный пароль!");
            }
        }

        // Обновленная функция поиска с приоритетом премиум меток
        document.getElementById('search-button').addEventListener('click', function() {
            const searchTerm = document.getElementById('search-input').value.toLowerCase();
            fetch('/get_markers')
                .then(response => response.json())
                .then(data => {
                    const resultsContainer = document.getElementById('search-results');
                    resultsContainer.innerHTML = '';

                    // Вычисление расстояния до каждого маркера
                    data.forEach(marker => {
                        marker.distance = calculateDistance(userLatitude, userLongitude, marker.latitude, marker.longitude);
                    });

                    // Фильтрация результатов по поисковому запросу
                    const results = data.filter(marker =>
                        marker.name.toLowerCase().includes(searchTerm) ||
                        marker.description.toLowerCase().includes(searchTerm)
                    );

                    // Сортировка результатов: сначала премиум метки, затем обычные,
                    // и внутри каждой категории сортировка по расстоянию
                    results.sort((a, b) => {
                        if (a.premium !== b.premium) {
                            return b.premium - a.premium; // Премиум метки идут первыми
                        }
                        return a.distance - b.distance; // Сортировка по расстоянию
                    });

                    // Отображение результатов
                    results.forEach(marker => {
                        const resultItem = document.createElement('div');
                        resultItem.classList.add('result-item');
                        
                        let premiumLabel = '';
                        if (marker.premium) {
                            const premiumStartDate = new Date(marker.premium_start_date);
                            const currentDate = new Date();
                            const daysLeft = Math.max(0, Math.floor((premiumStartDate.getTime() + (30 * 24 * 60 * 60 * 1000) - currentDate.getTime()) / (1000 * 60 * 60 * 24)));
                            premiumLabel = ` (${daysLeft} дней осталось)`;
                        }

                        resultItem.innerHTML = `
                            <b>${marker.name}</b>
                            <p>${marker.description}</p>
                            <p>Расстояние: ${marker.distance.toFixed(2)} км</p>
                            <p>Статус: ${marker.premium ? 'Премиум' + premiumLabel : 'Обычная'}</p>
                            <button style="background: linear-gradient(135deg, #ff00cc, #333399);
                                            color: white;
                                            border: none;
                                            padding: 10px 20px;
                                            border-radius: 30px;
                                            cursor: pointer;
                                            font-size: 14px;
                                            transition: background 0.3s ease;
                                            box-shadow: 0 0 10px rgba(255, 0, 204, 0.8);" 
                                    onclick="window.open('https://t.me/${marker.telegram_link}', '_blank')">
                                Перейти в Telegram
                            </button>
                            <button onclick="showOnMap(${marker.id}, ${marker.latitude}, ${marker.longitude}); hideResults()">Показать на карте</button>`;
                        
                        resultsContainer.appendChild(resultItem);
                    });

                    if (results.length === 0) {
                        resultsContainer.innerHTML = '<p style="color:white;">Нет результатов</p>';
                    }
                });
        });

        function showOnMap(markerId, lat, lng) {
            map.setView([lat, lng], 13);
            if (markersOnMap[markerId]) {
                markersOnMap[markerId].openPopup();
            }
        }

        function hideResults() {
            const resultsContainer = document.getElementById('search-results');
            resultsContainer.innerHTML = '';
        }

        function calculateDistance(lat1, lon1, lat2, lon2) {
            const R = 6371;
            const dLat = (lat2 - lat1) * Math.PI / 180;
            const dLon = (lon2 - lon1) * Math.PI / 180;
            const a =
                0.5 - Math.cos(dLat) / 2 +
                Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                (1 - Math.cos(dLon)) / 2;

            return R * 2 * Math.asin(Math.sqrt(a));
        }
    </script>
</body>
</html>
'''

# Маршрут для главной страницы
@app.route('/')
def index():
    check_premium_status()
    return render_template_string(html_template)

# Маршрут для получения всех меток
@app.route('/get_markers')
def get_markers_route():
    markers = get_all_markers()
    # Если для метки не указан логотип, используем изображение по умолчанию
    for marker in markers:
        if not marker.get("logo_link"):
            marker["logo_link"] = "https://simpleicon.com/wp-content/uploads/map-marker-1.png"
    return jsonify(markers)

# Маршрут для добавления метки
@app.route('/add_marker', methods=['POST'])
def add_marker():
    data = request.json
    name = data['name']
    description = data['description']
    telegram_link = data['telegram_link']
    logo_link = data['logo_link'] if data['logo_link'] else 'https://simpleicon.com/wp-content/uploads/map-marker-1.png'
    latitude, longitude = data['position']
    delete_password = data['delete_password']

    marker_id = add_marker_to_db(name, description, telegram_link, logo_link, latitude, longitude, delete_password)
    
    return jsonify({
        'id': marker_id,
        'name': name,
        'description': description,
        'telegram_link': telegram_link,
        'logo_link': logo_link,
        'latitude': latitude,
        'longitude': longitude,
        'delete_password': delete_password,
        'premium': 0,
        'premium_start_date': None
    })

# Маршрут для удаления метки
@app.route('/remove_marker', methods=['POST'])
def remove_marker_route():
    data = request.json
    marker_id = data['id']
    remove_marker_from_db(marker_id)
    return jsonify({'success': True})

# Маршрут для активации премиум-статуса
@app.route('/activate_premium', methods=['POST'])
def activate_premium_route():
    data = request.json
    marker_id = data['id']
    activate_premium(marker_id)
    return jsonify({'success': True})

if __name__ == '__main__':
    init_db()
    app.run(debug=True, host='0.0.0.0', port=7860)