-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.php
More file actions
2691 lines (2551 loc) · 146 KB
/
Copy pathadmin.php
File metadata and controls
2691 lines (2551 loc) · 146 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
// Check if system is set up before trying to load database-dependent functions
include_once 'common.inc';
if (!isSystemInstalled()) {
// System not set up, redirect to setup
PageHeader('Setup Required');
?>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6 col-md-8">
<div class="card mt-4">
<div class="card-header bg-warning text-dark text-center">
<h3 class="mb-0">Setup Required</h3>
</div>
<div class="card-body text-center">
<div class="alert alert-warning">
<h5 class="alert-heading">TippingPoint Not Configured</h5>
<p>TippingPoint has not been set up yet. Please run the initial setup to configure your database and create an administrator account.</p>
<hr>
<a href="setup.php" class="btn btn-primary">Start Setup</a>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
PageFooter('TippingPoint Setup', 'setup@tippingpoint', $ver);
exit;
}
// System is set up, proceed normally
include_once 'func.inc';
// Upgrade checks will be performed after authentication
session_start();
// Handle Ajax requests BEFORE any HTML output
$is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
if ($is_ajax && isset($_REQUEST['func']) && $_REQUEST['func'] == 'aircraft' && isset($_REQUEST['func_do']) && $_REQUEST['func_do'] == 'edit_do') {
// Include necessary files for Ajax handling
include_once 'func.inc';
// Initialize authentication variables
$is_authenticated = false;
$loginlevel = "0";
$loginuser = isset($_SESSION["loginuser"]) ? $_SESSION["loginuser"] : "";
$loginpass = isset($_SESSION["loginpass"]) ? $_SESSION["loginpass"] : "";
if (!empty($loginuser) && !empty($loginpass)) {
$login_query = $db->query("SELECT * FROM users WHERE username = ?", [$loginuser]);
$pass_verify = $db->fetchAssoc($login_query);
if ($pass_verify && password_verify($loginpass, $pass_verify['password'])) {
$loginlevel = $pass_verify['superuser'];
$is_authenticated = true;
}
}
// Check if user is authenticated (regular users can edit aircraft, they don't need to be superusers)
if (!$is_authenticated) {
header('Content-Type: application/json');
echo json_encode(['success' => false, 'error' => 'Authentication required']);
exit;
}
// Handle the Ajax request
include 'ajax_handler.php';
exit;
}
PageHeader("Admin Interface");
?>
<?php
// LOGIN CHECK
// Initialize loginlevel to default value
$loginlevel = "0";
if (!isset($_REQUEST['func']) || $_REQUEST['func'] != "login") {
$loginuser = isset($_SESSION["loginuser"]) ? $_SESSION["loginuser"] : "";
$loginpass = isset($_SESSION["loginpass"]) ? $_SESSION["loginpass"] : "";
// Check if user has session data
if (!empty($loginuser) && !empty($loginpass)) {
$login_query = $db->query("SELECT * FROM users WHERE username = ?", [$loginuser]);
$pass_verify = $db->fetchAssoc($login_query);
if ($pass_verify && password_verify($loginpass, $pass_verify['password'])) {
$loginlevel = $pass_verify['superuser'];
$_SESSION["user_name"] = $pass_verify['name'];
} else {
// Invalid credentials - redirect with error
header('Location: ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?func=login&sysmsg=invalid');
}
} else {
// No session data - redirect to login without error
header('Location: ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?func=login');
}
}
// Check if migration from MySQL to SQLite is needed BEFORE upgrade checks
// This prevents modifying the original MySQL database before migration
if ($loginlevel == "1" && file_exists('config.inc') && !file_exists(dirname(__FILE__) . '/data/tippingpoint.db')) {
// Skip upgrade checks and go directly to show migration option
// We'll perform upgrade checks after migration or if user declines migration
} else {
// Perform upgrade checks only for authenticated administrators
if ($loginlevel == "1") {
// Check if upgrade is needed
if (isset($config['update_version']) && version_compare($config['update_version'], '2.0.0', '<')) {
header('Location: admin_upgrade.php');
exit;
}
// Additional check for required columns existence (in case config wasn't updated properly)
try {
$test_query = $db->query("SELECT type, weight_limit FROM aircraft_weights LIMIT 1");
$test_query2 = $db->query("SELECT weight_units, fuel_type FROM aircraft LIMIT 1");
} catch (Exception $e) {
if (strpos($e->getMessage(), 'no such column:') !== false) {
header('Location: admin_upgrade.php');
exit;
}
}
}
}
echo "<body>\n";
echo "<nav class=\"navbar navbar-expand-lg navbar-dark bg-secondary fixed-top noprint\">\n";
echo " <div class=\"container-fluid\">\n";
echo " <a class=\"navbar-brand text-warning\" href=\"admin.php\" title=\"TippingPoint Administration Home\">TippingPoint</a>\n";
if (isset($_SESSION["user_name"])) {
echo " <button class=\"navbar-toggler\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#navbarNav\" aria-controls=\"navbarNav\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n";
echo " <span class=\"navbar-toggler-icon\"></span>\n";
echo " </button>\n";
echo " <div class=\"collapse navbar-collapse\" id=\"navbarNav\">\n";
echo " <div class=\"navbar-nav ms-auto\">\n";
echo " <a class=\"nav-link\" href=\"admin.php?func=system\">System Settings</a>\n";
echo " <a class=\"nav-link\" href=\"admin.php?func=aircraft\">Aircraft</a>\n";
echo " <a class=\"nav-link\" href=\"admin.php?func=users\">Users</a>\n";
echo " <a class=\"nav-link\" href=\"admin.php?func=audit\">Audit Log</a>\n";
echo " <a class=\"nav-link\" href=\"admin.php?func=logout\">Logout</a>\n";
echo " </div>\n";
echo " </div>\n";
}
echo " </div>\n";
echo "</nav>\n";
echo "<div class=\"container-fluid\">\n";
// UPDATE CHECK
if ($config['update_check'] < (time()-86400)) {
// Get latest release from GitHub API
$github_api_url = "https://api.github.com/repos/CAP-CalebNewville/tipping-point/releases/latest";
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'User-Agent: TippingPoint-Update-Check'
]
]);
$github_response = file_get_contents($github_api_url, false, $context);
if ($github_response !== false) {
$release_data = json_decode($github_response, true);
if (isset($release_data['tag_name'])) {
$ver_dist = ltrim($release_data['tag_name'], 'v'); // Remove 'v' prefix if present
} else {
$ver_dist = $config['update_version']; // Fallback to current version if API fails
}
} else {
$ver_dist = $config['update_version']; // Fallback to current version if API fails
}
$db->query("UPDATE configuration SET `value` = ? WHERE `item` = 'update_check'", [time()]);
$db->query("UPDATE configuration SET `value` = ? WHERE `item` = 'update_version'", [$ver_dist]);
$current_user = isset($_SESSION["loginuser"]) ? $_SESSION["loginuser"] : 'system';
$db->query("INSERT INTO audit (`id`, `timestamp`, `who`, `what`) VALUES (NULL, CURRENT_TIMESTAMP, ?, ?)", [$current_user, 'UPDATE_CHECK: installed ' . $ver . ', available ' . $ver_dist]);
}
if ($ver != $config['update_version'] && $loginlevel=="1") {
echo "<div class=\"alert alert-warning text-center\">\n";
echo "TippingPoint version " . $config['update_version'] . " is available, you are currently running version " . $ver . ".<br>\n";
echo "View the <a href=\"https://github.com/CAP-CalebNewville/tipping-point/releases\" target=\"_blank\">releases page</a> to see what's new, or visit the <a href=\"https://github.com/CAP-CalebNewville/tipping-point\" target=\"_blank\">project homepage</a> to download.<br>\n";
echo "</div>\n";
}
// Helper function to create readable audit messages
function createAuditMessage($action, $data = []) {
$message = $action;
if (!empty($data)) {
$parts = [];
foreach ($data as $key => $value) {
$parts[] = "{$key}={$value}";
}
$message .= ": " . implode(", ", $parts);
}
return $message;
}
// Check for deprecated CG warning columns that need to be removed
if ($loginlevel=="1") {
try {
$has_deprecated_columns = $db->hasColumn('aircraft', 'cgwarnfwd') || $db->hasColumn('aircraft', 'cgwarnaft') || $db->hasColumn('aircraft', 'cglimits');
if ($has_deprecated_columns) {
header('Location: admin_upgrade.php?reason=deprecated_columns');
exit;
}
} catch (Exception $e) {
// If we can't check for deprecated columns, continue anyway
}
}
// Check for missing arm_units column
if ($loginlevel=="1") {
try {
$has_arm_units_column = $db->hasColumn('aircraft', 'arm_units');
if (!$has_arm_units_column) {
header('Location: admin_upgrade.php?reason=missing_arm_units');
exit;
}
} catch (Exception $e) {
// If we can't check for arm_units column, continue anyway
}
}
echo "<div class=\"row justify-content-center\">\n<div class=\"col-lg-8 col-md-10\">\n<div class=\"card mt-4\">\n<div class=\"card-body\">\n";
// Display migration prompt if needed (before upgrade checks)
if ($loginlevel=="1" && file_exists('config.inc') && !file_exists(dirname(__FILE__) . '/data/tippingpoint.db')) {
echo "<div class=\"alert alert-info text-center\">\n";
echo "<h5 class=\"alert-heading\">Database Migration Available</h5>\n";
echo "<p>TippingPoint now uses SQLite for improved performance and easier deployment. Your MySQL data can be migrated automatically.</p>\n";
echo "<p><strong>Benefits:</strong> Better performance, easier backups, simpler deployment, no database server required.</p>\n";
echo "<a href=\"admin_migrate.php\" class=\"btn btn-primary\">Migrate to SQLite</a> \n";
echo "<button class=\"btn btn-outline-secondary\" onclick=\"this.parentElement.style.display='none';\">Remind Me Later</button>\n";
echo "</div>\n";
}
if (isset($_REQUEST['sysmsg'])) {
$sysmsg = $_REQUEST['sysmsg'];
if ($sysmsg=="logout") { echo "<div class=\"alert alert-success text-center\">You have been logged out.</div>\n\n";
} elseif ($sysmsg=="login") { echo "<div class=\"alert alert-success text-center\">You have been logged in. Select a function from the navigation above.</div>\n\n";
} elseif ($sysmsg=="unauthorized") { echo "<div class=\"alert alert-danger text-center\">Sorry, you are not allowed to access that module.</div>\n\n";
} elseif ($sysmsg=="invalid") { echo "<div class=\"alert alert-danger text-center\">You have entered an invalid username/password combination.</div>\n\n";
} elseif ($sysmsg=="acdeleted") { echo "<div class=\"alert alert-success text-center\">The aircraft has been deleted.</div>\n\n"; }
}
switch (isset($_REQUEST["func"]) ? $_REQUEST["func"] : "") {
case "login":
if (isset($_REQUEST['username']) && $_REQUEST['username']!="" && isset($_REQUEST['password'])) {
// login validation code here - stay logged in for a week
// setcookie("loginuser", $_REQUEST['username'], time()+604800);
// setcookie("loginpass", md5($_REQUEST['password']), time()+604800);
// Validate login credentials first
$login_query = $db->query("SELECT * FROM users WHERE username = ?", [$_REQUEST['username']]);
$user_data = $db->fetchAssoc($login_query);
if ($user_data && password_verify($_REQUEST['password'], $user_data['password'])) {
// Valid login - set session and redirect
$_SESSION["loginuser"] = $_REQUEST['username'];
$_SESSION["loginpass"] = $_REQUEST['password'];
header('Location: ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?sysmsg=login');
} else {
// Invalid login - redirect with error
header('Location: ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?func=login&sysmsg=invalid');
}
} else {
// print login form
echo "<div class=\"text-center mb-4\">\n";
echo "<h2 class=\"text-primary\">Tipping Point Administration</h2>\n";
echo "</div>\n";
echo "<form method=\"post\" action=\"admin.php\" class=\"mx-auto\" style=\"max-width: 400px;\">\n";
echo "<input type=\"hidden\" name=\"func\" value=\"login\">\n";
echo "<div class=\"mb-3\">\n";
echo "<label for=\"username\" class=\"form-label\">Username</label>\n";
echo "<input type=\"text\" class=\"form-control\" id=\"username\" name=\"username\" required>\n";
echo "</div>\n";
echo "<div class=\"mb-3\">\n";
echo "<label for=\"password\" class=\"form-label\">Password</label>\n";
echo "<input type=\"password\" class=\"form-control\" id=\"password\" name=\"password\" required>\n";
echo "</div>\n";
echo "<div class=\"d-grid\">\n";
echo "<button type=\"submit\" class=\"btn btn-primary\">Login</button>\n";
echo "</div>\n";
echo "</form>\n";
}
break;
case "logout":
//setcookie("loginuser", "", time()-3600);
//setcookie("loginpass", "", time()-3600);
session_unset();
session_destroy();
header('Location: ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"] . '?func=login&sysmsg=logout');
break;
case "system":
if ($loginlevel!="1") {
header('Location: ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?sysmsg=unauthorized');
}
echo "<h3 class=\"text-primary mb-3\">System Module</h3>";
if (isset($_REQUEST['message']) && $_REQUEST['message']=="updated") {echo "<p style=\"color: #00AA00; text-align: center;\">Settings Updated.</p>\n\n";}
switch (isset($_REQUEST["func_do"]) ? $_REQUEST["func_do"] : "") {
case "update":
// SQL query to update system settings
foreach ($_POST as $k=>$v) {
if ($k!="func" && $k!="func_do") {
// Use INSERT OR REPLACE to handle new config items
$sql_query = "INSERT OR REPLACE INTO configuration (item, value) VALUES (?, ?);";
$db->query($sql_query, [$k, $v]);
// Enter audit log
$audit_message = createAuditMessage("Updated system setting", [$k => $v]);
$db->query("INSERT INTO audit (`id`, `timestamp`, `who`, `what`) VALUES (NULL, CURRENT_TIMESTAMP, ?, ?)", [$loginuser, 'SYSTEM: ' . $audit_message]);
}
}
header('Location: ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"] . '?func=system&message=updated');
break;
default:
echo "<p class=\"mb-4\">This module adjusts settings that affect the entire software package.</p>";
echo "<form method=\"post\" action=\"admin.php\" class=\"mx-auto\" style=\"max-width: 600px;\">";
echo "<input type=\"hidden\" name=\"func\" value=\"system\">";
echo "<input type=\"hidden\" name=\"func_do\" value=\"update\">";
echo "<div class=\"mb-3\">";
echo "<label for=\"site_name\" class=\"form-label\">Site/Organization Name</label>";
echo "<input type=\"text\" class=\"form-control\" id=\"site_name\" name=\"site_name\" value=\"" . htmlspecialchars($config['site_name']) . "\">";
echo "</div>";
echo "<div class=\"mb-3\">";
echo "<label for=\"administrator\" class=\"form-label\">Administrator E-mail Address</label>";
echo "<input type=\"email\" class=\"form-control\" id=\"administrator\" name=\"administrator\" value=\"" . htmlspecialchars($config['administrator']) . "\">";
echo "</div>";
echo "<div class=\"mb-3\">";
echo "<label for=\"timezone\" class=\"form-label\">Local Time Zone</label>";
echo "<div>";
TimeZoneList($config['timezone']);
echo "</div>";
echo "</div>";
echo "<div class=\"mb-3\">";
echo "<label for=\"pilot_signature\" class=\"form-label\">Pilot Signature</label>";
echo "<select class=\"form-select\" id=\"pilot_signature\" name=\"pilot_signature\">";
echo "<option value=\"0\"";
if (!isset($config['pilot_signature']) || $config['pilot_signature'] != '1') { echo " selected"; }
echo ">No</option>";
echo "<option value=\"1\"";
if (isset($config['pilot_signature']) && $config['pilot_signature'] == '1') { echo " selected"; }
echo ">Yes</option>";
echo "</select>";
echo "<div class=\"form-text\">Display \"Pilot Signature\" block on printed weight and balance forms.</div>";
echo "</div>";
echo "<div class=\"d-grid\">";
echo "<button type=\"submit\" class=\"btn btn-primary\">Save Settings</button>";
echo "</div>";
echo "</form>";
}
break;
case "aircraft":
echo "<h3 class=\"text-primary mb-3\">Aircraft Module</h3>";
switch (isset($_REQUEST["func_do"]) ? $_REQUEST["func_do"] : "") {
case "add":
switch (isset($_REQUEST["step"]) ? $_REQUEST["step"] : "") {
case "2":
// SQL query to add a new aircraft
$sql_query = "INSERT INTO `aircraft` (`active`, `tailnumber`, `makemodel`, `emptywt`, `emptycg`, `maxwt`, `fuelunit`, `weight_units`, `fuel_type`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$db->query($sql_query, ['0', $_REQUEST['tailnumber'], $_REQUEST['makemodel'], $_REQUEST['emptywt'], $_REQUEST['emptycg'], $_REQUEST['maxwt'], $_REQUEST['fuelunit'], $_REQUEST['weight_units'], $_REQUEST['fuel_type']]);
$aircraft_result = $db->query("SELECT * FROM `aircraft` WHERE `tailnumber` = ? ORDER BY `id` DESC LIMIT 1", [$_REQUEST['tailnumber']]);
$aircraft = $db->fetchAssoc($aircraft_result);
// Enter in the audit log
$audit_data = [
'tailnumber' => $_REQUEST['tailnumber'],
'makemodel' => $_REQUEST['makemodel'],
'emptywt' => $_REQUEST['emptywt'],
'emptycg' => $_REQUEST['emptycg'],
'maxwt' => $_REQUEST['maxwt'],
'fuelunit' => $_REQUEST['fuelunit'],
'weight_units' => $_REQUEST['weight_units'],
'fuel_type' => $_REQUEST['fuel_type']
];
$audit_message = createAuditMessage("Created new aircraft", $audit_data);
$db->query("INSERT INTO audit (`id`, `timestamp`, `who`, `what`) VALUES (NULL, CURRENT_TIMESTAMP, ?, ?)", [$loginuser, $aircraft['tailnumber'] . ": " . $audit_message]);
echo "<p>Aircraft " . $aircraft['tailnumber'] . " added successfully. Now go to the <a href=\"admin.php?func=aircraft&func_do=edit&tailnumber=" . $aircraft['id'] . "\">aircraft editor</a> to complete the CG envelope and loading zones.</p>\n";
break;
default:
echo "<div class=\"row justify-content-center\">\n";
echo "<div class=\"col-lg-8 col-md-10\">\n";
echo "<div class=\"card\">\n";
echo "<div class=\"card-header\">\n";
echo "<h5 class=\"card-title mb-0\">Add New Aircraft - Step 1</h5>\n";
echo "</div>\n";
echo "<div class=\"card-body\">\n";
echo "<div class=\"mb-4\">\n";
echo "<p class=\"mb-2\">Define the basic information about the aircraft.</p>\n";
echo "<p class=\"text-muted small mb-0\">Fill in the aircraft specifications. Hover over field labels for additional help information.</p>\n";
echo "</div>\n";
echo "<form method=\"post\" action=\"admin.php\">\n";
echo "<input type=\"hidden\" name=\"func\" value=\"aircraft\">\n";
echo "<input type=\"hidden\" name=\"func_do\" value=\"add\">\n";
echo "<input type=\"hidden\" name=\"step\" value=\"2\">\n";
// Convert table structure to Bootstrap form groups
echo "<div class=\"row mb-3\">\n";
echo "<div class=\"col-md-6\">\n";
echo "<label for=\"tailnumber\" class=\"form-label\">Tail Number</label>\n";
echo "<input type=\"text\" class=\"form-control\" id=\"tailnumber\" name=\"tailnumber\" placeholder=\"N123AB\" required>\n";
echo "</div>\n";
echo "<div class=\"col-md-6\">\n";
echo "<label for=\"makemodel\" class=\"form-label\">Make and Model</label>\n";
echo "<input type=\"text\" class=\"form-control\" id=\"makemodel\" name=\"makemodel\" placeholder=\"Cessna Skyhawk\" required>\n";
echo "</div>\n";
echo "</div>\n";
echo "<div class=\"row mb-3\">\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"emptywt\" class=\"form-label\">Empty Weight</label>\n";
echo "<input type=\"number\" step=\"any\" class=\"form-control\" id=\"emptywt\" name=\"emptywt\" placeholder=\"1556.3\" required>\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"emptycg\" class=\"form-label\">Empty CG</label>\n";
echo "<input type=\"number\" step=\"any\" class=\"form-control\" id=\"emptycg\" name=\"emptycg\" placeholder=\"38.78\" required>\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"maxwt\" class=\"form-label\">Maximum Gross Weight</label>\n";
echo "<input type=\"number\" step=\"any\" class=\"form-control\" id=\"maxwt\" name=\"maxwt\" placeholder=\"2550\" required>\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"max_landing_weight\" class=\"form-label\">Maximum Landing Weight <small class=\"text-muted\">(Optional)</small></label>\n";
echo "<input type=\"number\" step=\"any\" class=\"form-control\" id=\"max_landing_weight\" name=\"max_landing_weight\" placeholder=\"e.g. 2300\" value=\"" . (isset($aircraft['max_landing_weight']) ? htmlspecialchars($aircraft['max_landing_weight']) : '') . "\">\n";
echo "</div>\n";
echo "</div>\n";
echo "<div class=\"row mb-4\">\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"weight_units\" class=\"form-label\">Weight Units</label>\n";
echo "<select class=\"form-select\" id=\"weight_units\" name=\"weight_units\">\n";
echo "<option value=\"Pounds\">Pounds</option>\n";
echo "<option value=\"Kilograms\">Kilograms</option>\n";
echo "</select>\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"arm_units\" class=\"form-label\">Arm Units</label>\n";
echo "<select class=\"form-select\" id=\"arm_units\" name=\"arm_units\">\n";
echo "<option value=\"Inches\">Inches</option>\n";
echo "<option value=\"Centimeters\">Centimeters</option>\n";
echo "</select>\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"fuelunit\" class=\"form-label\">Fuel Units</label>\n";
echo "<select class=\"form-select\" id=\"fuelunit\" name=\"fuelunit\">\n";
echo "<option value=\"Gallons\">Gallons</option>\n";
echo "<option value=\"Liters\">Liters</option>\n";
echo "<option value=\"Pounds\">Pounds</option>\n";
echo "<option value=\"Kilograms\">Kilograms</option>\n";
echo "</select>\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"fuel_type\" class=\"form-label\">Fuel Type</label>\n";
echo "<select class=\"form-select\" id=\"fuel_type\" name=\"fuel_type\">\n";
echo "<option value=\"100LL/Mogas\">100LL/Mogas</option>\n";
echo "<option value=\"Jet A\">Jet A</option>\n";
echo "</select>\n";
echo "</div>\n";
echo "</div>\n";
echo "<div class=\"d-grid gap-2 d-md-flex justify-content-md-end\">\n";
echo "<a href=\"admin.php?func=aircraft\" class=\"btn btn-outline-secondary me-md-2\">Cancel</a>\n";
echo "<button type=\"submit\" class=\"btn btn-primary\">Continue to Step 2</button>\n";
echo "</div>\n";
echo "</form>\n";
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
}
break;
case "delete":
if ($_REQUEST['tailnumber']!="") {
if ($_REQUEST['confirm']=="DELETE FOREVER") {
// Get aircraft info before deletion for audit log
$aircraft_query = $db->query("SELECT * FROM aircraft WHERE id = ?", [$_REQUEST['tailnumber']]);
$aircraft = $db->fetchAssoc($aircraft_query);
$sql_query1 = "DELETE FROM aircraft_cg WHERE `tailnumber` = ?";
$sql_query2 = "DELETE FROM aircraft_weights WHERE `tailnumber` = ?";
$sql_query3 = "DELETE FROM aircraft WHERE `id` = ?";
$db->query($sql_query1, [$_REQUEST['tailnumber']]);
$db->query($sql_query2, [$_REQUEST['tailnumber']]);
$db->query($sql_query3, [$_REQUEST['tailnumber']]);
// Enter in the audit log
$audit_data = [
'tailnumber' => $aircraft['tailnumber'],
'makemodel' => $aircraft['makemodel'],
'aircraft_id' => $_REQUEST['tailnumber']
];
$audit_message = createAuditMessage("Deleted aircraft and all associated data", $audit_data);
$db->query("INSERT INTO audit (`id`, `timestamp`, `who`, `what`) VALUES (NULL, CURRENT_TIMESTAMP, ?, ?)", [$loginuser, 'ACDELETE: ' . $audit_message]);
header('Location: ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"] . '?func=aircraft&sysmsg=acdeleted');
} else {
echo "<div class=\"alert alert-warning\">\n";
echo "<h5 class=\"alert-heading\">Aircraft NOT Deleted</h5>\n";
echo "<p class=\"mb-2\">In the confirmation box, you must type the words <strong>\"DELETE FOREVER\"</strong> in all caps.</p>\n";
echo "<p class=\"mb-0\">Use your browser's back button to try again.</p>\n";
echo "</div>\n";
}
} else {
echo "<div class=\"row justify-content-center\">\n";
echo "<div class=\"col-lg-8 col-md-10\">\n";
echo "<div class=\"card border-danger\">\n";
echo "<div class=\"card-header bg-danger text-white\">\n";
echo "<h5 class=\"card-title mb-0\"><i class=\"bi bi-exclamation-triangle\"></i> Delete Aircraft - PERMANENT ACTION</h5>\n";
echo "</div>\n";
echo "<div class=\"card-body\">\n";
echo "<div class=\"alert alert-danger mb-4\">\n";
echo "<h6 class=\"alert-heading\"><strong>⚠️ WARNING: This is permanent and CANNOT be undone!</strong></h6>\n";
echo "<p class=\"mb-2\">Aircraft deletion is a permanent action. The aircraft and all of its associated data will be gone forever.</p>\n";
echo "<p class=\"mb-0\">If you wish to temporarily deactivate an aircraft profile, use the <a href=\"admin.php?func=aircraft&func_do=edit\" class=\"alert-link\">edit</a> screen instead. This is useful for a single aircraft with multiple configurations (wheels/skis/floats).</p>\n";
echo "</div>\n";
echo "<form method=\"post\" action=\"admin.php\">\n";
echo "<input type=\"hidden\" name=\"func\" value=\"aircraft\">\n";
echo "<input type=\"hidden\" name=\"func_do\" value=\"delete\">\n";
echo "<div class=\"mb-3\">\n";
echo "<label for=\"tailnumber\" class=\"form-label\">Choose Aircraft to Delete</label>\n";
AircraftListAll();
echo "</div>\n";
echo "<div class=\"mb-4\">\n";
echo "<label for=\"confirm\" class=\"form-label\">Type the words \"DELETE FOREVER\" to confirm</label>\n";
echo "<input type=\"text\" class=\"form-control\" id=\"confirm\" name=\"confirm\" placeholder=\"DELETE FOREVER\" required>\n";
echo "<div class=\"form-text text-danger\">You must type exactly: DELETE FOREVER (in all caps)</div>\n";
echo "</div>\n";
echo "<div class=\"d-grid gap-2 d-md-flex justify-content-md-between\">\n";
echo "<a href=\"admin.php?func=aircraft\" class=\"btn btn-outline-secondary\">Cancel</a>\n";
echo "<button type=\"submit\" class=\"btn btn-danger\" onclick=\"return window.confirm('Are you REALLY sure you want to PERMANENTLY delete this aircraft?')\">Delete Aircraft Forever</button>\n";
echo "</div>\n";
echo "</form>\n";
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
}
break;
case "duplicate":
if ($_REQUEST['tailnumber']!="") {
// create the new aircraft
$aircraft_result = $db->query("SELECT * FROM aircraft WHERE id = ?", [$_REQUEST['tailnumber']]);
$aircraft = $db->fetchAssoc($aircraft_result);
$db->query("INSERT INTO aircraft (`active`, `tailnumber`, `makemodel`, `emptywt`, `emptycg`, `maxwt`, `fuelunit`, `weight_units`, `arm_units`, `fuel_type`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
['0', $_REQUEST['newtailnumber'], $_REQUEST['newmakemodel'], $aircraft['emptywt'], $aircraft['emptycg'], $aircraft['maxwt'], $aircraft['fuelunit'], $aircraft['weight_units'], $aircraft['arm_units'], $aircraft['fuel_type']]);
// get id of new aircraft
$aircraft_result = $db->query("SELECT * FROM aircraft WHERE tailnumber = ? ORDER BY id DESC LIMIT 1", [$_REQUEST['newtailnumber']]);
$aircraft_new = $db->fetchAssoc($aircraft_result);
// duplicate the weights
$weights_result = $db->query("SELECT * FROM aircraft_weights WHERE tailnumber = ?", [$_REQUEST['tailnumber']]);
while($row = $db->fetchAssoc($weights_result)) {
$db->query("INSERT INTO aircraft_weights (`tailnumber`, `order`, `item`, `weight`, `arm`, `fuelwt`, `type`, `weight_limit`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
[$aircraft_new['id'], $row['order'], $row['item'], $row['weight'], $row['arm'], $row['fuelwt'] ?? 0, $row['type'] ?? 'Variable Weight no limit', $row['weight_limit'] ?? null]);
}
// duplicate the cg envelopes
$cg_result = $db->query("SELECT * FROM aircraft_cg WHERE tailnumber = ?", [$_REQUEST['tailnumber']]);
while($row = $db->fetchAssoc($cg_result)) {
$envelope_name = isset($row['envelope_name']) ? $row['envelope_name'] : 'Normal';
$color = isset($row['color']) ? $row['color'] : 'blue';
$db->query("INSERT INTO aircraft_cg (`tailnumber`, `arm`, `weight`, `envelope_name`, `color`) VALUES (?, ?, ?, ?, ?)",
[$aircraft_new['id'], $row['arm'], $row['weight'], $envelope_name, $color]);
}
// Enter in the audit log
$db->query("INSERT INTO audit (`id`, `timestamp`, `who`, `what`) VALUES (NULL, CURRENT_TIMESTAMP, ?, ?)", [$loginuser,
'DUPLICATE: (' . $aircraft['id'] . ', ' . $aircraft['tailnumber'] . ', ' . $aircraft['makemodel'] . ') AS (' . $aircraft_new['id'] . ', ' . $_REQUEST['newtailnumber'] . ', ' . $_REQUEST['newmakemodel'] . ')']);
echo "<div class=\"alert alert-success\">\n";
echo "<h5 class=\"alert-heading\">Aircraft Duplicated Successfully!</h5>\n";
echo "<p class=\"mb-2\">The aircraft has been cloned with the new tail number: <strong>" . htmlspecialchars($_REQUEST['newtailnumber']) . "</strong></p>\n";
echo "<p class=\"mb-0\">Next step: <a href=\"admin.php?func=aircraft&func_do=edit&tailnumber=" . $aircraft_new['id'] . "\" class=\"alert-link\">Complete the aircraft configuration</a> by editing the CG envelope and loading zones.</p>\n";
echo "</div>\n";
} else {
echo "<div class=\"row justify-content-center\">\n";
echo "<div class=\"col-lg-8 col-md-10\">\n";
echo "<div class=\"card\">\n";
echo "<div class=\"card-header\">\n";
echo "<h5 class=\"card-title mb-0\">Duplicate Aircraft</h5>\n";
echo "</div>\n";
echo "<div class=\"card-body\">\n";
echo "<div class=\"mb-4\">\n";
echo "<p class=\"mb-3\">Clone an existing aircraft to create a new one with the same specifications.</p>\n";
echo "<p class=\"text-muted small mb-0\">This is useful for aircraft with multiple configurations (wheels/skis/floats) or similar models that share most specifications.</p>\n";
echo "</div>\n";
echo "<form method=\"post\" action=\"admin.php\">\n";
echo "<input type=\"hidden\" name=\"func\" value=\"aircraft\">\n";
echo "<input type=\"hidden\" name=\"func_do\" value=\"duplicate\">\n";
echo "<div class=\"mb-3\">\n";
echo "<label for=\"tailnumber\" class=\"form-label\">Choose Aircraft to Duplicate</label>\n";
AircraftListAll();
echo "</div>\n";
echo "<div class=\"mb-3\">\n";
echo "<label for=\"newtailnumber\" class=\"form-label\">New Tail Number</label>\n";
echo "<input type=\"text\" class=\"form-control\" id=\"newtailnumber\" name=\"newtailnumber\" placeholder=\"N123AB\" required>\n";
echo "</div>\n";
echo "<div class=\"mb-4\">\n";
echo "<label for=\"newmakemodel\" class=\"form-label\">New Make and Model</label>\n";
echo "<input type=\"text\" class=\"form-control\" id=\"newmakemodel\" name=\"newmakemodel\" placeholder=\"Cessna Skyhawk\" required>\n";
echo "</div>\n";
echo "<div class=\"d-grid gap-2 d-md-flex justify-content-md-end\">\n";
echo "<a href=\"admin.php?func=aircraft\" class=\"btn btn-outline-secondary me-md-2\">Cancel</a>\n";
echo "<button type=\"submit\" class=\"btn btn-success\">Duplicate Aircraft</button>\n";
echo "</div>\n";
echo "</form>\n";
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
}
break;
case "edit":
if (isset($_REQUEST['tailnumber']) && $_REQUEST['tailnumber']!="") {
// Check if database needs upgrade before any output
$has_envelope_columns = $db->hasColumn('aircraft_cg', 'envelope_name');
if (!$has_envelope_columns) {
// Redirect to upgrade script
header('Location: admin_upgrade.php');
exit;
}
$aircraft_result = $db->query("SELECT * FROM aircraft WHERE id = ?", [$_REQUEST['tailnumber']]);
$aircraft = $db->fetchAssoc($aircraft_result);
echo "<div class=\"mb-4\">\n";
echo "<h4 class=\"text-primary\">Editing Aircraft: " . htmlspecialchars($aircraft['tailnumber']) . " ";
if ($aircraft['active'] == 1) {
echo "<span class=\"badge bg-success\" style=\"font-size: 0.8rem; vertical-align: middle;\">Active</span>";
} else {
echo "<span class=\"badge bg-secondary\" style=\"font-size: 0.8rem; vertical-align: middle;\">Inactive</span>";
}
echo "</h4>\n";
echo "<div class=\"mt-2\">\n";
echo "<a href=\"index.php?tailnumber=" . htmlspecialchars($aircraft['id']) . "\" target=\"_blank\" class=\"btn btn-outline-primary btn-sm\">\n";
echo "<i class=\"fas fa-external-link-alt\"></i> View Aircraft\n";
echo "</a>\n";
echo "</div>\n";
echo "</div>\n";
// Aircraft basic information
echo "<div class=\"card mb-4\">\n";
echo "<div class=\"card-header\">\n";
echo "<h4 class=\"card-title mb-0\">Aircraft Basic Information</h4>\n";
echo "</div>\n";
echo "<div class=\"card-body\">\n";
echo "<form method=\"post\" action=\"admin.php\" onsubmit=\"return submitBasicInformation(event)\">\n";
echo "<input type=\"hidden\" name=\"id\" value=\"" . $aircraft['id'] . "\">\n";
echo "<input type=\"hidden\" name=\"func\" value=\"aircraft\">\n";
echo "<input type=\"hidden\" name=\"func_do\" value=\"edit_do\">\n";
echo "<input type=\"hidden\" name=\"what\" value=\"basics\">\n";
echo "<div class=\"row mb-3\">\n";
echo "<div class=\"col-md-6\">\n";
echo "<label for=\"tailnumber\" class=\"form-label\">Tail Number</label>\n";
echo "<input type=\"text\" class=\"form-control\" id=\"tailnumber\" name=\"tailnumber\" value=\"" . htmlspecialchars($aircraft['tailnumber']) . "\">\n";
echo "</div>\n";
echo "<div class=\"col-md-6\">\n";
echo "<label for=\"makemodel\" class=\"form-label\">Make and Model</label>\n";
echo "<input type=\"text\" class=\"form-control\" id=\"makemodel\" name=\"makemodel\" value=\"" . htmlspecialchars($aircraft['makemodel']) . "\">\n";
echo "</div>\n";
echo "</div>\n";
echo "<div class=\"row mb-3\">\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"emptywt\" class=\"form-label\">Empty Weight</label>\n";
echo "<input type=\"number\" step=\"any\" class=\"form-control\" id=\"emptywt\" name=\"emptywt\" value=\"" . $aircraft['emptywt'] . "\">\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"emptycg\" class=\"form-label\">Empty CG</label>\n";
echo "<input type=\"number\" step=\"any\" class=\"form-control\" id=\"emptycg\" name=\"emptycg\" value=\"" . $aircraft['emptycg'] . "\">\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"maxwt\" class=\"form-label\">Maximum Gross Weight</label>\n";
echo "<input type=\"number\" step=\"any\" class=\"form-control\" id=\"maxwt\" name=\"maxwt\" value=\"" . $aircraft['maxwt'] . "\">\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"max_landing_weight\" class=\"form-label\">Maximum Landing Weight</label>\n";
echo "<input type=\"number\" step=\"any\" class=\"form-control\" id=\"max_landing_weight\" name=\"max_landing_weight\" placeholder=\"Optional - e.g. 2300\" value=\"" . (isset($aircraft['max_landing_weight']) ? htmlspecialchars($aircraft['max_landing_weight']) : '') . "\">\n";
echo "</div>\n";
echo "</div>\n";
echo "<div class=\"row mb-4\">\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"weight_units\" class=\"form-label\">Weight Units</label>\n";
echo "<select class=\"form-select\" id=\"weight_units\" name=\"weight_units\">\n";
echo "<option value=\"Pounds\"";
if(isset($aircraft['weight_units']) && $aircraft['weight_units']=="Pounds") {echo " selected";}
echo ">Pounds</option>\n";
echo "<option value=\"Kilograms\"";
if(isset($aircraft['weight_units']) && $aircraft['weight_units']=="Kilograms") {echo " selected";}
echo ">Kilograms</option>\n";
echo "</select>\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"arm_units\" class=\"form-label\">Arm Units</label>\n";
echo "<select class=\"form-select\" id=\"arm_units\" name=\"arm_units\">\n";
echo "<option value=\"Inches\"";
if(isset($aircraft['arm_units']) && $aircraft['arm_units']=="Inches") {echo " selected";}
echo ">Inches</option>\n";
echo "<option value=\"Centimeters\"";
if(isset($aircraft['arm_units']) && $aircraft['arm_units']=="Centimeters") {echo " selected";}
echo ">Centimeters</option>\n";
echo "</select>\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"fuelunit\" class=\"form-label\">Fuel Units</label>\n";
echo "<select class=\"form-select\" id=\"fuelunit\" name=\"fuelunit\">\n";
echo "<option value=\"Gallons\"";
if($aircraft['fuelunit']=="Gallons") {echo " selected";}
echo ">Gallons</option>\n";
echo "<option value=\"Liters\"";
if($aircraft['fuelunit']=="Liters") {echo " selected";}
echo ">Liters</option>\n";
echo "<option value=\"Pounds\"";
if($aircraft['fuelunit']=="Pounds") {echo " selected";}
echo ">Pounds</option>\n";
echo "<option value=\"Kilograms\"";
if($aircraft['fuelunit']=="Kilograms") {echo " selected";}
echo ">Kilograms</option>\n";
echo "</select>\n";
echo "</div>\n";
echo "<div class=\"col-md-3\">\n";
echo "<label for=\"fuel_type\" class=\"form-label\">Fuel Type</label>\n";
echo "<select class=\"form-select\" id=\"fuel_type\" name=\"fuel_type\">\n";
echo "<option value=\"100LL/Mogas\"";
if(isset($aircraft['fuel_type']) && $aircraft['fuel_type']=="100LL/Mogas") {echo " selected";}
echo ">100LL/Mogas</option>\n";
echo "<option value=\"Jet A\"";
if(isset($aircraft['fuel_type']) && $aircraft['fuel_type']=="Jet A") {echo " selected";}
echo ">Jet A</option>\n";
echo "</select>\n";
echo "</div>\n";
echo "</div>\n";
echo "<div class=\"row align-items-center\">\n";
echo "<div class=\"col-md-3\">\n";
echo "</div>\n";
echo "<div class=\"col-md-6 text-center\">\n";
echo "<div class=\"form-check form-switch\" style=\"gap: 0.25rem; display: flex; align-items: center; justify-content: center;\">\n";
echo "<input type=\"checkbox\" class=\"form-check-input\" name=\"active\" value=\"1\" id=\"active\" style=\"margin: 0;\"";
if ($aircraft['active']==1) {echo" checked";}
echo ">\n";
echo "<label class=\"form-check-label\" for=\"active\" style=\"margin: 0;\">Show aircraft in the weight & balance list</label>\n";
echo "</div>\n";
echo "</div>\n";
echo "<div class=\"col-md-3 text-end\">\n";
echo "<button type=\"submit\" class=\"btn btn-primary\">Save Basic Information</button>\n";
echo "</div>\n";
echo "</div>\n";
echo "</form>\n";
echo "</div>\n";
echo "</div>\n";
// Aircraft CG envelopes (multiple envelopes support)
echo "<div class=\"card mb-4\">\n";
echo "<div class=\"card-header d-flex justify-content-between align-items-center\">\n";
echo "<h4 class=\"card-title mb-0\">Center of Gravity Envelopes</h4>\n";
echo "<div class=\"btn-group\" role=\"group\">\n";
echo "<button type=\"button\" class=\"btn btn-success btn-sm\" data-bs-toggle=\"modal\" data-bs-target=\"#newEnvelopeModal\">Add New Envelope</button>\n";
echo "</div>\n";
echo "</div>\n";
echo "<div class=\"card-body\">\n";
// Help information for CG envelopes
echo "<div class=\"alert alert-info mb-3\">\n";
echo "<h6 class=\"alert-heading\"><i class=\"fas fa-info-circle\"></i> Where to Find CG Envelope Data</h6>\n";
echo "<p class=\"mb-2\">CG envelope data can typically be found in:</p>\n";
echo "<ul class=\"mb-2\">\n";
echo "<li>Your aircraft's <strong>Flight Manual (AFM/POH)</strong></li>\n";
echo "<li>FAA <strong>Type Certificate Data Sheet (TCDS)</strong> - <a href=\"https://drs.faa.gov/browse/TCDSMODEL/doctypeDetails\" target=\"_blank\" rel=\"noopener\">Available here <i class=\"fas fa-external-link-alt\"></i></a></li>\n";
echo "</ul>\n";
echo "<p class=\"mb-0\"><strong>Important:</strong> Always verify that STCs (Supplemental Type Certificates) or other modifications have not superseded the manufacturer's original data. Modified aircraft may have different CG limits.</p>\n";
echo "</div>\n";
// Get all unique envelopes for this aircraft
$envelope_result = $db->query("SELECT DISTINCT envelope_name, color FROM aircraft_cg WHERE tailnumber = ? ORDER BY envelope_name", [$aircraft['id']]);
$envelopes = [];
while ($envelope = $db->fetchAssoc($envelope_result)) {
$envelopes[] = $envelope;
}
// If we have a current envelope from URL that's not in the list (newly created), add it
if (isset($_GET['envelope']) && !empty($_GET['envelope'])) {
$current_from_url = $_GET['envelope'];
$found_in_list = false;
foreach ($envelopes as $env) {
if ($env['envelope_name'] === $current_from_url) {
$found_in_list = true;
break;
}
}
if (!$found_in_list) {
// Add the envelope from URL with color from URL parameter or default
$color_from_url = isset($_GET['envelope_color']) ? $_GET['envelope_color'] : 'blue';
$envelopes[] = ['envelope_name' => $current_from_url, 'color' => $color_from_url];
}
}
// If no envelopes exist, show info message
if (empty($envelopes)) {
echo "<div class=\"alert alert-info text-center\">\n";
echo "<h6>No CG Envelopes Defined</h6>\n";
echo "<p class=\"mb-2\">This aircraft doesn't have any CG envelopes defined yet.</p>\n";
echo "<button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\" data-bs-target=\"#newEnvelopeModal\">Create First Envelope</button>\n";
echo "</div>\n";
} else {
// Envelope selector and current envelope display
$current_envelope = isset($_GET['envelope']) ? $_GET['envelope'] : $envelopes[0]['envelope_name'];
$current_envelope_color = 'primary';
// Check for envelope color in URL parameter first (for newly created envelopes)
if (isset($_GET['envelope_color']) && !empty($_GET['envelope_color'])) {
$current_envelope_color = $_GET['envelope_color'];
} else {
// Find current envelope color from existing envelopes
foreach ($envelopes as $env) {
if ($env['envelope_name'] == $current_envelope) {
$current_envelope_color = $env['color'];
break;
}
}
}
echo "<div class=\"row mb-3\">\n";
echo "<div class=\"col-md-8\">\n";
echo "<div class=\"alert alert-info mb-0\">\n";
echo "<small>Enter the data points for the CG envelope. It does not matter which point you start with or if you go clockwise or counter-clockwise, but they must be entered in order. The last point will automatically be connected back to the first.</small>\n";
echo "</div>\n";
echo "</div>\n";
// Only show envelope selector if multiple envelopes exist
if (count($envelopes) > 1) {
echo "<div class=\"col-md-4\">\n";
echo "<div class=\"card border-" . $current_envelope_color . "\">\n";
echo "<div class=\"card-body p-2\">\n";
echo "<h6 class=\"card-title mb-2\">Current Envelope</h6>\n";
echo "<select class=\"form-select form-select-sm\" onchange=\"window.location.href='admin.php?func=aircraft&func_do=edit&tailnumber=" . $aircraft['id'] . "&envelope=' + this.value\">\n";
foreach ($envelopes as $env) {
$selected = ($env['envelope_name'] == $current_envelope) ? 'selected' : '';
echo "<option value=\"" . htmlspecialchars($env['envelope_name']) . "\" {$selected}>" . htmlspecialchars($env['envelope_name']) . " (" . ucfirst($env['color']) . ")</option>\n";
}
echo "</select>\n";
echo "<div class=\"mt-2\">\n";
echo "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" onclick=\"editEnvelope('" . htmlspecialchars($current_envelope) . "', '" . htmlspecialchars($current_envelope_color) . "')\">Edit Envelope</button>\n";
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
}
echo "</div>\n";
// Get CG points for current envelope
$cg_result = $db->query("SELECT * FROM aircraft_cg WHERE tailnumber = ? AND envelope_name = ?", [$aircraft['id'], $current_envelope]);
echo "<form method=\"post\" action=\"admin.php\" name=\"cg\">\n";
echo "<input type=\"hidden\" name=\"tailnumber\" value=\"" . $aircraft['id'] . "\">\n";
echo "<input type=\"hidden\" name=\"func\" value=\"aircraft\">\n";
echo "<input type=\"hidden\" name=\"func_do\" value=\"edit_do\">\n";
echo "<input type=\"hidden\" name=\"what\" value=\"cg\">\n";
echo "<input type=\"hidden\" name=\"envelope_name\" value=\"" . htmlspecialchars($current_envelope) . "\">\n";
// Pass envelope color if provided in URL (for new envelopes)
if (isset($_GET['envelope_color']) && !empty($_GET['envelope_color'])) {
echo "<input type=\"hidden\" name=\"envelope_color\" value=\"" . htmlspecialchars($_GET['envelope_color']) . "\">\n";
}
echo "<div class=\"table-responsive\">\n";
echo "<table class=\"table table-sm table-hover\">\n";
echo "<thead class=\"table-dark\">\n";
echo "<tr><th class=\"text-center\">Arm</th><th class=\"text-center\">Weight</th><th class=\"text-center\">Actions</th></tr>\n";
echo "</thead>\n";
echo "<tbody>\n";
while($cg = $db->fetchAssoc($cg_result)) {
echo "<tr>\n";
echo "<td class=\"text-center\">\n";
echo "<input type=\"number\" step=\"any\" name=\"cgarm" . $cg['id'] . "\" value=\"" . $cg['arm'] . "\" class=\"form-control form-control-sm text-center\" style=\"width: 100px; display: inline-block;\">\n";
echo "</td>\n";
echo "<td class=\"text-center\">\n";
echo "<input type=\"number\" step=\"any\" name=\"cgweight" . $cg['id'] . "\" value=\"" . $cg['weight'] . "\" class=\"form-control form-control-sm text-center\" style=\"width: 100px; display: inline-block;\">\n";
echo "</td>\n";
echo "<td class=\"text-center\">\n";
echo "<div class=\"btn-group btn-group-sm\" role=\"group\">\n";
echo "<button type=\"button\" class=\"btn btn-outline-primary\" onclick=\"updateCGPoint(" . $cg['id'] . ", " . $aircraft['id'] . ", '" . htmlspecialchars($current_envelope, ENT_QUOTES) . "')\">Update</button>\n";
echo "<button type=\"button\" class=\"btn btn-outline-danger\" onclick=\"deleteCGPoint(" . $cg['id'] . ", " . $aircraft['id'] . ")\">Delete</button>\n";
echo "</div>\n";
echo "</td>\n";
echo "</tr>\n";
}
// Add new CG point row
echo "<tr class=\"table-success\">\n";
echo "<td class=\"text-center\">\n";
echo "<input type=\"number\" step=\"any\" name=\"new_arm\" class=\"form-control form-control-sm text-center\" placeholder=\"Arm\" style=\"width: 100px; display: inline-block;\">\n";
echo "</td>\n";
echo "<td class=\"text-center\">\n";
echo "<input type=\"number\" step=\"any\" name=\"new_weight\" class=\"form-control form-control-sm text-center\" placeholder=\"Weight\" style=\"width: 100px; display: inline-block;\">\n";
echo "</td>\n";
echo "<td class=\"text-center\">\n";
echo "<button type=\"button\" class=\"btn btn-success btn-sm\" onclick=\"addCGPoint(" . $aircraft['id'] . ", '" . htmlspecialchars($current_envelope, ENT_QUOTES) . "', '" . $current_envelope_color . "')\">Add Point</button>\n";
echo "</td>\n";
echo "</tr>\n";
echo "</tbody>\n";
echo "</table>\n";
echo "</div>\n";
echo "</form>\n";
// CG Graph
echo "<div class=\"text-center mt-4\">\n";
echo "<embed src=\"scatter.php?size=small&tailnumber=" . $aircraft['id'] . "&envelope=" . urlencode($current_envelope) . "\" width=\"420\" height=\"220\" class=\"border rounded\">\n";
echo "</div>\n";
}
echo "</div>\n";
echo "</div>\n";
// New Envelope Modal
echo "<div class=\"modal fade\" id=\"newEnvelopeModal\" tabindex=\"-1\">\n";
echo "<div class=\"modal-dialog\">\n";
echo "<div class=\"modal-content\">\n";
echo "<div class=\"modal-header\">\n";
echo "<h5 class=\"modal-title\">Add New CG Envelope</h5>\n";
echo "<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>\n";
echo "</div>\n";
echo "<div class=\"modal-body\">\n";
echo "<div class=\"mb-3\">\n";
echo "<label for=\"envelope_name\" class=\"form-label\">Envelope Name</label>\n";
echo "<input type=\"text\" class=\"form-control\" id=\"envelope_name\" name=\"envelope_name\" placeholder=\"e.g., Normal, Utility, Aerobatic\" required>\n";
echo "</div>\n";
echo "<div class=\"mb-3\">\n";
echo "<label for=\"envelope_color\" class=\"form-label\">Color</label>\n";
echo "<select class=\"form-select\" id=\"envelope_color\" name=\"envelope_color\" required>\n";
// Get used colors to disable them
$used_colors = [];
foreach ($envelopes as $env) {
$used_colors[] = $env['color'];
}
$available_colors = [
'blue' => 'Blue',
'purple' => 'Purple',
'brown' => 'Brown',
'gray' => 'Gray',
'black' => 'Black',
'lime' => 'Lime',
'cyan' => 'Cyan',
'magenta' => 'Magenta',
'maroon' => 'Maroon',
'teal' => 'Teal'
];
foreach ($available_colors as $color_value => $color_name) {
$disabled = in_array($color_value, $used_colors) ? ' disabled' : '';
$suffix = in_array($color_value, $used_colors) ? ' (Already Used)' : '';
echo "<option value=\"{$color_value}\"{$disabled}>{$color_name}{$suffix}</option>\n";
}
echo "</select>\n";
echo "</div>\n";
echo "</div>\n";
echo "<div class=\"modal-footer\">\n";
echo "<button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button>\n";
echo "<button type=\"button\" class=\"btn btn-primary\" onclick=\"createEnvelope(" . $aircraft['id'] . ")\">Create Envelope</button>\n";
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
// Edit Envelope Modal
echo "<div class=\"modal fade\" id=\"editEnvelopeModal\" tabindex=\"-1\">\n";
echo "<div class=\"modal-dialog\">\n";
echo "<div class=\"modal-content\">\n";
echo "<div class=\"modal-header\">\n";
echo "<h5 class=\"modal-title\">Edit CG Envelope</h5>\n";
echo "<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>\n";
echo "</div>\n";
echo "<div class=\"modal-body\">\n";
echo "<input type=\"hidden\" id=\"edit_old_envelope_name\" value=\"\">\n";
echo "<div class=\"mb-3\">\n";
echo "<label for=\"edit_envelope_name\" class=\"form-label\">Envelope Name</label>\n";
echo "<input type=\"text\" class=\"form-control\" id=\"edit_envelope_name\" name=\"envelope_name\" required>\n";
echo "</div>\n";
echo "<div class=\"mb-3\">\n";
echo "<label for=\"edit_envelope_color\" class=\"form-label\">Color</label>\n";
echo "<select class=\"form-select\" id=\"edit_envelope_color\" name=\"envelope_color\" required>\n";
echo "<!-- Options will be populated dynamically by JavaScript -->\n";
echo "</select>\n";
echo "</div>\n";
echo "</div>\n";
echo "<div class=\"modal-footer\">\n";
echo "<button type=\"button\" class=\"btn btn-danger me-auto\" onclick=\"deleteCurrentEnvelope()\">Delete Envelope</button>\n";