File size: 20,232 Bytes
73566f6
463dbc3
73566f6
86b4aeb
73566f6
463dbc3
 
 
 
 
 
73566f6
463dbc3
73566f6
 
 
 
 
463dbc3
6f093ab
 
86b4aeb
 
 
6f093ab
 
 
86b4aeb
6f093ab
 
 
 
 
86b4aeb
463dbc3
 
 
 
86b4aeb
463dbc3
 
86b4aeb
 
463dbc3
 
0dcd2ca
 
 
 
 
 
 
 
 
 
 
 
 
86b4aeb
73566f6
 
86b4aeb
 
 
 
 
 
 
 
 
 
 
 
463dbc3
73566f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
463dbc3
 
86b4aeb
 
 
0dcd2ca
 
86b4aeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73566f6
 
0dcd2ca
 
 
 
 
 
 
 
86b4aeb
73566f6
0dcd2ca
 
 
 
 
86b4aeb
 
73566f6
 
 
 
 
 
 
 
 
 
86b4aeb
73566f6
86b4aeb
73566f6
0dcd2ca
 
 
 
 
 
 
86b4aeb
0dcd2ca
463dbc3
 
86b4aeb
463dbc3
 
 
 
 
 
 
73566f6
 
86b4aeb
73566f6
 
 
86b4aeb
73566f6
 
463dbc3
86b4aeb
463dbc3
 
 
 
73566f6
 
 
86b4aeb
73566f6
 
86b4aeb
73566f6
 
 
 
 
 
 
 
 
 
86b4aeb
 
73566f6
 
 
 
 
 
 
 
 
 
 
 
 
86b4aeb
 
 
73566f6
 
463dbc3
 
86b4aeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
463dbc3
 
86b4aeb
 
 
 
 
 
 
 
 
 
 
 
463dbc3
 
 
 
86b4aeb
463dbc3
 
 
 
 
 
86b4aeb
463dbc3
 
86b4aeb
463dbc3
73566f6
86b4aeb
73566f6
 
 
 
 
 
 
86b4aeb
 
73566f6
 
 
86b4aeb
 
 
73566f6
86b4aeb
73566f6
 
86b4aeb
 
 
 
 
 
 
 
73566f6
 
86b4aeb
 
 
 
 
73566f6
 
 
 
 
86b4aeb
 
 
 
 
 
 
 
 
 
 
 
 
463dbc3
 
86b4aeb
 
463dbc3
86b4aeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dcd2ca
86b4aeb
 
0dcd2ca
86b4aeb
 
 
 
 
 
 
 
 
0dcd2ca
 
86b4aeb
 
 
 
 
 
 
 
 
 
 
 
 
0dcd2ca
86b4aeb
 
 
6f093ab
86b4aeb
 
 
 
 
 
 
 
 
 
 
 
 
 
6f093ab
 
 
86b4aeb
 
 
 
 
 
 
 
 
 
6f093ab
86b4aeb
 
 
6f093ab
 
86b4aeb
 
 
 
 
 
 
 
 
 
 
 
6f093ab
86b4aeb
 
 
 
6f093ab
86b4aeb
 
 
 
 
 
 
6f093ab
86b4aeb
 
 
 
 
 
 
 
 
 
 
6f093ab
 
86b4aeb
 
 
 
 
6f093ab
73566f6
86b4aeb
 
73566f6
 
86b4aeb
 
73566f6
463dbc3
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
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { CaseStoreService, PoliceCase } from '../shared/case-store.service';
import { INFOPAGE_SECTIONS } from '../shared/infopage-sections';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-recordpage',
  templateUrl: './recordpage.component.html',
  styleUrls: ['./recordpage.component.css']
})
export class RecordpageComponent implements OnInit, OnDestroy {
  cases: PoliceCase[] = [];
  private casesSub?: Subscription;

  // Date field groups for formatting
  dateTimeFields = new Set<string>(['Date & Time (Entry)', 'Occurred From', 'Occurred To', 'Time Reported', 'Time Discovered']);
  dateFields = new Set<string>(['Follow-up Date', 'Next Hearing Date']);

  // Pagination
  currentPage: number = 1;
  pageSize: number = 5;
  pageSizeOptions: number[] = [5, 10, 20, 50];

  get totalPages(): number {
    return Math.ceil(this.filteredCases.length / this.pageSize) || 1;
  }

  get pagedCases(): PoliceCase[] {
    const start = (this.currentPage - 1) * this.pageSize;
    return this.filteredCases.slice(start, start + this.pageSize);
  }

  // Modal state
  showDetails = false;
  selectedCase: PoliceCase | null = null;
  selectedIndex = -1;

  // Search query
  q = '';

  // Sorting
  sortKey: 'caseId' | 'crime' | 'dateTime' | 'status' | 'Investigation Officer' = 'dateTime';
  sortDir: 'asc' | 'desc' = 'desc';

  // Filter state
  filterCrimeType: string = '';
  filterStatus: string = '';
  filterLocation: string = '';
  filterOfficer: string = '';

  crimeTypes: string[] = [];
  statusTypes: string[] = [];
  locations: string[] = [];
  officers: string[] = [];

  filteredCases: PoliceCase[] = [];

  // Selection state
  allSelected: boolean = false;

  // For modal subgroup pills
  selectedSubgroup: any = {
    crime: 'Identification & Timing',
    suspect: 'Identity',
    notes: 'Investigation Notes'
  };

  // Reference infopage section/subgroup/fields structure
  sections = INFOPAGE_SECTIONS;

  constructor(private caseStore: CaseStoreService, private router: Router) { }

  ngOnInit(): void {
    if (typeof this.caseStore.getCases$ === 'function') {
      this.casesSub = this.caseStore.getCases$().subscribe((cases: PoliceCase[]) => {
        this.cases = cases || [];
        this.cases.forEach((c: any) => { if (c.selected === undefined) c.selected = false; });
        this.populateFilterOptions();
        this.applyFilters();
        this.applySort();
      });
    } else {
      this.load();
      this.populateFilterOptions();
      this.applyFilters();
      this.applySort();
    }
  }

  ngOnDestroy(): void {
    if (this.casesSub) this.casesSub.unsubscribe();
  }

  // Helper methods
  getSubgroups(sectionKey: string): string[] {
    return Object.keys(this.sections[sectionKey]?.subgroups || {});
  }

  getFieldsForSubgroup(sectionKey: string, subgroup: string): string[] {
    return this.sections[sectionKey]?.subgroups[subgroup] || [];
  }

  selectSubgroup(sectionKey: string, subgroup: string) {
    this.selectedSubgroup[sectionKey] = subgroup;
  }

  // Case statistics
  get totalCases(): number {
    return this.cases.length;
  }

  get openCases(): number {
    return this.cases.filter(c => c.status === 'Open').length;
  }

  get closedCases(): number {
    return this.cases.filter(c => c.status === 'Closed').length;
  }

  // Table rows getter
  get rows(): PoliceCase[] {
    return this.pagedCases;
  }

  // Pagination results
  get resultsStart(): number {
    return this.filteredCases.length === 0 ? 0 : (this.currentPage - 1) * this.pageSize + 1;
  }

  get resultsEnd(): number {
    return Math.min(this.currentPage * this.pageSize, this.filteredCases.length);
  }

  get resultsTotal(): number {
    return this.filteredCases.length;
  }

  // Navigation methods
  navigateHome(): void {
    this.router.navigate(['/']);
  }

  navigateBackToInfoPage(): void {
    this.router.navigate(['/infopage']);
  }

  logout(): void {
    // Implement proper logout logic
    localStorage.clear();
    sessionStorage.clear();
    this.router.navigate(['/login']);
  }

  // Data loading and filtering
  load(): void {
    this.cases = this.caseStore.getPoliceCases();
    this.cases.forEach((c: any) => { if (c.selected === undefined) c.selected = false; });
    this.populateFilterOptions();
    this.applyFilters();
  }

  populateFilterOptions() {
    this.crimeTypes = [...new Set(this.cases.map(c => c.crime).filter(Boolean))] as string[];
    this.statusTypes = [...new Set(this.cases.map(c => c.status).filter(Boolean))] as string[];
    this.locations = [...new Set(this.cases.map(c => c.police?.address).filter(Boolean))] as string[];
    this.officers = [...new Set(this.cases.map(c => c.police?.name).filter(Boolean))] as string[];
  }

  applyFilters() {
    // Filter by dropdowns
    let filtered = this.cases.filter(c =>
      (!this.filterCrimeType || c.crime === this.filterCrimeType) &&
      (!this.filterStatus || c.status === this.filterStatus) &&
      (!this.filterLocation || c.police?.address === this.filterLocation) &&
      (!this.filterOfficer || c.police?.name === this.filterOfficer)
    );

    // Filter by search query
    const s = (this.q || '').toLowerCase();
    if (s) {
      filtered = filtered.filter(c =>
        (c.caseId || '').toString().toLowerCase().includes(s) ||
        (c.crime || '').toLowerCase().includes(s) ||
        (c.police?.address || '').toLowerCase().includes(s) ||
        (c.status || '').toLowerCase().includes(s) ||
        (c.police?.name || '').toLowerCase().includes(s)
      );
    }

    this.filteredCases = filtered;
    this.currentPage = 1;
    this.applySort();
  }

  resetFilters() {
    this.filterCrimeType = '';
    this.filterStatus = '';
    this.filterLocation = '';
    this.filterOfficer = '';
    this.q = '';
    this.applyFilters();
  }

  // Sorting methods
  setSort(key: typeof this.sortKey) {
    if (this.sortKey === key) {
      this.sortDir = this.sortDir === 'asc' ? 'desc' : 'asc';
    } else {
      this.sortKey = key;
      this.sortDir = key === 'dateTime' ? 'desc' : 'asc';
    }
    this.applySort();
  }

  isAsc(key: typeof this.sortKey) {
    return this.sortKey === key && this.sortDir === 'asc';
  }

  isDesc(key: typeof this.sortKey) {
    return this.sortKey === key && this.sortDir === 'desc';
  }

  ariaSort(key: typeof this.sortKey) {
    return this.sortKey === key ? (this.sortDir === 'asc' ? 'ascending' : 'descending') : 'none';
  }

  applySort() {
    const key = this.sortKey;
    const dir = this.sortDir;

    this.filteredCases.sort((a, b) => {
      let aVal: any, bVal: any;

      switch (key) {
        case 'caseId':
          aVal = a.caseId || '';
          bVal = b.caseId || '';
          break;
        case 'crime':
          aVal = a.crime || '';
          bVal = b.crime || '';
          break;
        case 'dateTime':
          aVal = a.dateTime ? new Date(a.dateTime).getTime() : 0;
          bVal = b.dateTime ? new Date(b.dateTime).getTime() : 0;
          break;
        case 'status':
          aVal = a.status || '';
          bVal = b.status || '';
          break;
        case 'Investigation Officer':
          aVal = a.police?.name || '';
          bVal = b.police?.name || '';
          break;
        default:
          aVal = '';
          bVal = '';
      }

      if (aVal < bVal) return dir === 'asc' ? -1 : 1;
      if (aVal > bVal) return dir === 'asc' ? 1 : -1;
      return 0;
    });
  }

  // Pagination methods
  setPage(page: number) {
    if (page < 1 || page > this.totalPages) return;
    this.currentPage = page;
  }

  nextPage() {
    this.setPage(this.currentPage + 1);
  }

  prevPage() {
    this.setPage(this.currentPage - 1);
  }

  getPagination(): (number | string)[] {
    const pages: (number | string)[] = [];
    const total = this.totalPages;

    if (total <= 7) {
      for (let i = 1; i <= total; i++) pages.push(i);
    } else {
      if (this.currentPage <= 4) {
        for (let i = 1; i <= 5; i++) pages.push(i);
        pages.push('...');
        pages.push(total);
      } else if (this.currentPage >= total - 3) {
        pages.push(1);
        pages.push('...');
        for (let i = total - 4; i <= total; i++) pages.push(i);
      } else {
        pages.push(1);
        pages.push('...');
        for (let i = this.currentPage - 1; i <= this.currentPage + 1; i++) pages.push(i);
        pages.push('...');
        pages.push(total);
      }
    }

    return pages;
  }

  goToPage(page: string | number) {
    if (typeof page === 'number') {
      this.setPage(page);
    }
  }

  onPageSizeChange(size: number) {
    this.pageSize = size;
    this.currentPage = 1;
  }

  // Modal methods
  openDetails(c: PoliceCase, i: number): void {
    this.selectedCase = c;
    this.selectedIndex = i;
    this.showDetails = true;
    document.body.style.overflow = 'hidden';
  }

  closeDetails(): void {
    this.showDetails = false;
    this.selectedCase = null;
    this.selectedIndex = -1;
    document.body.style.overflow = 'auto';
  }

  // Case actions
  editCase(c: PoliceCase, i: number): void {
    const prefill: Record<string, any> = {};

    try {
      const fd = (c as any).formData;
      if (fd && Array.isArray(fd)) {
        (fd as Array<any>).forEach(kv => { if (kv && kv.key) prefill[kv.key] = kv.value; });
      } else if (fd && typeof fd === 'object') {
        Object.assign(prefill, fd as Record<string, any>);
      }

      // Include mapped top-level properties
      if (c.caseId) prefill['Case ID'] = c.caseId;
      if (c.crime) prefill['Crime Type'] = c.crime;
      if (c.dateTime) prefill['Date & Time (Entry)'] = c.dateTime;
      if (c.police?.address) prefill['Location'] = c.police.address;
      if (c.police?.name) prefill['Investigating Officer'] = c.police.name;
      if (c.accused?.name) prefill['Suspect Name'] = c.accused.name;
    } catch (e) {
      console.error('Error preparing edit data:', e);
    }

    this.router.navigate(['/infopage', c.caseId], {
      state: {
        from: 'record',
        returnId: c.caseId,
        prefillFormData: prefill,
        case: c
      }
    });
  }

  deleteCase(index: number): void {
    if (confirm('Are you sure you want to delete this case?')) {
      this.caseStore.deletePoliceCaseAt(index);
      this.load();
    }
  }

  navigateToCaseDetails(c: PoliceCase): void {
    if (!c || !c.caseId) return;

    const origin = this.router.url.includes('/case-details') ? 'case-details' : 'record';

    this.router.navigate(['/case-details-summary-page', c.caseId], {
      queryParams: {
        from: origin,
        returnId: c.caseId
      },
      state: {
        case: c,
        from: origin,
        returnId: c.caseId
      }
    });
  }

  // Field value getters for modal
  objectKeys = Object.keys;

  getFieldValue(sc: any, sectionKey: string, field: string): any {
    const fieldMap: { [key: string]: string | string[] } = {
      // Crime Details
      'Case ID': 'caseId',
      'FIR / Ref #': 'firRef',
      'Crime Type': 'crime',
      'Case Category': 'caseCategory',
      'Date & Time (Entry)': 'dateTime',
      'Occurred From': 'occurredFrom',
      'Occurred To': 'occurredTo',
      'Time Reported': 'timeReported',
      'Time Discovered': 'timeDiscovered',
      'Country': 'country',
      'State': 'state',
      'District': 'district',
      'Number of Victims': 'numberOfVictims',
      'Brief Description': 'briefDescription',
      'Location': ['police', 'address'],
      'Jurisdiction / PS': 'jurisdiction',
      'Scene Type': 'sceneType',
      'Reported By': 'reportedBy',
      'Reported Contact': 'reportedContact',
      'Witness Count': 'witnessCount',
      'Victim Name': 'victimName',
      'Victim Contact': 'victimContact',
      'Victim Summary': 'victimSummary',
      'Suspected Offender Known?': 'suspectedOffenderKnown',
      'Suspect Link': 'suspectLink',
      'Legal Sections / Charges': 'legalSections',
      'Offence Category': 'offenceCategory',
      'Offence Description': 'offenceDescription',
      'Suspected Motive': 'suspectedMotive',
      'Confirmed Motive': 'confirmedMotive',
      'Weapon Involved': 'weaponInvolved',
      'Property Loss / Damage': 'propertyLoss',
      'Evidence Collected': 'evidenceCollected',
      'Forensic Tests Required': 'forensicTestsRequired',
      'Scene Condition': 'sceneCondition',
      'Photos / Video?': 'photosVideo',
      'CCTV Present?': 'cctvPresent',
      'CCTV Sources / IDs': 'cctvSources',
      'Physical Evidence (list)': 'physicalEvidence',
      'Chain of Custody?': 'chainOfCustody',
      'Digital Evidence': 'digitalEvidence',
      'Evidence Storage Reference': 'evidenceStorageReference',
      'Investigating Officer': ['police', 'name'],
      'Duty Person': ['police', 'dutyPerson'],
      'Supervising Officer': ['police', 'supervisingOfficer'],
      'Patrol Notes': ['police', 'patrolNotes'],
      'Arrest Made': 'arrestMade',
      'Arrest Location': 'arrestLocation',
      'Initial Actions Taken': 'initialActionsTaken',
      'riskLevel': 'riskLevel',
      'Confidentiality': 'confidentiality',
      'Biometric / Forensic IDs': 'biometricIds',
      'DNA Ref ID': 'dnaRefId',
      'Fingerprint ID': 'fingerprintId',
      'Case Status': 'status',
      'Linked Cases': 'linkedCases',
      'arrestCount': 'arrestCount',
      'Case Priority': 'casePriority',
      'Follow-up Date': 'followUpDate',
      'Court Case ID': 'courtCaseId',
      'Next Hearing Date': 'nextHearingDate',
      'Final Summary': 'finalSummary',
      'Remark': 'remark',
      // Suspect Details
      'Suspect ID': ['accused', 'suspectId'],
      'Suspect Name': ['accused', 'name'],
      'Alias / Nickname': ['accused', 'alias'],
      'Age': ['accused', 'age'],
      'Gender': ['accused', 'gender'],
      'Nationality': ['accused', 'nationality'],
      'Nationality ID / Passport Number': ['accused', 'passportNumber'],
      'Languages': ['accused', 'languages'],
      'Address': ['accused', 'address'],
      'Known Aliases': ['accused', 'knownAliases'],
      'Government ID': ['accused', 'governmentId'],
      'Height (cm)': ['accused', 'height'],
      'Weight (kg)': ['accused', 'weight'],
      'Build': ['accused', 'build'],
      'Hair Color': ['accused', 'hairColor'],
      'Eye Color': ['accused', 'eyeColor'],
      'Distinguishing Marks': ['accused', 'distinguishingMarks'],
      'Tattoo Details': ['accused', 'tattooDetails'],
      'Scar Details': ['accused', 'scarDetails'],
      'Photo Upload': ['accused', 'photoUpload'],
      'Employment': ['accused', 'employment'],
      'Education': ['accused', 'education'],
      'Occupation': ['accused', 'occupation'],
      'Company': ['accused', 'company'],
      'Workplace Address': ['accused', 'workplaceAddress'],
      'Marital Status': ['accused', 'maritalStatus'],
      'Known Habits': ['accused', 'knownHabits'],
      'Known Financial Details': ['accused', 'knownFinancialDetails'],
      'Associate Names': ['accused', 'associateNames'],
      'Gang Affiliation': ['accused', 'gangAffiliation'],
      'Family Connections': ['accused', 'familyConnections'],
      'Social Media Handles': ['accused', 'socialMediaHandles'],
      'Criminal History': ['accused', 'criminalHistory'],
      'Prior Arrests': ['accused', 'priorArrests'],
      'Probation/Parole Status': ['accused', 'probationStatus'],
      // Notes/Evidence
      'Initial Findings': ['police', 'information'],
      'Detailed Notes': ['notes', 'detailedNotes'],
      'Status': 'status',
      'Version History / Updates': ['notes', 'versionHistory'],
      'Evidence Photos': ['legal', 'evidencePhotos'],
      'Evidence Videos': ['legal', 'evidenceVideos'],
      'Evidence Documents': ['legal', 'evidenceDocuments'],
      'Links to Evidence': ['legal', 'linksToEvidence'],
      'Final Recommendations': ['legal', 'finalRecommendations'],
      'Witness Statements': ['legal', 'witnessStatements'],
      'Confessions': ['legal', 'confessions'],
      // Audit Fields
      'Created By': 'createdBy',
      'Creation Date': 'creationDate',
      'Last Updated': 'lastUpdated',
      'Verified By': 'verifiedBy'
    };

    const path = fieldMap[field] || field;
    let value: any = undefined;

    if (Array.isArray(path)) {
      let v = sc;
      for (const p of path) {
        if (v && v[p] !== undefined) v = v[p];
        else { v = undefined; break; }
      }
      value = v;
    } else {
      value = sc && sc[path] !== undefined ? sc[path] : undefined;
    }

    // Try to find in formData
    if (value === null || value === undefined || value === '') {
      try {
        const fd = this.getFormDataArray(sc);
        const norm = (s: any) => {
          if (s === null || s === undefined) return '';
          let t = String(s).toLowerCase();
          t = t.replace(/&/g, '');
          t = t.replace(/and/g, '');
          t = t.replace(/entry/g, '');
          t = t.replace(/\s+/g, '');
          return t.replace(/[^a-z0-9]/g, '');
        };

        if (fd && fd.length) {
          let kv = fd.find(k => k && String(k.key).toLowerCase() === String(field).toLowerCase());
          if (kv) value = kv.value;

          if (value === null || value === undefined || value === '') {
            const fieldNorm = norm(field);
            const pathName = Array.isArray(path) ? path[path.length - 1] : String(path);
            const pathNorm = norm(pathName);
            kv = fd.find(k => k && (norm(k.key) === fieldNorm || norm(k.key) === pathNorm));
            if (kv) value = kv.value;
          }
        }

        if ((value === null || value === undefined || value === '') && sc && sc.formData && typeof sc.formData === 'object') {
          if (sc.formData[field] !== undefined) value = sc.formData[field];
        }
      } catch (e) {
        // ignore
      }
    }

    // Normalize and format
    if (value === null || value === undefined || value === '') return 'Not Assigned';

    // Date formatting
    if (this.dateTimeFields.has(field) || this.dateFields.has(field)) {
      const d = new Date(value);
      if (!isNaN(d.getTime())) {
        if (this.dateFields.has(field)) return d.toISOString().slice(0, 10);
        return d.toLocaleString();
      }
    }

    if (typeof value === 'object') return this.formatFormValue(value);
    return value;
  }

  getValue(obj: any, key: string): any {
    const v = obj && obj[key] !== undefined ? obj[key] : undefined;
    if (v === null || v === undefined || v === '') return 'Not Assigned';
    if (typeof v === 'object') return this.formatFormValue(v);
    if (this.dateTimeFields.has(key) || this.dateFields.has(key)) {
      const d = new Date(v);
      if (!isNaN(d.getTime())) {
        if (this.dateFields.has(key)) return d.toISOString().slice(0, 10);
        return d.toLocaleString();
      }
    }
    return v;
  }

  // Form data helpers
  isFormDataArray(fd: any): boolean {
    return Array.isArray(fd) && fd.length > 0 && fd.every((item: any) => item && Object.prototype.hasOwnProperty.call(item, 'key'));
  }

  getFormDataArray(caseObj: any): Array<{ key: string; value: any }> {
    if (!caseObj || !caseObj.formData) return [];
    const fd = caseObj.formData;
    if (this.isFormDataArray(fd)) return fd as Array<{ key: string; value: any }>;
    if (typeof fd === 'object') return Object.keys(fd).map(k => ({ key: k, value: fd[k] }));
    return [{ key: 'value', value: fd }];
  }

  formatFormValue(value: any): string {
    if (value === null || value === undefined || value === '') return 'Not Assigned';
    if (typeof value === 'object') {
      try {
        return JSON.stringify(value, null, 2);
      } catch {
        return String(value);
      }
    }
    return String(value);
  }

  // Other methods
  toggleSelectAll(event: Event): void {
    const checked = (event.target as HTMLInputElement).checked;
    this.allSelected = checked;
    this.rows.forEach((c: any) => c.selected = checked);
  }

  onModernSearch() {
    return false;
  }

  goToDetect(caseId: string): void {
    this.router.navigate(['/py-detect'], { state: { caseId } });
  }
}