-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard_builder.php
More file actions
3420 lines (3070 loc) · 159 KB
/
dashboard_builder.php
File metadata and controls
3420 lines (3070 loc) · 159 KB
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
<?php
// Start output buffering to prevent header issues
ob_start();
// Include required files
require_once 'incl/const.php';
require_once 'incl/Database.php';
require_once 'incl/Auth.php';
require_once 'incl/Config.php';
// Require authentication
requireAuth();
// Get dashboard ID if editing
$dashboardId = isset($_GET['id']) ? intval($_GET['id']) : 0;
$dashboard = null;
$dashboardConfig = null;
if ($dashboardId > 0) {
// Editing existing dashboard - check permission
try {
$dashboard = getDashboardById($dashboardId);
if ($dashboard) {
if (!canEdit('dashboard', $dashboardId)) {
// User doesn't have permission to edit this dashboard
ob_end_clean();
header('Location: index.php?error=access_denied');
exit;
}
$dashboardConfig = json_decode($dashboard['config'], true);
}
} catch (Exception $e) {
$error = "Failed to load dashboard.";
}
} else {
// Creating new dashboard - only admins can create
if (!isAdmin()) {
ob_end_clean();
header('Location: index.php?error=access_denied');
exit;
}
}
// Get available layers from GeoServer
$availableLayers = getAvailableLayers();
$geoServerConfig = getGeoServerConfig();
// Handle save request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
if ($_POST['action'] === 'save') {
$title = isset($_POST['title']) ? trim($_POST['title']) : 'Untitled Dashboard';
$description = isset($_POST['description']) ? trim($_POST['description']) : '';
$categoryId = isset($_POST['category_id']) && $_POST['category_id'] !== '' ? intval($_POST['category_id']) : null;
$config = isset($_POST['config']) ? json_decode($_POST['config'], true) : [];
try {
if ($dashboardId > 0) {
// Update existing dashboard
updateDashboard($dashboardId, $title, $description, $config, $categoryId);
ob_end_clean();
header('Location: index.php?saved=dashboard');
exit;
} else {
// Create new dashboard
$newId = saveDashboard($title, $description, $config, $categoryId);
ob_end_clean();
header('Location: index.php?saved=dashboard');
exit;
}
} catch (Exception $e) {
error_log("Error saving dashboard: " . $e->getMessage());
$error = "Failed to save dashboard. Please check database configuration.";
}
}
}
// Flush output buffer
ob_end_flush();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $dashboardId > 0 ? 'Edit' : 'Create'; ?> Dashboard - GeoLite</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<!-- Quill Editor -->
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<style>
:root {
--bg: #f6f7fb;
--panel: #fff;
--muted: #6b7280;
--text: #1f2937;
--accent: #667eea;
--shadow: 0 10px 24px rgba(0,0,0,.08);
--radius: 14px;
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
background: var(--bg);
color: var(--text);
font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial;
}
.topbar {
height: 56px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 16px;
background: #fff;
box-shadow: var(--shadow);
position: sticky;
top: 0;
z-index: 10;
}
.btn {
border: 1px solid #e5e7eb;
border-radius: 10px;
padding: 8px 12px;
background: #fff;
cursor: pointer;
}
.btn-primary {
background: var(--accent);
color: #fff;
border-color: var(--accent);
}
.wrap {
display: grid;
grid-template-columns: 320px 1fr;
gap: 16px;
padding: 16px;
height: calc(100vh - 200px);
transition: grid-template-columns 0.3s ease;
}
.wrap.sidebar-collapsed {
grid-template-columns: 0px 1fr;
}
.sidebar {
background: #fff;
border-radius: 14px;
box-shadow: var(--shadow);
padding: 16px;
height: 100%;
overflow: auto;
position: relative;
transition: all 0.3s ease;
}
.wrap.sidebar-collapsed .sidebar {
margin-left: -320px;
opacity: 0;
pointer-events: none;
}
.sidebar-toggle {
position: absolute;
left: 16px;
top: 80px;
z-index: 100;
background: #fff;
border: 1px solid #e5e7eb;
border-radius: 10px;
padding: 8px 12px;
cursor: pointer;
box-shadow: var(--shadow);
transition: all 0.3s ease;
}
.sidebar-toggle:hover {
background: #f9fafb;
border-color: var(--accent);
}
.sidebar-collapsed .sidebar-toggle {
left: 16px;
}
.picker {
padding: 12px;
border: 1px dashed #e5e7eb;
border-radius: 12px;
background: #fafafa;
cursor: pointer;
margin-bottom: 10px;
transition: all 0.2s;
}
.picker:hover {
background: #f3f4f6;
border-color: var(--accent);
}
.canvas {
position: relative;
height: 100%;
border-radius: 12px;
background: white;
box-shadow: var(--shadow);
overflow: auto;
}
.item {
position: absolute;
background: #fff;
border-radius: 0px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
overflow: hidden;
border-top: 2px solid #d97706;
}
.item[data-kind="map"] {
overflow: visible;
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 8px;
border-bottom: 1px solid #eef0f4;
cursor: move;
background: #f9fafb;
}
.title {
font-weight: 600;
padding: 2px 4px;
border-radius: 4px;
transition: background 0.2s;
font-size: 12px;
border: 1px solid transparent;
outline: none;
}
.title:hover {
background: #f3f4f6;
}
.title:focus {
background: #fff;
border-color: var(--accent);
}
.tools {
display: flex;
gap: 4px;
align-items: center;
}
.tbtn {
border: none;
background: #f3f4f6;
width: 30px;
height: 30px;
border-radius: 8px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
color: #6b7280;
transition: all 0.2s;
}
.tbtn:hover {
background: #e5e7eb;
color: #374151;
}
.tbtn.maximize {
position: relative;
}
.tbtn.maximize::before {
content: '⛶';
font-size: 16px;
}
.tbtn.maximize.maximized::before {
content: '⛷';
font-size: 16px;
}
.item.maximized {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 1000;
border-radius: 0;
}
.item.maximized .card-header {
background: #fff;
border-bottom: 1px solid #eef0f4;
}
.body {
height: calc(100% - 40px);
overflow: auto;
}
.item[data-kind="map"] .body {
overflow: visible;
}
.item[data-kind="map"] .pad { padding: 0; height: 100%; }
.item[data-kind="text"] .pad {
display: flex;
flex-direction: column;
height: 100%;
}
.item[data-kind="text"] .pad > div {
flex: 1;
width: 100%;
}
/* Ensure Quill-generated content displays properly */
.item[data-kind="text"] .pad > div p,
.item[data-kind="text"] .pad > div ul,
.item[data-kind="text"] .pad > div ol {
margin: 0;
padding: 0;
width: 100%;
}
.item[data-kind="text"] .pad > div ul,
.item[data-kind="text"] .pad > div ol {
padding-left: 20px;
}
.pad {
padding: 12px;
}
.resize {
position: absolute;
right: 6px;
bottom: 6px;
width: 16px;
height: 16px;
cursor: nwse-resize;
background: linear-gradient(135deg,transparent 50%,#cbd5e1 50%),
linear-gradient(45deg,transparent 50%,#cbd5e1 50%);
background-size: 8px 8px;
background-repeat: no-repeat;
background-position: left bottom, right top;
border-radius: 4px;
z-index: 40000;
}
.leaflet-container {
height: 100%;
width: 100%;
}
.help {
font-size: 12px;
color: #6b7280;
}
/* Modal styles */
.backdrop {
position: fixed;
inset: 0;
background: rgba(0,0,0,.35);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.modal-custom {
width: min(820px,calc(100% - 24px));
background: #fff;
border-radius: 14px;
box-shadow: var(--shadow);
overflow: hidden;
position: relative;
z-index: 10000;
}
.mh {
padding: 12px 16px;
border-bottom: 1px solid #eef0f4;
font-weight: 600;
}
.mb {
padding: 14px 16px;
max-height: 70vh;
overflow: auto;
}
.mf {
padding: 12px 16px;
border-top: 1px solid #eef0f4;
display: flex;
gap: 8px;
justify-content: flex-end;
}
.row-custom {
display: grid;
grid-template-columns: 200px 1fr;
gap: 10px;
align-items: center;
margin-bottom: 10px;
}
.row-custom input, .row-custom select, .row-custom textarea {
width: 100%;
padding: 8px;
border: 1px solid #e5e7eb;
border-radius: 8px;
font: inherit;
}
#dbg {
display: none;
margin: 8px 16px;
padding: 8px 12px;
border-radius: 8px;
border: 1px solid #ffeeba;
border-left: 4px solid #ffecb5;
background: #fff3cd;
color: #856404;
font: 12px/1.4 system-ui;
}
/* Feature popup styles */
.feature-popup, .multi-feature-popup {
font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial;
min-width: 200px;
max-width: 300px;
}
.popup-header {
background: var(--accent);
color: white;
padding: 8px 12px;
margin: -10px -10px 10px -10px;
border-radius: 8px 8px 0 0;
}
.popup-header h4 {
margin: 0;
font-size: 14px;
font-weight: 600;
}
.popup-content {
padding: 0;
}
.popup-row {
padding: 4px 0;
border-bottom: 1px solid #f0f0f0;
font-size: 12px;
}
.popup-row:last-child {
border-bottom: none;
}
.popup-row strong {
color: #333;
}
.popup-footer {
margin-top: 10px;
text-align: center;
}
.popup-btn {
background: var(--accent);
color: white;
border: none;
padding: 6px 12px;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
font-weight: 500;
}
.popup-btn:hover {
background: #5a67d8;
}
/* Modal styles */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
z-index: 2000;
display: flex;
align-items: center;
justify-content: center;
}
.feature-table-modal {
background: white;
border-radius: 8px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
max-width: 80%;
max-height: 80%;
overflow: hidden;
display: flex;
flex-direction: column;
}
.modal-header {
background: var(--accent);
color: white;
padding: 12px 16px;
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-header h3 {
margin: 0;
font-size: 16px;
font-weight: 600;
}
.modal-close {
background: none;
border: none;
color: white;
font-size: 20px;
cursor: pointer;
padding: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
}
.modal-close:hover {
background: rgba(255, 255, 255, 0.2);
border-radius: 4px;
}
.modal-content {
padding: 16px;
overflow: auto;
flex: 1;
}
.feature-table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.feature-table th {
background: #f8f9fa;
padding: 8px;
text-align: left;
border: 1px solid #dee2e6;
font-weight: 600;
}
.feature-table td {
padding: 8px;
border: 1px solid #dee2e6;
vertical-align: top;
}
.feature-table tr:nth-child(even) {
background: #f8f9fa;
}
</style>
</head>
<body>
<?php
$headerTitle = 'Dashboard Builder';
$headerSubtitle = $dashboardId > 0 ? 'Edit Dashboard' : 'Create Dashboard';
$headerIcon = 'speedometer2';
include 'incl/header.php';
?>
<div class="topbar" style="background: white; padding: 10px 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px;">
<div style="display: flex; gap: 10px; justify-content: center; align-items: center;">
<button class="btn" id="testBtn">Test Widgets</button>
<button class="btn" id="clearBtn">Clear</button>
<button class="btn" id="loadBtn" style="display: none;">Load</button>
<button class="btn btn-primary" id="saveBtn">Save Dashboard</button>
</div>
</div>
<div id="dbg"></div>
<button class="sidebar-toggle" id="sidebarToggle" title="Toggle Sidebar">
<i class="bi bi-layout-sidebar"></i>
</button>
<div class="wrap" id="mainWrap">
<aside class="sidebar">
<h6 style="margin-top: 0;">Dashboard Widgets</h6>
<div class="picker" data-kind="map">
<i class="bi bi-geo-alt"></i> <strong>Map</strong>
<div class="help">Add an interactive map</div>
</div>
<div class="picker" data-kind="chart">
<i class="bi bi-bar-chart"></i> <strong>Chart</strong>
<div class="help">Add a chart (bar, line, pie)</div>
</div>
<div class="picker" data-kind="table">
<i class="bi bi-table"></i> <strong>Table</strong>
<div class="help">Add a data table</div>
</div>
<div class="picker" data-kind="counter">
<i class="bi bi-123"></i> <strong>Counter</strong>
<div class="help">Count, Sum, or Average</div>
</div>
<div class="picker" data-kind="text">
<i class="bi bi-type"></i> <strong>HTML</strong>
<div class="help">Add formatted HTML content</div>
</div>
<hr style="margin: 16px 0; border: none; border-top: 1px solid #eef0f4">
<div class="help">
Drag widgets onto the canvas to build your dashboard.
Click to configure, drag to reposition, and resize from the corner.
</div>
</aside>
<main class="canvas" id="canvas"></main>
</div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
<!-- Quill Editor -->
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script>
// Configuration from PHP
const DASHBOARD_EDITOR = true;
const DASHBOARD_ID = <?php echo $dashboardId; ?>;
const AVAILABLE_LAYERS = <?php echo json_encode($availableLayers); ?>;
const INITIAL_CONFIG = <?php echo $dashboardConfig ? json_encode($dashboardConfig) : 'null'; ?>;
const canvas = document.getElementById('canvas');
// Debug information
console.log('Dashboard Builder loaded');
console.log('Available layers:', AVAILABLE_LAYERS);
console.log('Initial config:', INITIAL_CONFIG);
// Sidebar toggle functionality
const sidebarToggle = document.getElementById('sidebarToggle');
const mainWrap = document.getElementById('mainWrap');
let sidebarCollapsed = false;
sidebarToggle.addEventListener('click', () => {
sidebarCollapsed = !sidebarCollapsed;
mainWrap.classList.toggle('sidebar-collapsed', sidebarCollapsed);
// Update button icon
const icon = sidebarToggle.querySelector('i');
if (sidebarCollapsed) {
icon.className = 'bi bi-layout-sidebar-inset';
} else {
icon.className = 'bi bi-layout-sidebar';
}
// Trigger resize for any maps to adjust to new canvas size
setTimeout(() => {
items.forEach(item => {
if (item.kind === 'map') {
const mapDiv = document.getElementById('map-' + item.id);
if (mapDiv && mapDiv._leaflet_map) {
mapDiv._leaflet_map.invalidateSize();
}
}
});
}, 350); // Wait for transition to complete
});
// Function to build CQL filter for data fetching
function buildCqlFilterForData(filters, layerId) {
if (!filters || !filters[layerId]) return '';
const conditions = filters[layerId];
const filterParts = [];
conditions.forEach((filter, idx) => {
if (!filter.attribute || !filter.value) return;
const attribute = filter.attribute;
const operator = filter.operator || '=';
const value = filter.value;
let condition = '';
switch (operator) {
case '=':
condition = attribute + ' = \'' + value.replace(/'/g, "''") + '\'';
break;
case '!=':
condition = attribute + ' != \'' + value.replace(/'/g, "''") + '\'';
break;
case '>':
case '<':
case '>=':
case '<=':
condition = attribute + ' ' + operator + ' ' + value;
break;
case 'LIKE':
condition = attribute + ' LIKE \'%' + value.replace(/'/g, "''") + '%\'';
break;
default:
condition = attribute + ' = \'' + value.replace(/'/g, "''") + '\'';
}
if (idx > 0 && filter.logic) {
filterParts.push(filter.logic + ' ' + condition);
} else {
filterParts.push(condition);
}
});
return filterParts.join(' ');
}
// Function to fetch data from GeoServer WFS via proxy
async function fetchLayerData(layerName, limit = 100) {
try {
const proxyUrl = 'geoserver_proxy.php?dash_id=' + DASHBOARD_ID;
let wfsUrl = `${proxyUrl}&service=WFS&version=1.0.0&request=GetFeature&typeName=${layerName}&outputFormat=application/json&maxFeatures=${limit}`;
// Build filter map from all map widgets
const layerFilters = {};
items.forEach(item => {
if (item.kind === 'map' && item.config.filters) {
Object.keys(item.config.filters).forEach(layerId => {
layerFilters[layerId] = item.config.filters[layerId];
});
}
});
// Apply CQL filter if configured for this layer in any map widget
if (layerFilters[layerName]) {
const cqlFilter = buildCqlFilterForData(layerFilters, layerName);
if (cqlFilter) {
wfsUrl += `&CQL_FILTER=${encodeURIComponent(cqlFilter)}`;
console.log('Applying filter when fetching data for', layerName + ':', cqlFilter);
}
}
console.log('Fetching data from:', wfsUrl);
const response = await fetch(wfsUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Layer data fetched:', data);
return data;
} catch (error) {
console.error('Error fetching layer data:', error);
return null;
}
}
// Function to format numbers with comma separators
function formatNumber(value) {
if (typeof value === 'string') {
// If it's a string (like "Error"), return as is
return value;
}
if (value == null || isNaN(value)) {
return '0';
}
// Use toLocaleString to add comma separators
return Number(value).toLocaleString();
}
// Filter index tracking
let filterIndexes = {};
// Function to generate layer filters HTML for the map widget
function generateLayerFiltersHTML(item) {
const selectedLayers = item.config.layers || [];
const filters = item.config.filters || {};
if (selectedLayers.length === 0) {
return '<p style="color: #999; text-align: center; padding: 20px;">Select layers above to configure filters.</p>';
}
let html = '';
selectedLayers.forEach(layerId => {
const layer = AVAILABLE_LAYERS.find(l => l.id === layerId);
if (!layer) return;
const layerFilters = filters[layerId] || [{'attribute': '', 'operator': '=', 'value': '', 'logic': 'AND'}];
html += `
<div style="margin-bottom: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
<label style="font-weight: 600; font-size: 12px;">
${layer.title} (${layer.workspace})
</label>
<button type="button" onclick="addFilterCondition('${layerId.replace(/:/g, '_')}')"
style="background: #0d6efd; color: white; border: none; padding: 4px 10px; border-radius: 4px; cursor: pointer; font-size: 11px;">
+ Add Condition
</button>
</div>
<div class="filter-conditions-${layerId.replace(/:/g, '_')}">
${layerFilters.map((condition, idx) => {
const isFirst = idx === 0;
return `
<div style="margin-bottom: 10px; padding: 8px; border: 1px solid #e0e0e0; border-radius: 4px; background: white;">
${!isFirst ? `
<div style="margin-bottom: 6px;">
<select name="layer_filters[${layerId}][${idx}][logic]"
style="padding: 4px 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 11px;">
<option value="AND" ${(!condition.logic || condition.logic === 'AND') ? 'selected' : ''}>AND</option>
<option value="OR" ${(condition.logic === 'OR') ? 'selected' : ''}>OR</option>
</select>
</div>
` : ''}
<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px; margin-bottom: 8px;">
<input type="text" name="layer_filters[${layerId}][${idx}][attribute]"
placeholder="Attribute name"
value="${(condition.attribute || '').replace(/"/g, '"')}"
style="padding: 6px; border: 1px solid #ddd; border-radius: 4px; font-size: 12px;">
<select name="layer_filters[${layerId}][${idx}][operator]"
style="padding: 6px; border: 1px solid #ddd; border-radius: 4px; font-size: 12px;">
<option value="=" ${(!condition.operator || condition.operator === '=') ? 'selected' : ''}>equals (=)</option>
<option value=">" ${(condition.operator === '>') ? 'selected' : ''}>greater (>)</option>
<option value="<" ${(condition.operator === '<') ? 'selected' : ''}>less (<)</option>
<option value=">=" ${(condition.operator === '>=') ? 'selected' : ''}>>=</option>
<option value="<=" ${(condition.operator === '<=') ? 'selected' : ''}><=</option>
<option value="!=" ${(condition.operator === '!=') ? 'selected' : ''}>not equals (!=)</option>
<option value="LIKE" ${(condition.operator === 'LIKE') ? 'selected' : ''}>contains (LIKE)</option>
</select>
</div>
<div style="display: flex; gap: 8px;">
<input type="text" name="layer_filters[${layerId}][${idx}][value]"
placeholder="Filter value"
value="${(condition.value || '').replace(/"/g, '"')}"
style="flex: 1; padding: 6px; border: 1px solid #ddd; border-radius: 4px; font-size: 12px;">
<button type="button" onclick="this.parentElement.parentElement.remove()"
style="background: #dc3545; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 11px;">
Remove
</button>
</div>
</div>
`;
}).join('')}
</div>
</div>
`;
});
return html;
}
// Function to add a filter condition to a layer
function addFilterCondition(sanitizedLayerId) {
const originalLayerId = sanitizedLayerId.replace(/_/g, ':');
const container = document.querySelector('.filter-conditions-' + sanitizedLayerId);
if (!container) return;
if (!filterIndexes[sanitizedLayerId]) {
filterIndexes[sanitizedLayerId] = container.querySelectorAll('div').length;
}
const index = filterIndexes[sanitizedLayerId]++;
const conditionHtml = `
<div style="margin-bottom: 10px; padding: 8px; border: 1px solid #e0e0e0; border-radius: 4px; background: white;">
<div style="margin-bottom: 6px;">
<select name="layer_filters[${originalLayerId}][${index}][logic]" style="padding: 4px 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 11px;">
<option value="AND">AND</option>
<option value="OR">OR</option>
</select>
</div>
<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px; margin-bottom: 8px;">
<input type="text" name="layer_filters[${originalLayerId}][${index}][attribute]" placeholder="Attribute name" style="padding: 6px; border: 1px solid #ddd; border-radius: 4px; font-size: 12px;">
<select name="layer_filters[${originalLayerId}][${index}][operator]" style="padding: 6px; border: 1px solid #ddd; border-radius: 4px; font-size: 12px;">
<option value="=">equals (=)</option>
<option value=">">greater (>)</option>
<option value="<">less (<)</option>
<option value=">=">>=</option>
<option value="<="><=</option>
<option value="!=">not equals (!=)</option>
<option value="LIKE">contains (LIKE)</option>
</select>
</div>
<div style="display: flex; gap: 8px;">
<input type="text" name="layer_filters[${originalLayerId}][${index}][value]" placeholder="Filter value" style="flex: 1; padding: 6px; border: 1px solid #ddd; border-radius: 4px; font-size: 12px;">
<button type="button" onclick="this.parentElement.parentElement.remove()" style="background: #dc3545; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 11px;">
Remove
</button>
</div>
</div>
`;
container.insertAdjacentHTML('beforeend', conditionHtml);
}
// Function to handle map clicks and show popups
async function handleMapClick(e, map, layers) {
if (!layers || layers.length === 0) {
console.log('No layers configured for popups');
return;
}
const lat = e.latlng.lat;
const lng = e.latlng.lng;
try {
// Query each layer for features at the clicked point
const allFeatures = [];
for (const layerId of layers) {
try {
const features = await queryFeaturesAtPoint(layerId, lat, lng);
if (features && features.length > 0) {
allFeatures.push(...features.map(f => ({
...f,
layerName: layerId
})));
}
} catch (error) {
console.warn(`Error querying layer ${layerId}:`, error);
}
}
if (allFeatures.length > 0) {
showFeaturePopup(allFeatures, lat, lng, map);
} else {
// Show a simple popup indicating no features found
L.popup()
.setLatLng([lat, lng])
.setContent('<div style="padding: 10px; text-align: center; color: #666;">No features found at this location</div>')
.openOn(map);
}
} catch (error) {
console.error('Error handling map click:', error);
}
}
// Function to query features at a specific point using WFS
async function queryFeaturesAtPoint(layerId, lat, lng) {
try {
const proxyUrl = 'geoserver_proxy.php?dash_id=' + DASHBOARD_ID;
const bbox = `${lng-0.001},${lat-0.001},${lng+0.001},${lat+0.001}`;
const wfsUrl = `${proxyUrl}&service=WFS&version=1.0.0&request=GetFeature&typeName=${layerId}&outputFormat=application/json&bbox=${bbox}&srsName=EPSG:4326`;
const response = await fetch(wfsUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.features || [];
} catch (error) {
console.error('Error querying features at point:', error);
return [];
}
}
// Function to show feature popup
function showFeaturePopup(features, lat, lng, map) {
if (features.length === 1) {
// Single feature - show simple popup
const feature = features[0];
const popupContent = generatePopupContent(feature);
L.popup()
.setLatLng([lat, lng])
.setContent(popupContent)
.openOn(map);
} else {
// Multiple features - show navigation popup
const popupContent = generateMultiFeaturePopupContent(features, lat, lng);
L.popup()
.setLatLng([lat, lng])
.setContent(popupContent)
.openOn(map);
}
}
// Function to generate popup content for a single feature
function generatePopupContent(feature) {
const props = feature.properties || {};
const layerName = feature.layerName || 'Unknown Layer';
let html = `<div class="feature-popup">`;
html += `<div class="popup-header">`;
html += `<h4>${layerName}</h4>`;
html += `</div>`;
html += `<div class="popup-content">`;
// Show first 5 properties
const propKeys = Object.keys(props).slice(0, 5);
propKeys.forEach(key => {
const value = props[key];
const displayValue = typeof value === 'string' && value.length > 50
? value.substring(0, 50) + '...'
: value;
html += `<div class="popup-row">`;
html += `<strong>${key}:</strong> ${displayValue}`;
html += `</div>`;
});
if (Object.keys(props).length > 5) {
html += `<div class="popup-row">`;
html += `<em>... and ${Object.keys(props).length - 5} more properties</em>`;
html += `</div>`;
}
html += `</div>`;
html += `<div class="popup-footer">`;
html += `<button class="popup-btn" onclick="showFeatureTable(${JSON.stringify(feature).replace(/"/g, '"')})">View Details</button>`;
html += `</div>`;
html += `</div>`;
return html;
}
// Function to generate popup content for multiple features