File size: 38,198 Bytes
d9d886e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
const PdfPrinter = require('pdfmake')
const path = require('path')
const fs = require('fs')
const { calculateDistance } = require('../mathHelpers')
const generateGraph = require('./generateGraph')
const { processAltitudeScaling } = require('./altitudeScaler')

// Fungsi untuk membaca dan parse JSON metadata dengan error handling
const readJSONMetadata = (filePath) => {
  try {
    if (!fs.existsSync(filePath)) {
      console.warn(`Metadata file not found: ${filePath}`)
      return null
    }

    const fileContent = fs.readFileSync(filePath, 'utf8')

    if (!fileContent.trim()) {
      console.warn(`Metadata file is empty: ${filePath}`)
      return null
    }

    const jsonData = JSON.parse(fileContent)

    console.log(`Successfully read metadata from: ${filePath}`)
    return jsonData
  } catch (error) {
    console.error(`Error reading JSON metadata from ${filePath}:`, error.message)
    return null
  }
}

// Fungsi untuk mencari file metadata alternatif
const findMetadataFile = (mappingImageFolder) => {
  if (!mappingImageFolder || typeof mappingImageFolder !== 'string' || mappingImageFolder.trim() === '') {
    console.warn('Invalid mappingImageFolder provided for metadata search:', mappingImageFolder)
    return null
  }

  const cleanFolderName = mappingImageFolder.trim()
  const metadataFilePath = path.join(__dirname, '..', '..', 'ortho_results', cleanFolderName, `info_${cleanFolderName}.json`)

  if (fs.existsSync(metadataFilePath)) {
    console.log(`Found metadata file: ${metadataFilePath}`)
    return metadataFilePath
  }

  console.warn(`No metadata file found for: ${mappingImageFolder}`)
  console.log('Searched path:', metadataFilePath)
  return null
}

// Fungsi untuk mencari file VARI_classified JSON
const findVARIClassifiedFile = (mappingImageFolder) => {
  if (!mappingImageFolder || typeof mappingImageFolder !== 'string' || mappingImageFolder.trim() === '') {
    console.warn('Invalid mappingImageFolder provided for VARI search:', mappingImageFolder)
    return null
  }

  const cleanFolderName = mappingImageFolder.trim()

  const variFilePath = path.join(__dirname, '..', '..', 'ortho_results', cleanFolderName, `VARI_classified_${cleanFolderName}.json`)

  if (fs.existsSync(variFilePath)) {
    console.log(`Found VARI classified file: ${variFilePath}`)
    return variFilePath
  }

  console.warn(`No VARI classified file found for: ${mappingImageFolder}`)
  console.log('Searched VARI path:', variFilePath)
  return null
}

const readVARIClassificationData = (variFilePath) => {
  if (!variFilePath || !fs.existsSync(variFilePath)) {
    console.warn('VARI classification file not found or path invalid')
    return null
  }

  try {
    const rawData = fs.readFileSync(variFilePath, 'utf8')
    const parsedData = JSON.parse(rawData)

    console.log('Raw VARI data structure:', Object.keys(parsedData))

    return parsedData
  } catch (error) {
    console.error('Error reading VARI classification JSON:', error.message)
    return null
  }
}

const extractVARIMetrics = (variData) => {
  if (!variData) {
    return {
      index_mean: 'N/A',
      vegetasi_area_m2: 'N/A',
      vegetasi_percent: 'N/A',
      total_area_m2: 'N/A',
      vegetasi_pixels: 'N/A',
      total_pixels: 'N/A'
    }
  }

  const metrics = {
    index_mean: variData.index_mean || 'N/A',
    vegetasi_area_m2: variData.vegetasi_area_m2 || 'N/A',
    vegetasi_percent: variData.vegetasi_percent || 'N/A',
    total_area_m2: variData.total_area_m2 || 'N/A',
    vegetasi_pixels: variData.vegetasi_pixels || 'N/A',
    total_pixels: variData.total_pixels || 'N/A'
  }

  return metrics
}

// Fungsi untuk format VARI metrics untuk display di PDF
const formatVARIMetricsForDisplay = (metrics) => {
  const formatted = {
    indexMean: parseFloat(metrics.index_mean).toFixed(4),
    vegetasiAreaM2: parseFloat(metrics.vegetasi_area_m2).toFixed(4),
    vegetasiAreaM2Display: parseFloat(metrics.vegetasi_area_m2).toFixed(4),
    vegetasiPercent: parseFloat(metrics.vegetasi_percent).toFixed(4),
    totalAreaM2: parseFloat(metrics.total_area_m2).toFixed(4),
    vegetasiPixels: typeof metrics.vegetasi_pixels === 'number'
      ? metrics.vegetasi_pixels.toLocaleString('id-ID')
      : metrics.vegetasi_pixels,
    totalPixels: typeof metrics.total_pixels === 'number'
      ? metrics.total_pixels.toLocaleString('id-ID')
      : metrics.total_pixels
  }

  return formatted
}

// Fungsi untuk extract metadata dengan fallback values yang lebih baik
const extractMetadataFields = (jsonData, mappingImageFolder = null) => {
  if (!jsonData) {
    return {
      matcherType: 'N/A',
      reconstructionAlgorithm: 'N/A',
      coordinateSystem: 'N/A',
      colorsChannelBand: 'N/A',
      colorsChannelDtype: 'N/A',
      mosaicWidth: 'N/A',
      mosaicHeight: 'N/A'
    }
  }

  const metadata = {
    matcherType: jsonData.rec_parameter?.matcher_type || 'SIFT',
    reconstructionAlgorithm: jsonData.rec_parameter?.reconstruction_algorithm || 'Incremental SfM',
    coordinateSystem: jsonData.mosaic?.crs || 'EPSG:4326',
    colorsChannelBand: jsonData.mosaic?.band || '3',
    colorsChannelDtype: jsonData.mosaic?.dtype || 'uint8',
    mosaicWidth: jsonData.mosaic?.width || 'N/A',
    mosaicHeight: jsonData.mosaic?.height || 'N/A'
  }

  return metadata
}

// Fungsi untuk menghitung jarak menggunakan formula Haversine
const calculateHaversineDistance = (lat1, lon1, lat2, lon2) => {
  const R = 6371000 // Radius bumi dalam meter
  const φ1 = lat1 * Math.PI / 180 // Konversi ke radian
  const φ2 = lat2 * Math.PI / 180
  const Δφ = (lat2 - lat1) * Math.PI / 180
  const Δλ = (lon2 - lon1) * Math.PI / 180

  const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
            Math.cos(φ1) * Math.cos(φ2) *
            Math.sin(Δλ / 2) * Math.sin(Δλ / 2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))

  return R * c // Jarak dalam meter
}

// Fungsi untuk menghitung jarak 3D dengan mempertimbangkan altitude
const calculate3DDistance = (lat1, lon1, alt1, lat2, lon2, alt2) => {
  const horizontalDistance = calculateHaversineDistance(lat1, lon1, lat2, lon2)
  const verticalDistance = Math.abs(alt2 - alt1)

  // Menggunakan teorema Pythagoras untuk jarak 3D
  return Math.sqrt(horizontalDistance * horizontalDistance + verticalDistance * verticalDistance)
}

// Fungsi untuk validasi koordinat GPS
const isValidGPSCoordinate = (lat, lon, alt = null) => {
  // Validasi latitude (-90 to 90)
  if (lat < -90 || lat > 90) return false

  // Validasi longitude (-180 to 180)
  if (lon < -180 || lon > 180) return false

  // Koordinat (0,0) biasanya invalid kecuali benar-benar di Gulf of Guinea
  if (lat === 0 && lon === 0) return false

  // Validasi altitude jika ada (reasonable range: -500m to 50000m)
  if (alt !== null && (alt < -500 || alt > 50000)) return false

  return true
}

// Fungsi untuk format duration dari array [jam, menit, detik] langsung
const formatDurationFromArray = (durationArray) => {
  if (!Array.isArray(durationArray)) return 'N/A'

  const [hours = 0, minutes = 0, seconds = 0] = durationArray

  // Validasi dan konversi ke integer
  const numHours = Math.floor(typeof hours === 'number' ? hours : parseFloat(hours) || 0)
  const numMinutes = Math.floor(typeof minutes === 'number' ? minutes : parseFloat(minutes) || 0)
  const numSeconds = Math.floor(typeof seconds === 'number' ? seconds : parseFloat(seconds) || 0)

  console.log('Format array directly:', { numHours, numMinutes, numSeconds })

  // Buat array untuk bagian-bagian yang akan ditampilkan
  const parts = []

  if (numHours > 0) {
    parts.push(`${numHours} Jam`)
  }

  if (numMinutes > 0) {
    parts.push(`${numMinutes} Menit`)
  }

  if (numSeconds > 0) {
    parts.push(`${numSeconds} Detik`)
  }

  // Jika tidak ada bagian yang valid, kembalikan "0 Detik"
  if (parts.length === 0) {
    return '0 Detik'
  }

  // Gabungkan semua bagian dengan spasi
  return parts.join(' ')
}

// Fungsi untuk format duration untuk display dalam format Indonesia
const formatDuration = (durationInput) => {
  // Jika input adalah array, gunakan formatter array langsung
  if (Array.isArray(durationInput)) {
    return formatDurationFromArray(durationInput)
  }

  // Jika input adalah minutes (number), lakukan konversi
  const minutes = durationInput
  if (!minutes || minutes <= 0) return 'N/A'

  // Konversi total menit ke jam, menit, dan detik
  const totalSeconds = Math.round(minutes * 60)
  const hours = Math.floor(totalSeconds / 3600)
  const mins = Math.floor((totalSeconds % 3600) / 60)
  const secs = totalSeconds % 60

  // Buat array untuk bagian-bagian yang akan ditampilkan
  const parts = []

  if (hours > 0) {
    parts.push(`${hours} Jam`)
  }

  if (mins > 0) {
    parts.push(`${mins} Menit`)
  }

  if (secs > 0) {
    parts.push(`${secs} Detik`)
  }

  // Jika tidak ada bagian yang valid, kembalikan "0 Detik"
  if (parts.length === 0) {
    return '0 Detik'
  }

  // Gabungkan semua bagian dengan spasi
  return parts.join(' ')
}

// Define fonts for PDFMake
const fonts = {
  Helvetica: {
    normal: 'Helvetica',
    bold: 'Helvetica-Bold',
    italics: 'Helvetica-Oblique',
    bolditalics: 'Helvetica-BoldOblique'
  }
}

const printer = new PdfPrinter(fonts)

// Fungsi untuk menentukan kategori deforestasi berdasarkan persentase vegetasi dari data VARI
const analyzeDeforestationByIndex = (missionData) => {
  // Definisi kategori berdasarkan persentase vegetasi
  const categories = {
    AMAN: {
      name: 'Aman',
      color: '#22c55e', // green
      percentageRange: { min: 95, max: 100 }
    },
    SEDANG: {
      name: 'Penurunan Deforestasi Sedang',
      color: '#f59e0b', // amber
      percentageRange: { min: 50, max: 94.99 }
    },
    TINGGI: {
      name: 'Penurunan Vegetasi Tinggi',
      color: '#ef4444', // red
      percentageRange: { min: 0, max: 49.99 }
    }
  }

  // Dapatkan index_mean dari data VARI untuk variabel index
  let actualIndex = missionData?.variMetrics?.index_mean || null

  // Log sumber data index
  if (missionData?.variMetrics?.index_mean !== null && missionData?.variMetrics?.index_mean !== undefined) {
    console.log('Using VARI index_mean as deforestation index:', actualIndex)
  }

  // Jika tidak ada index_mean, gunakan nilai dummy untuk testing
  if (actualIndex === null || actualIndex === undefined) {
    console.warn('No index_mean provided from VARI, using dummy value -0.0137 for testing')
    actualIndex = -0.0137 // Dummy value untuk testing
  }

  // Validasi dan normalize index ke range -1 hingga 1
  actualIndex = Math.max(-1, Math.min(1, parseFloat(actualIndex) || 0))

  // Dapatkan persentase vegetasi dari data VARI
  let vegetasiPercent = missionData?.variMetrics?.vegetasi_percent || null

  // Log sumber data persentase vegetasi
  if (missionData?.variMetrics?.vegetasi_percent !== null && missionData?.variMetrics?.vegetasi_percent !== undefined) {
    console.log('Using VARI vegetasi_percent as vegetation percentage:', vegetasiPercent)
  }

  // Jika tidak ada data vegetasi_percent, gunakan nilai dummy untuk testing
  if (vegetasiPercent === null || vegetasiPercent === undefined) {
    console.warn('No vegetasi_percent provided from VARI, using dummy value 75.5 for testing')
    vegetasiPercent = 75.5 // Dummy value untuk testing (kategori SEDANG)
  }

  // Validasi dan normalize persentase ke range 0 hingga 100
  vegetasiPercent = Math.max(0, Math.min(100, parseFloat(vegetasiPercent) || 0))

  // Tentukan kategori berdasarkan persentase vegetasi
  let selectedCategory
  if (vegetasiPercent >= categories.AMAN.percentageRange.min) {
    selectedCategory = { ...categories.AMAN }
  } else if (vegetasiPercent >= categories.SEDANG.percentageRange.min) {
    selectedCategory = { ...categories.SEDANG }
  } else {
    selectedCategory = { ...categories.TINGGI }
  }

  console.log(`Deforestation analysis - Index: ${actualIndex.toFixed(4)}, Vegetasi Percent: ${vegetasiPercent.toFixed(2)}%, Category: ${selectedCategory.name}`)

  return {
    ...selectedCategory,
    index: actualIndex.toFixed(4),
    percentage: vegetasiPercent.toFixed(2),
    range: `${selectedCategory.percentageRange.min}% - ${selectedCategory.percentageRange.max}%`
  }
}

// Fungsi untuk mencari file gambar dengan format nama fixed
const findImageFile = (mappingImageFolder, imageType) => {
  let fileName, extension

  // Fixed filename patterns untuk setiap tipe image
  switch (imageType.toLowerCase()) {
    case 'chm':
      fileName = `chm.vis_${mappingImageFolder}`
      extension = '.jpg'
      break
    case 'dsm':
      fileName = `dsm.vis_${mappingImageFolder}`
      extension = '.jpg'
      break
    case 'contour':
      fileName = `contour_map_${mappingImageFolder}`
      extension = '.jpg'
      break
    case 'vari':
      fileName = `VARI_${mappingImageFolder}`
      extension = '.png'
      break
    case 'mosaic':
      fileName = `mosaic_${mappingImageFolder}`
      extension = '.png'
      break
    case 'segmentation':
      fileName = 'compared'
      extension = '.png'
      break
    default:
      console.warn(`Unknown image type: ${imageType}`)
      return null
  }

  // Path ke file image
  const filePath = path.join(
    __dirname, '..', '..',
    'ortho_results',
    mappingImageFolder,
    fileName + extension
  )

  if (fs.existsSync(filePath)) {
    console.log(`Found ${imageType.toUpperCase()} image: ${filePath}`)
    return filePath
  }

  console.warn(`${imageType.toUpperCase()} image not found: ${filePath}`)
  return null
}

// Fungsi untuk validasi dan info gambar yang ditemukan
const validateImageFile = (filePath, imageType) => {
  if (!filePath || !fs.existsSync(filePath)) {
    return {
      isValid: false,
      path: filePath,
      error: 'File not found',
      type: imageType
    }
  }

  try {
    const stats = fs.statSync(filePath)
    const fileSizeMB = (stats.size / (1024 * 1024)).toFixed(2)

    return {
      isValid: true,
      path: filePath,
      fileName: path.basename(filePath),
      fileSizeMB: parseFloat(fileSizeMB),
      type: imageType,
      lastModified: stats.mtime
    }
  } catch (error) {
    return {
      isValid: false,
      path: filePath,
      error: error.message,
      type: imageType
    }
  }
}

// Fungsi untuk format dan validasi metadata untuk display di PDF
const formatMetadataForDisplay = (metadata) => {
  const formatted = {
    matcherType: metadata.matcherType === 'N/A' ? 'SIFT (default)' : metadata.matcherType,
    reconstructionAlgorithm: metadata.reconstructionAlgorithm === 'N/A' ? 'Incremental SfM (default)' : metadata.reconstructionAlgorithm,
    coordinateSystem: metadata.coordinateSystem === 'N/A' ? 'WGS 84 (EPSG:4326)' : `WGS 84 (${metadata.coordinateSystem})`,
    colorsChannelBand: metadata.colorsChannelBand === 'N/A' ? '3 (RGB)' : `${metadata.colorsChannelBand}`,
    colorsChannelDtype: metadata.colorsChannelDtype === 'N/A' ? 'uint8' : metadata.colorsChannelDtype,
    mosaicSize: (metadata.mosaicWidth === 'N/A' || metadata.mosaicHeight === 'N/A')
      ? 'Size unknown'
      : `${metadata.mosaicWidth} x ${metadata.mosaicHeight}`,
    mosaicWidth: metadata.mosaicWidth,
    mosaicHeight: metadata.mosaicHeight
  }

  return formatted
}

const generatePDF = async (data, displayedData, responseCallback) => {
  try {
    // Maximum altitude with enhanced scaling
    const originalZs = data.plotInterface[8].mavData[0].data
    const altitudeScalingResult = processAltitudeScaling(originalZs, 54, {
      validateData: true,
      logProcess: true,
      includeInfo: true
    })

    // Use scaled data or fallback to original if scaling failed
    const zs = altitudeScalingResult.success ? altitudeScalingResult.scaledData : originalZs
    const maxAlt = Math.max(...zs)
    const originalMaxAlt = Math.max(...originalZs)

    console.log('=== Altitude Processing Summary ===')
    console.log('Original max altitude:', originalMaxAlt, 'Scaled max altitude:', maxAlt)
    if (altitudeScalingResult.summary) {
      console.log('Scaling summary:', altitudeScalingResult.summary)
    }
    if (altitudeScalingResult.warnings.length > 0) {
      console.warn('Altitude scaling warnings:', altitudeScalingResult.warnings)
    }

    // Displayed data from Export PDF Modal
    const {
      missionTitle,
      preVehicleBatteryVolt,
      preRemoteBatteryVolt,
      afterRemoteBatteryVolt,
      afterVehicleBatteryVolt,
      status,
      damagedComponents: damage,
      notes,
      logSource,
      autopilotType,
      duration,
      flightDateTime,
      vehicleType,
      mappingImage,
      mappingImageFolder,
      mappingImageType,
      mappingImageSize,
      motorType,
      propellerType,
      ESCType,
      batterySpec,
      receiverSpec
    } = displayedData

    // Distance calculation
    let globalPositionCategory = data.categories.find(
      (cat) => cat.category === 'POSITION_DATA'
    ) // Protobuf
    globalPositionCategory = globalPositionCategory || data.categories.find((cat) => cat.category === 'GLOBAL_POSITION_INT') // Mavlink

    let xs, ys
    if (globalPositionCategory.category === 'GLOBAL_POSITION_INT') {
      xs = globalPositionCategory.data.map((entry) => entry.mavData[0] / 1e5)
      ys = globalPositionCategory.data.map((entry) => entry.mavData[1] / 1e5)
    } else {
      xs = globalPositionCategory.data.map((entry) => entry.mavData[1] / 10)
      ys = globalPositionCategory.data.map((entry) => entry.mavData[2] / 10)
    }

    const totalDistance = () => {
      let total = 0
      const validPoints = []

      // Filter dan validasi data GPS
      for (let i = 0; i < Math.min(xs.length, ys.length, zs.length); i++) {
        const lat = xs[i]
        const lon = ys[i]
        const alt = zs[i]

        // Validasi koordinat GPS
        if (isValidGPSCoordinate(lat, lon, alt)) {
          validPoints.push({ lat, lon, alt, index: i })
        }
      }

      console.log(`Total GPS points: ${xs.length}, Valid points: ${validPoints.length}`)

      // Hitung jarak kumulatif antar titik valid
      for (let i = 0; i < validPoints.length - 1; i++) {
        const current = validPoints[i]
        const next = validPoints[i + 1]

        // Hitung jarak 3D antara dua titik
        const distance = calculate3DDistance(
          current.lat, current.lon, current.alt,
          next.lat, next.lon, next.alt
        )

        // Filter jarak yang terlalu besar (kemungkinan error GPS)
        // Maksimal 1000m antar titik untuk drone
        if (distance > 0 && distance < 1000) {
          total += distance
        } else if (distance >= 1000) {
          console.warn(`Skipping large distance: ${distance.toFixed(2)}m between points ${current.index} and ${next.index}`)
        }
      }

      console.log(`Total calculated distance: ${total.toFixed(2)}m`)
      return Math.round(total)
    }

    // Generate altitude graph with scaled data
    const dataWithScaledAltitude = {
      ...data,
      plotInterface: data.plotInterface.map((item, index) => {
        if (index === 8) { // Altitude data is at index 8
          return {
            ...item,
            mavData: [{
              ...item.mavData[0],
              data: zs // Use scaled altitude data
            }]
          }
        }
        return item
      })
    }
    const myChart = await generateGraph(dataWithScaledAltitude)

    // Search for mosaic image
    const imageMappingPath = findImageFile(mappingImageFolder, 'mosaic')
    const hasImageMapping = imageMappingPath !== null

    // Search for CHM image
    const imagechmPath = findImageFile(mappingImageFolder, 'chm')
    const chmValidation = validateImageFile(imagechmPath, 'chm')
    const hasImageChm = chmValidation.isValid

    // Search for Contour image
    const imageContourPath = findImageFile(mappingImageFolder, 'contour')
    const contourValidation = validateImageFile(imageContourPath, 'contour')
    const hasImageContour = contourValidation.isValid

    // Search for DSM image
    const imageDsmPath = findImageFile(mappingImageFolder, 'dsm')
    const dsmValidation = validateImageFile(imageDsmPath, 'dsm')
    const hasImageDsm = dsmValidation.isValid

    const imageVariPath = findImageFile(mappingImageFolder, 'vari')
    const variValidation = validateImageFile(imageVariPath, 'vari')
    const hasImageVari = variValidation.isValid

    // Search for Segmentation image
    const imageSegmentationPath = findImageFile(mappingImageFolder, 'segmentation')
    const segmentationValidation = validateImageFile(imageSegmentationPath, 'segmentation')
    const hasImageSegmentation = segmentationValidation.isValid

    // Try to find metadata file from multiple possible locations
    const metadataFilePath = findMetadataFile(mappingImageFolder)

    // Read and parse JSON metadata
    const metadataJson = metadataFilePath ? readJSONMetadata(metadataFilePath) : null

    // Extract metadata fields using enhanced extraction with multiple fallbacks
    const {
      matcherType,
      reconstructionAlgorithm,
      coordinateSystem,
      colorsChannelBand,
      colorsChannelDtype,
      mosaicWidth,
      mosaicHeight
    } = extractMetadataFields(metadataJson, mappingImageFolder)

    // Format metadata for display in PDF
    const formattedMetadata = formatMetadataForDisplay({
      matcherType,
      reconstructionAlgorithm,
      coordinateSystem,
      colorsChannelBand,
      colorsChannelDtype,
      mosaicWidth,
      mosaicHeight
    })

    // Try to find VARI classification file from multiple possible locations
    const variFilePath = findVARIClassifiedFile(mappingImageFolder)

    // Read and parse VARI classification data
    const variClassificationData = variFilePath ? readVARIClassificationData(variFilePath) : null

    // Extract VARI metrics using enhanced extraction with multiple fallbacks
    const {
      index_mean,
      vegetasi_area_m2,
      vegetasi_percent,
      total_area_m2,
      vegetasi_pixels,
      total_pixels
    } = extractVARIMetrics(variClassificationData)

    // Format VARI metrics for display in PDF
    const formattedVARIMetrics = formatVARIMetricsForDisplay({
      index_mean,
      vegetasi_area_m2,
      vegetasi_percent,
      total_area_m2,
      vegetasi_pixels,
      total_pixels
    })

    // Analyze deforestation status using vegetasi_percent from VARI data
    // Percentage scale: 0% to 100% based on vegetation coverage
    // TINGGI (Penurunan Vegetasi Tinggi): 0-49.99%, SEDANG: 50-94.99%, AMAN: 95-100%
    const deforestationAnalysis = analyzeDeforestationByIndex({
      displayedData,
      variMetrics: {
        index_mean,
        vegetasi_area_m2,
        vegetasi_percent,
        total_area_m2,
        vegetasi_pixels,
        total_pixels
      },
      totalDistance
    })

    console.log('displayedData object:', displayedData)

    // Create PDF document definition
    const docDefinition = {
      pageSize: 'A4',
      pageMargins: [60, 80, 60, 60],
      defaultStyle: {
        font: 'Helvetica',
        fontSize: 10
      },

      header: function () {
        return {
          columns: [
            {
              text: missionTitle || 'Test_Flight',
              alignment: 'left',
              margin: [60, 20, 0, 0],
              fontSize: 10,
              bold: true
            },
            {
              text: flightDateTime || new Date().toISOString(),
              alignment: 'right',
              margin: [0, 20, 60, 0],
              fontSize: 10
            }
          ]
        }
      },

      // footer: function (currentPage, pageCount) {
      //   return {
      //     columns: [
      //       { text: '', alignment: 'left', margin: [60, 0, 0, 20] },
      //       {
      //         text: `Page ${currentPage} of ${pageCount}`,
      //         alignment: 'right',
      //         margin: [0, 0, 60, 20],
      //         fontSize: 9,
      //         color: 'gray'
      //       }
      //     ]
      //   }
      // },

      content: [
        // Adhyasta Logo
        {
          image: path.join(__dirname, 'LogoGamaforce.png'),
          width: 150,
          alignment: 'center',
          margin: [0, 0, 0, 0]
        },

        // Title
        {
          text: 'MISSION SUMMARY',
          style: 'header',
          alignment: 'center',
          margin: [0, 10, 0, 30]
        },

        // General Info Section
        {
          text: 'General Info',
          style: 'sectionHeader',
          margin: [0, 0, 0, 10]
        },

        // General Info Table
        {
          style: 'tableStyle',
          table: {
            widths: ['40%', '60%'],
            body: [
              ['Mission name', missionTitle || 'Test_Flight'],
              ['Mission date', flightDateTime || new Date().toISOString()],
              ['Distance', `${totalDistance()} meter`],
              ['GPS Data Points', `${xs.length} total, ${xs.filter((x, i) => isValidGPSCoordinate(x, ys[i], zs[i])).length} valid`],
              ['Maximum altitude', `${maxAlt} meter`],
              // ['Altitude Range', `${Math.max(...zs) - Math.min(...zs)} meter`],
              // ['Min Altitude', `${Math.min(...zs)} meter`],
              ['Duration', formatDuration(duration) || 'N/A'],
              ['Vehicle', vehicleType || '-'],
              [
                'Vehicle Battery',
                `Before: ${preVehicleBatteryVolt || '-'} V, After: ${
                  afterVehicleBatteryVolt || '-'
                } V`
              ],
              [
                'Remote Battery',
                `Before: ${preRemoteBatteryVolt || '-'} V, After: ${
                  afterRemoteBatteryVolt || '-'
                } V`
              ],
              [
                'Damaged Components',
                damage && damage.trim() !== ''
                  ? damage
                  : 'No damage reported'
              ],
              ['Flight Status', status || 'Success']
            ]
          },
          layout: 'noBorders',
          margin: [0, 0, 0, 20]
        },

        // Orthomosaic Section
        {
          text: 'Orthomosaic',
          style: 'sectionHeader',
          margin: [0, 0, 0, 10]
        },
        // Orthomosaic Info Table
        {
          style: 'tableStyle',
          table: {
            widths: ['40%', '60%'],
            body: [
              ['Size', formattedMetadata.mosaicSize],
              ['Coordinate system', formattedMetadata.coordinateSystem],
              ['Colors', `${formattedMetadata.colorsChannelBand} bands, ${formattedMetadata.colorsChannelDtype}`],
              ['Date created', new Date().toISOString().replace('T', ' ').split('.')[0]],
              ['File size', mappingImageSize || 'N/A']
            ]
          },
          layout: 'noBorders',
          margin: [0, 0, 0, 0]
        },

        // Subsection title (Reconstruction Parameters)
        {
          text: 'Reconstruction Parameters',
          style: 'subsectionHeader',
          margin: [20, 0, 0, 6]
        },
        // Subsection table
        {
          style: 'tableStyle',
          table: {
            widths: ['40%', '60%'],
            body: [
              ['Blending mode', 'mosaic'],
              ['Enable hole filling', 'no'],
              ['Matcher type', formattedMetadata.matcherType],
              ['Reconstruction algorithm', formattedMetadata.reconstructionAlgorithm]
            ]
          },
          layout: 'noBorders',
          margin: [20, 0, 0, 20] // indentasi biar jelas child dari Orthomosaic
        },

        // Specification Section
        {
          text: 'Specifications',
          style: 'sectionHeader',
          margin: [0, 0, 0, 10]
        },
        {
          style: 'tableStyle',
          table: {
            widths: ['40%', '60%'],
            body: [
              ['Motor type', motorType || '-'],
              ['Propeller type', propellerType || '-'],
              ['ESC type', ESCType || '-'],
              ['Battery specification', batterySpec || '-'],
              ['Receiver specification', receiverSpec || '-']
            ]
          },
          layout: 'noBorders',
          margin: [0, 0, 0, 0]
        },

        // Page break for second page
        { text: '', pageBreak: 'before' },

        // Notes Section
        {
          text: 'Notes',
          style: 'sectionHeader',
          margin: [0, 0, 0, 10]
        },
        {
          style: 'tableStyle',
          table: {
            widths: ['40%', '60%'],
            body: [
              ['Notes', notes || '-'],
              ['Log source', logSource || '-'],
              ['Autopilot type', autopilotType || '-']
            ]
          },
          layout: 'noBorders',
          margin: [0, 0, 0, 30]
        },

        // Altitude graph section
        {
          text: 'Altitude graph',
          style: 'subheader',
          alignment: 'left',
          margin: [0, 0, 0, 10]
        },

        {
          image: myChart,
          fit: [475, 300],
          alignment: 'center',
          margin: [0, 0, 0, 20]
        },
        // VARI Vegetation Analysis Section
        {
          text: 'Analisis Vegetasi (VARI)',
          style: 'sectionHeader',
          margin: [0, 15, 0, 15]
        },

        // VARI Metrics Overview
        {
          style: 'tableStyle',
          table: {
            widths: ['40%', '60%'],
            body: [
              [
                { text: 'Metrik Vegetasi', style: 'tableHeader', colSpan: 2 },
                {}
              ],
              ['Area Vegetasi', `${formattedVARIMetrics.vegetasiAreaM2} m²`],
              ['Persentase Vegetasi', `${formattedVARIMetrics.vegetasiPercent} %`],
              ['Total Area Analisis', `${formattedVARIMetrics.totalAreaM2} m²`],
              ['Pixel Vegetasi', `${formattedVARIMetrics.vegetasiPixels}`],
              ['Total Pixel', `${formattedVARIMetrics.totalPixels}`]
            ]
          },
          layout: {
            hLineWidth: function (i, node) {
              return (i === 0 || i === node.table.body.length) ? 1 : 0.5
            },
            vLineWidth: function (i, node) {
              return (i === 0 || i === node.table.widths.length) ? 1 : 0.5
            },
            hLineColor: function (i, node) {
              return '#cccccc'
            },
            vLineColor: function (i, node) {
              return '#cccccc'
            }
          },
          margin: [0, 0, 0, 15]
        },

        // Deforestation Analysis Section
        {
          text: 'Analisis Tingkat Deforestasi',
          style: 'sectionHeader',
          margin: [0, 0, 0, 15]
        },

        // Status Overview
        {
          style: 'tableStyle',
          table: {
            widths: ['25%', '25%', '15%', '35%'],
            body: [
              [
                { text: 'Status Hutan', style: 'tableHeader' },
                { text: 'Indeks', style: 'tableHeader' },
                { text: 'Persentase', style: 'tableHeader' },
                { text: 'Keterangan', style: 'tableHeader' }
              ],
              [
                {
                  text: deforestationAnalysis.name,
                  color: deforestationAnalysis.color,
                  bold: true
                },
                `${deforestationAnalysis.index}`,
                // `${deforestationAnalysis.percentage}% (${deforestationAnalysis.range})`,
                `${deforestationAnalysis.percentage}%`,
                `Area dalam kondisi ${deforestationAnalysis.name.toLowerCase()}`
              ]
            ]
          },
          layout: {
            hLineWidth: function (i, node) {
              return (i === 0 || i === node.table.body.length) ? 1 : 0.5
            },
            vLineWidth: function (i, node) {
              return (i === 0 || i === node.table.widths.length) ? 1 : 0.5
            },
            hLineColor: function (i, node) {
              return '#cccccc'
            },
            vLineColor: function (i, node) {
              return '#cccccc'
            }
          },
          margin: [0, 0, 0, 20]
        },

        // AI Analysis Section (if available)
        ...(displayedData.aiAnalysis
          ? [
              {
                text: 'Analisis Gambar Komprehensif (AI)',
                style: 'subsectionHeader',
                margin: [0, 15, 0, 10]
              },
              {
                text: displayedData.aiAnalysis,
                fontSize: 10,
                lineHeight: 1.5,
                alignment: 'justify',
                margin: [0, 0, 0, 15]
              }
            ]
          : []),

        // Page break for third page
        { text: '', pageBreak: 'before' },

        // Mosaic Image section
        {
          text: 'Mosaic Image',
          style: 'header',
          alignment: 'left',
          margin: [0, 0, 0, 15]
        },

        hasImageMapping
          ? {
              image: imageMappingPath,
              fit: [475, 650],
              alignment: 'center',
              margin: [0, 0, 0, 20]
            }
          : {
              text: 'No image found',
              alignment: 'center',
              margin: [0, 0, 0, 30],
              fontSize: 10,
              color: 'gray'
            },

        { text: '', pageBreak: 'before' },

        {
          text: 'Visible Atmospherically Resistant Index (VARI)',
          style: 'header',
          alignment: 'left',
          margin: [0, 0, 0, 15]
        },

        hasImageVari
          ? {
              image: imageVariPath,
              fit: [475, 650],
              alignment: 'center',
              margin: [0, 0, 0, 20]
            }
          : {
              text: 'No image found',
              alignment: 'center',
              margin: [0, 0, 0, 30],
              fontSize: 10,
              color: 'gray'
            },

        { text: '', pageBreak: 'before' },

        {
          text: 'Digital Surface Model (DSM)',
          style: 'header',
          alignment: 'left',
          margin: [0, 0, 0, 15]
        },
        hasImageDsm
          ? {
              image: imageDsmPath,
              fit: [475, 650],
              alignment: 'center',
              margin: [0, 0, 0, 20]
            }
          : {
              text: 'No image found',
              alignment: 'center',
              margin: [0, 0, 0, 30],
              fontSize: 10,
              color: 'gray'
            },

        { text: '', pageBreak: 'before' },

        {
          text: 'Canopy Height Model (CHM)',
          style: 'header',
          alignment: 'left',
          margin: [0, 0, 0, 15]
        },
        hasImageChm
          ? {
              image: imagechmPath,
              fit: [475, 650],
              alignment: 'center',
              margin: [0, 0, 0, 20]
            }
          : {
              text: 'No image found',
              alignment: 'center',
              margin: [0, 0, 0, 30],
              fontSize: 10,
              color: 'gray'
            },

        { text: '', pageBreak: 'before' },

        {
          text: 'Contour Map',
          style: 'header',
          alignment: 'left',
          margin: [0, 0, 0, 15]
        },
        hasImageContour
          ? {
              image: imageContourPath,
              fit: [475, 650],
              alignment: 'center',
              margin: [0, 0, 0, 20]
            }
          : {
              text: 'No image found',
              alignment: 'center',
              margin: [0, 0, 0, 30],
              fontSize: 10,
              color: 'gray'
            },

        { text: '', pageBreak: 'before' },

        {
          text: 'Segmentation Result',
          style: 'header',
          alignment: 'left',
          margin: [0, 0, 0, 15]
        },
        hasImageSegmentation
          ? {
              image: imageSegmentationPath,
              fit: [475, 650],
              alignment: 'center',
              margin: [0, 0, 0, 20]
            }
          : {
              text: 'No image found',
              alignment: 'center',
              margin: [0, 0, 0, 30],
              fontSize: 10,
              color: 'gray'
            }

      ],

      styles: {
        header: {
          fontSize: 16,
          bold: true
        },
        sectionHeader: {
          fontSize: 12,
          bold: true,
          color: 'black'
        },
        subheader: {
          fontSize: 12,
          bold: true
        },
        tableStyle: {
          margin: [20, 5, 0, 15],
          fontSize: 10,
          lineHeight: 1.5
        },
        subsectionHeader: {
          fontSize: 11,
          bold: true,
          color: 'black'
        },
        tableHeader: {
          fontSize: 10,
          bold: true,
          color: 'white',
          fillColor: '#374151'
        },
        warningHeader: {
          fontSize: 12,
          bold: true,
          color: '#ef4444',
          background: '#fef2f2'
        },
        warningText: {
          fontSize: 10,
          italics: true,
          color: '#dc2626',
          margin: [20, 0, 20, 0]
        }
      }
    }

    // Generate PDF
    const pdfDoc = printer.createPdfKitDocument(docDefinition)
    const pdfPath = path.join(__dirname, '..', '..', 'output.pdf')
    const writeStream = fs.createWriteStream(pdfPath)

    pdfDoc.pipe(writeStream)
    pdfDoc.end()

    writeStream.on('finish', function () {
      console.log('PDF written to file:', pdfPath)
      const pdfFile = fs.createReadStream(pdfPath)
      const pdfBuffer = []
      pdfFile.on('data', (chunk) => {
        pdfBuffer.push(chunk)
      })
      pdfFile.on('end', () => {
        const pdfBufferData = Buffer.concat(pdfBuffer)
        responseCallback(pdfBufferData, null)
      })
    })

    writeStream.on('error', function (err) {
      console.error('Error writing PDF to file:', err)
      responseCallback(null, 'Error writing PDF to file')
    })
  } catch (err) {
    console.error('Error generating PDF:', err)
    responseCallback(null, 'Error generating PDF')
  }
}

module.exports = generatePDF