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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ContactManagementAPI.Data;
using ContactManagementAPI.Models;
using ContactManagementAPI.Services;
using ContactManagementAPI.Security;
using System.Globalization;

namespace ContactManagementAPI.Controllers
{
    public class HomeController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly FileUploadService _fileUploadService;
        private readonly ImportExportService _importExportService;
        private readonly ContactStatisticsService _statisticsService;
        private readonly UserContextService _userContextService;
        private readonly AdminHistoryService _adminHistoryService;

        public HomeController(
            ApplicationDbContext context,
            FileUploadService fileUploadService,
            ImportExportService importExportService,
            ContactStatisticsService statisticsService,
            UserContextService userContextService,
            AdminHistoryService adminHistoryService)
        {
            _context = context;
            _fileUploadService = fileUploadService;
            _importExportService = importExportService;
            _statisticsService = statisticsService;
            _userContextService = userContextService;
            _adminHistoryService = adminHistoryService;
        }

        // GET: Home/Index - Display all contacts with search functionality
        [RequireRight(RightsCatalog.ContactsView)]
        public async Task<IActionResult> Index(string searchTerm = "")
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            var contacts = ApplyContactScope(
                    _context.Contacts
                        .Include(c => c.Group)
                        .AsQueryable(),
                    currentUser)
                .AsQueryable();

            if (!string.IsNullOrEmpty(searchTerm))
            {
                contacts = contacts.Where(c =>
                    c.FirstName.Contains(searchTerm) ||
                    (c.LastName != null && c.LastName.Contains(searchTerm)) ||
                    (c.Email != null && c.Email.Contains(searchTerm)) ||
                    (c.Mobile1 != null && c.Mobile1.Contains(searchTerm)) ||
                    (c.Mobile2 != null && c.Mobile2.Contains(searchTerm)) ||
                    (c.Mobile3 != null && c.Mobile3.Contains(searchTerm)));
            }

            ViewBag.SearchTerm = searchTerm;
            return View(await contacts.OrderByDescending(c => c.UpdatedAt).ToListAsync());
        }

        // GET: Home/Details/5
        [RequireRight(RightsCatalog.ContactsView)]
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
                return NotFound();

            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            var contact = await _context.Contacts
                .Include(c => c.Group)
                .Include(c => c.Photos)
                .Include(c => c.Documents)
                .Include(c => c.BankAccounts)
                .FirstOrDefaultAsync(c => c.Id == id);

            if (contact == null)
                return NotFound();

            if (!CanAccessContact(currentUser, contact))
            {
                TempData["ErrorMessage"] = "You can view only contacts from your group.";
                return RedirectToAction(nameof(Index));
            }

            return View(contact);
        }

        // GET: Home/Create
        [RequireRight(RightsCatalog.ContactsCreate)]
        public IActionResult Create()
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            PopulateFormData();

            if (!currentUser.IsAdmin)
            {
                var scopedContactGroupId = ResolveContactGroupIdForUser(currentUser);
                if (scopedContactGroupId.HasValue)
                {
                    ViewData["ForcedGroupId"] = scopedContactGroupId.Value;
                }
            }

            return View();
        }

        // POST: Home/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [RequireRight(RightsCatalog.ContactsCreate)]
        public async Task<IActionResult> Create([Bind("FirstName,LastName,NickName,Gender,DateOfBirth,Email,Mobile1,Mobile2,Mobile3,WhatsAppNumber,PassportNumber,PanNumber,AadharNumber,DrivingLicenseNumber,VotersId,Address,City,State,PostalCode,Country,GroupId,OtherDetails")] Contact contact, List<ContactBankAccount>? bankAccounts, IFormFile? profilePhoto)
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            if (!currentUser.IsAdmin)
            {
                var scopedContactGroupId = ResolveContactGroupIdForUser(currentUser);
                if (!scopedContactGroupId.HasValue)
                {
                    ModelState.AddModelError(nameof(Contact.GroupId), "Your account is not assigned to a contact group.");
                }
                else
                {
                    contact.GroupId = scopedContactGroupId.Value;
                }
            }

            NormalizeOptionalBankAccountModelState();
            ValidateDuplicateContact(contact);

            if (ModelState.IsValid)
            {
                contact.CreatedAt = DateTime.Now;
                contact.UpdatedAt = DateTime.Now;

                var preparedBankAccounts = PrepareBankAccounts(bankAccounts);
                SyncLegacyBankFields(contact, preparedBankAccounts.FirstOrDefault());
                
                // Save contact first to get the ID
                _context.Add(contact);
                await _context.SaveChangesAsync();

                if (preparedBankAccounts.Any())
                {
                    foreach (var bankAccount in preparedBankAccounts)
                    {
                        bankAccount.ContactId = contact.Id;
                    }

                    _context.ContactBankAccounts.AddRange(preparedBankAccounts);
                    await _context.SaveChangesAsync();
                }
                
                // Handle profile photo upload after we have the contact ID
                if (profilePhoto != null)
                {
                    var result = await _fileUploadService.UploadPhotoAsync(profilePhoto, contact.Id);
                    if (result.Success)
                    {
                        contact.PhotoPath = result.FilePath;
                        _context.Update(contact);
                        await _context.SaveChangesAsync();
                    }
                }

                _adminHistoryService.Log(
                    actionType: "Create",
                    entityType: "Contact",
                    entityId: contact.Id,
                    performedBy: _userContextService.CurrentUser?.UserName ?? "Unknown",
                    details: $"Created contact '{contact.FirstName} {contact.LastName}'.");
                
                TempData["SuccessMessage"] = "Contact created successfully!";
                return RedirectToAction(nameof(Details), new { id = contact.Id });
            }
            PopulateFormData(contact, PrepareBankAccounts(bankAccounts));
            return View(contact);
        }

        // GET: Home/Edit/5
        [RequireRight(RightsCatalog.ContactsEdit)]
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
                return NotFound();

            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            if (!currentUser.IsAdmin)
            {
                TempData["ErrorMessage"] = "Only admin can edit existing contacts.";
                return RedirectToAction(nameof(Index));
            }

            var contact = await _context.Contacts
                .Include(c => c.BankAccounts)
                .FirstOrDefaultAsync(c => c.Id == id);
            if (contact == null)
                return NotFound();

            PopulateFormData(contact);
            return View(contact);
        }

        // POST: Home/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [RequireRight(RightsCatalog.ContactsEdit)]
        public async Task<IActionResult> Edit(int id, List<ContactBankAccount>? bankAccounts, IFormFile? profilePhoto)
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            if (!currentUser.IsAdmin)
            {
                TempData["ErrorMessage"] = "Only admin can edit existing contacts.";
                return RedirectToAction(nameof(Index));
            }

            NormalizeOptionalBankAccountModelState();

            var existingContact = await _context.Contacts
                .AsTracking()
                .Include(c => c.BankAccounts)
                .FirstOrDefaultAsync(c => c.Id == id);

            if (existingContact == null)
                return NotFound();

            var updateSucceeded = await TryUpdateModelAsync(
                existingContact,
                "",
                c => c.FirstName,
                c => c.LastName,
                c => c.NickName,
                c => c.Gender,
                c => c.DateOfBirth,
                c => c.Email,
                c => c.Mobile1,
                c => c.Mobile2,
                c => c.Mobile3,
                c => c.WhatsAppNumber,
                c => c.PassportNumber,
                c => c.PanNumber,
                c => c.AadharNumber,
                c => c.DrivingLicenseNumber,
                c => c.VotersId,
                c => c.Address,
                c => c.City,
                c => c.State,
                c => c.PostalCode,
                c => c.Country,
                c => c.GroupId,
                c => c.OtherDetails);

            if (!updateSucceeded)
            {
                PopulateFormData(existingContact, PrepareBankAccounts(bankAccounts));
                return View(existingContact);
            }

            ValidateDuplicateContact(existingContact, id);

            if (ModelState.IsValid)
            {
                try
                {
                    var postedGender = Request.Form["Gender"].ToString();
                    existingContact.Gender = string.IsNullOrWhiteSpace(postedGender) ? null : postedGender;

                    var postedDateOfBirth = Request.Form["DateOfBirth"].ToString();
                    if (string.IsNullOrWhiteSpace(postedDateOfBirth))
                    {
                        existingContact.DateOfBirth = null;
                    }
                    else if (DateTime.TryParseExact(postedDateOfBirth, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsedDateOfBirth) ||
                             DateTime.TryParse(postedDateOfBirth, out parsedDateOfBirth))
                    {
                        existingContact.DateOfBirth = parsedDateOfBirth;
                    }

                    existingContact.UpdatedAt = DateTime.Now;

                    var preparedBankAccounts = PrepareBankAccounts(bankAccounts);
                    if (existingContact.BankAccounts.Any())
                    {
                        _context.ContactBankAccounts.RemoveRange(existingContact.BankAccounts);
                    }

                    if (preparedBankAccounts.Any())
                    {
                        foreach (var bankAccount in preparedBankAccounts)
                        {
                            bankAccount.ContactId = existingContact.Id;
                        }

                        _context.ContactBankAccounts.AddRange(preparedBankAccounts);
                    }

                    SyncLegacyBankFields(existingContact, preparedBankAccounts.FirstOrDefault());

                    // Handle profile photo upload
                    if (profilePhoto != null)
                    {
                        var result = await _fileUploadService.UploadPhotoAsync(profilePhoto, existingContact.Id);
                        if (result.Success)
                        {
                            // Delete old photo if exists
                            if (!string.IsNullOrEmpty(existingContact.PhotoPath))
                            {
                                _fileUploadService.DeleteFile(existingContact.PhotoPath);
                            }
                            existingContact.PhotoPath = result.FilePath;
                        }
                    }
                    
                    await _context.SaveChangesAsync();

                    _adminHistoryService.Log(
                        actionType: "Edit",
                        entityType: "Contact",
                        entityId: existingContact.Id,
                        performedBy: _userContextService.CurrentUser?.UserName ?? "Unknown",
                        details: $"Edited contact '{existingContact.FirstName} {existingContact.LastName}'.");

                    TempData["SuccessMessage"] = "Contact updated successfully!";
                    return RedirectToAction(nameof(Details), new { id = existingContact.Id });
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ContactExists(id))
                        return NotFound();
                    throw;
                }
            }
            PopulateFormData(existingContact, PrepareBankAccounts(bankAccounts));
            return View(existingContact);
        }

        // GET: Home/Delete/5
        [RequireRight(RightsCatalog.ContactsDelete)]
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
                return NotFound();

            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            if (!currentUser.IsAdmin)
            {
                TempData["ErrorMessage"] = "Only admin can delete contacts.";
                return RedirectToAction(nameof(Index));
            }

            var contact = await _context.Contacts
                .Include(c => c.Group)
                .FirstOrDefaultAsync(c => c.Id == id);

            if (contact == null)
                return NotFound();

            return View(contact);
        }

        // POST: Home/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [RequireRight(RightsCatalog.ContactsDelete)]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            if (!currentUser.IsAdmin)
            {
                TempData["ErrorMessage"] = "Only admin can delete contacts.";
                return RedirectToAction(nameof(Index));
            }

            var contact = await _context.Contacts.FindAsync(id);
            if (contact != null)
            {
                _context.Contacts.Remove(contact);
                await _context.SaveChangesAsync();
                TempData["SuccessMessage"] = "Contact deleted successfully!";
            }
            return RedirectToAction(nameof(Index));
        }

        // POST: Home/DeleteMultiple - Bulk delete contacts
        [HttpPost]
        [ValidateAntiForgeryToken]
        [RequireRight(RightsCatalog.ContactsDelete)]
        public async Task<IActionResult> DeleteMultiple(List<int> contactIds)
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            if (!currentUser.IsAdmin)
            {
                TempData["ErrorMessage"] = "Only admin can delete contacts.";
                return RedirectToAction(nameof(Index));
            }

            if (contactIds == null || !contactIds.Any())
            {
                TempData["ErrorMessage"] = "No contacts selected for deletion.";
                return RedirectToAction(nameof(Index));
            }

            try
            {
                var contactsToDelete = await _context.Contacts
                    .Where(c => contactIds.Contains(c.Id))
                    .ToListAsync();

                if (contactsToDelete.Any())
                {
                    _context.Contacts.RemoveRange(contactsToDelete);
                    await _context.SaveChangesAsync();

                    TempData["SuccessMessage"] = $"Successfully deleted {contactsToDelete.Count} contact(s)!";
                }
                else
                {
                    TempData["ErrorMessage"] = "No matching contacts found to delete.";
                }
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = $"Error deleting contacts: {ex.Message}";
            }

            return RedirectToAction(nameof(Index));
        }

        private bool ContactExists(int id)
        {
            return _context.Contacts.Any(e => e.Id == id);
        }

        private void PopulateFormData(Contact? contact = null, List<ContactBankAccount>? bankAccounts = null)
        {
            ViewData["Groups"] = _context.ContactGroups.OrderBy(g => g.Name).ToList();

            var bankNames = _context.ContactBankAccounts
                .Where(b => !string.IsNullOrWhiteSpace(b.BankName))
                .Select(b => b.BankName!)
                .Distinct()
                .OrderBy(name => name)
                .ToList();

            if (!string.IsNullOrWhiteSpace(contact?.BankName) && !bankNames.Contains(contact.BankName))
            {
                bankNames.Add(contact.BankName);
                bankNames = bankNames.OrderBy(name => name).ToList();
            }

            ViewData["BankNames"] = bankNames;

            if (bankAccounts != null && bankAccounts.Any())
            {
                ViewData["BankAccounts"] = bankAccounts;
                return;
            }

            if (contact?.BankAccounts != null && contact.BankAccounts.Any())
            {
                ViewData["BankAccounts"] = contact.BankAccounts.OrderBy(b => b.Id).ToList();
                return;
            }

            if (contact != null && (!string.IsNullOrWhiteSpace(contact.BankAccountNumber) || !string.IsNullOrWhiteSpace(contact.BankName) || !string.IsNullOrWhiteSpace(contact.BranchName) || !string.IsNullOrWhiteSpace(contact.IfscCode)))
            {
                ViewData["BankAccounts"] = new List<ContactBankAccount>
                {
                    new ContactBankAccount
                    {
                        AccountNumber = contact.BankAccountNumber,
                        BankName = contact.BankName,
                        BranchName = contact.BranchName,
                        IfscCode = contact.IfscCode
                    }
                };
                return;
            }

            ViewData["BankAccounts"] = new List<ContactBankAccount> { new ContactBankAccount() };
        }

        private static List<ContactBankAccount> PrepareBankAccounts(List<ContactBankAccount>? bankAccounts)
        {
            return (bankAccounts ?? new List<ContactBankAccount>())
                .Where(b => !string.IsNullOrWhiteSpace(b.AccountNumber) || !string.IsNullOrWhiteSpace(b.BankName) || !string.IsNullOrWhiteSpace(b.BranchName) || !string.IsNullOrWhiteSpace(b.IfscCode))
                .Select(b => new ContactBankAccount
                {
                    AccountNumber = b.AccountNumber,
                    BankName = b.BankName,
                    BranchName = b.BranchName,
                    IfscCode = b.IfscCode,
                    CreatedAt = DateTime.Now,
                    UpdatedAt = DateTime.Now
                })
                .ToList();
        }

        private static void SyncLegacyBankFields(Contact contact, ContactBankAccount? primaryBankAccount)
        {
            if (primaryBankAccount == null)
            {
                contact.BankAccountNumber = null;
                contact.BankName = null;
                contact.BranchName = null;
                contact.IfscCode = null;
                return;
            }

            contact.BankAccountNumber = primaryBankAccount.AccountNumber;
            contact.BankName = primaryBankAccount.BankName;
            contact.BranchName = primaryBankAccount.BranchName;
            contact.IfscCode = primaryBankAccount.IfscCode;
        }

        private void NormalizeOptionalBankAccountModelState()
        {
            var bankAccountKeys = ModelState.Keys
                .Where(key => key.StartsWith("bankAccounts[", StringComparison.OrdinalIgnoreCase))
                .ToList();

            foreach (var key in bankAccountKeys)
            {
                ModelState.Remove(key);
            }
        }

        private void ValidateDuplicateContact(Contact contact, int? excludeContactId = null)
        {
            var normalizedMobile = NormalizeDigits(contact.Mobile1);
            var normalizedAadhar = NormalizeDigits(contact.AadharNumber);

            if (!string.IsNullOrWhiteSpace(normalizedMobile))
            {
                var mobileConflict = _context.Contacts
                    .AsNoTracking()
                    .Where(c => c.Id != (excludeContactId ?? 0) && !string.IsNullOrWhiteSpace(c.Mobile1))
                    .Select(c => new { c.FirstName, c.LastName, c.Mobile1 })
                    .ToList()
                    .FirstOrDefault(c => NormalizeDigits(c.Mobile1) == normalizedMobile);

                if (mobileConflict != null)
                {
                    ModelState.AddModelError(nameof(Contact.Mobile1),
                        $"Mobile number already exists for contact '{mobileConflict.FirstName} {mobileConflict.LastName}'.");
                }
            }

            if (!string.IsNullOrWhiteSpace(normalizedAadhar))
            {
                var aadharConflict = _context.Contacts
                    .AsNoTracking()
                    .Where(c => c.Id != (excludeContactId ?? 0) && !string.IsNullOrWhiteSpace(c.AadharNumber))
                    .Select(c => new { c.FirstName, c.LastName, c.AadharNumber })
                    .ToList()
                    .FirstOrDefault(c => NormalizeDigits(c.AadharNumber) == normalizedAadhar);

                if (aadharConflict != null)
                {
                    ModelState.AddModelError(nameof(Contact.AadharNumber),
                        $"Aadhar number already exists for contact '{aadharConflict.FirstName} {aadharConflict.LastName}'.");
                }
            }

            if (string.IsNullOrWhiteSpace(normalizedMobile) && string.IsNullOrWhiteSpace(normalizedAadhar))
            {
                var firstName = NormalizeText(contact.FirstName);
                var lastName = NormalizeText(contact.LastName);
                var nickName = NormalizeText(contact.NickName);

                if (!string.IsNullOrWhiteSpace(firstName))
                {
                    var nameConflict = _context.Contacts
                        .AsNoTracking()
                        .Where(c => c.Id != (excludeContactId ?? 0) && !string.IsNullOrWhiteSpace(c.FirstName))
                        .Select(c => new { c.FirstName, c.LastName, c.NickName })
                        .ToList()
                        .FirstOrDefault(c =>
                            NormalizeText(c.FirstName) == firstName &&
                            NormalizeText(c.LastName) == lastName &&
                            NormalizeText(c.NickName) == nickName);

                    if (nameConflict != null)
                    {
                        ModelState.AddModelError(nameof(Contact.FirstName),
                            "A contact with the same First Name, Last Name, and Nick Name already exists. Provide Mobile1 or Aadhar if this is a different person.");
                    }
                }
            }
        }

        private List<Contact> FilterDuplicateImportedContacts(List<Contact> contacts, List<string> errors)
        {
            var validContacts = new List<Contact>();

            var existingContacts = _context.Contacts
                .AsNoTracking()
                .Select(c => new { c.FirstName, c.LastName, c.NickName, c.Mobile1, c.AadharNumber })
                .ToList();

            var seenMobiles = new HashSet<string>();
            var seenAadhars = new HashSet<string>();
            var seenNames = new HashSet<string>();

            for (var i = 0; i < contacts.Count; i++)
            {
                var contact = contacts[i];
                var rowLabel = $"Row {i + 1} ({contact.FirstName} {contact.LastName})";

                var normalizedMobile = NormalizeDigits(contact.Mobile1);
                var normalizedAadhar = NormalizeDigits(contact.AadharNumber);
                var firstName = NormalizeText(contact.FirstName);
                var lastName = NormalizeText(contact.LastName);
                var nickName = NormalizeText(contact.NickName);
                var nameKey = $"{firstName}|{lastName}|{nickName}";

                var hasError = false;

                if (!string.IsNullOrWhiteSpace(normalizedMobile))
                {
                    var existsInDb = existingContacts.Any(c => NormalizeDigits(c.Mobile1) == normalizedMobile);
                    var existsInImport = seenMobiles.Contains(normalizedMobile);
                    if (existsInDb || existsInImport)
                    {
                        errors.Add($"{rowLabel}: Mobile1 already exists.");
                        hasError = true;
                    }
                }

                if (!string.IsNullOrWhiteSpace(normalizedAadhar))
                {
                    var existsInDb = existingContacts.Any(c => NormalizeDigits(c.AadharNumber) == normalizedAadhar);
                    var existsInImport = seenAadhars.Contains(normalizedAadhar);
                    if (existsInDb || existsInImport)
                    {
                        errors.Add($"{rowLabel}: AadharNumber already exists.");
                        hasError = true;
                    }
                }

                if (string.IsNullOrWhiteSpace(normalizedMobile) && string.IsNullOrWhiteSpace(normalizedAadhar))
                {
                    var existsInDb = existingContacts.Any(c =>
                        NormalizeText(c.FirstName) == firstName &&
                        NormalizeText(c.LastName) == lastName &&
                        NormalizeText(c.NickName) == nickName);
                    var existsInImport = seenNames.Contains(nameKey);

                    if (existsInDb || existsInImport)
                    {
                        errors.Add($"{rowLabel}: Same First Name + Last Name + Nick Name already exists.");
                        hasError = true;
                    }
                }

                if (hasError)
                {
                    continue;
                }

                if (!string.IsNullOrWhiteSpace(normalizedMobile))
                {
                    seenMobiles.Add(normalizedMobile);
                }

                if (!string.IsNullOrWhiteSpace(normalizedAadhar))
                {
                    seenAadhars.Add(normalizedAadhar);
                }

                if (string.IsNullOrWhiteSpace(normalizedMobile) && string.IsNullOrWhiteSpace(normalizedAadhar))
                {
                    seenNames.Add(nameKey);
                }

                validContacts.Add(contact);
            }

            return validContacts;
        }

        private static string NormalizeDigits(string? value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return string.Empty;
            }

            return new string(value.Where(char.IsDigit).ToArray());
        }

        private static string NormalizeText(string? value)
        {
            return (value ?? string.Empty).Trim().ToUpperInvariant();
        }

        #region Import/Export Actions

        // GET: Home/Dashboard - Display contact statistics
        [RequireRight(RightsCatalog.ContactsView)]
        public async Task<IActionResult> Dashboard()
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            if (!currentUser.IsAdmin)
            {
                TempData["ErrorMessage"] = "Dashboard is available only for admin.";
                return RedirectToAction(nameof(Index));
            }

            var statistics = await _statisticsService.GetStatisticsAsync();
            return View(statistics);
        }

        // GET: Home/FindDuplicates - Display potential duplicate contacts
        [RequireRight(RightsCatalog.ContactsView)]
        public async Task<IActionResult> FindDuplicates()
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            if (!currentUser.IsAdmin)
            {
                TempData["ErrorMessage"] = "Find Duplicates is available only for admin.";
                return RedirectToAction(nameof(Index));
            }

            var duplicates = await _statisticsService.FindDuplicatesAsync();
            return View(duplicates);
        }

        // GET: Home/Import - Display import page
        [RequireRight(RightsCatalog.ContactsCreate)]
        public IActionResult Import()
        {
            return View();
        }

        // POST: Home/ImportFile - Handle file import
        [HttpPost]
        [ValidateAntiForgeryToken]
        [RequireRight(RightsCatalog.ContactsCreate)]
        public async Task<IActionResult> ImportFile(IFormFile file, string fileType)
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            if (file == null || file.Length == 0)
            {
                TempData["ErrorMessage"] = "Please select a file to import.";
                return RedirectToAction(nameof(Import));
            }

            List<Contact> contacts;
            List<string> errors;

            try
            {
                using var stream = file.OpenReadStream();

                if (fileType == "excel")
                {
                    (contacts, errors) = await _importExportService.ImportFromExcel(stream);
                }
                else if (fileType == "csv")
                {
                    (contacts, errors) = await _importExportService.ImportFromCsv(stream);
                }
                else
                {
                    TempData["ErrorMessage"] = "Invalid file type selected.";
                    return RedirectToAction(nameof(Import));
                }

                if (errors.Any())
                {
                    TempData["ErrorMessage"] = $"Import completed with errors:<br/>{string.Join("<br/>", errors)}";
                }

                if (contacts.Any())
                {
                    if (!currentUser.IsAdmin)
                    {
                        var scopedContactGroupId = ResolveContactGroupIdForUser(currentUser);
                        if (!scopedContactGroupId.HasValue)
                        {
                            TempData["ErrorMessage"] = "Your account is not assigned to a contact group.";
                            return RedirectToAction(nameof(Import));
                        }

                        foreach (var importedContact in contacts)
                        {
                            importedContact.GroupId = scopedContactGroupId.Value;
                        }
                    }

                    contacts = FilterDuplicateImportedContacts(contacts, errors);

                    if (errors.Any())
                    {
                        TempData["ErrorMessage"] = $"Import completed with errors:<br/>{string.Join("<br/>", errors)}";
                    }

                    if (!contacts.Any())
                    {
                        TempData["ErrorMessage"] = TempData["ErrorMessage"] ?? "No valid contacts found in the file.";
                        return RedirectToAction(nameof(Import));
                    }

                    // Set change tracking to true for saving
                    _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.TrackAll;
                    
                    await _context.Contacts.AddRangeAsync(contacts);
                    await _context.SaveChangesAsync();
                    
                    // Reset tracking behavior
                    _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

                    TempData["SuccessMessage"] = $"Successfully imported {contacts.Count} contact(s)!";
                }
                else
                {
                    TempData["ErrorMessage"] = "No valid contacts found in the file.";
                }
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = $"Error importing file: {ex.Message}";
            }

            return RedirectToAction(nameof(Index));
        }

        // GET: Home/ExportExcel - Export to Excel
        [RequireRight(RightsCatalog.ContactsView)]
        public async Task<IActionResult> ExportExcel()
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            var contacts = await ApplyContactScope(
                    _context.Contacts
                        .Include(c => c.Group)
                        .OrderBy(c => c.FirstName),
                    currentUser)
                .ToListAsync();

            var fileBytes = await _importExportService.ExportToExcel(contacts);
            var fileName = $"Contacts_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
            
            return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }

        // GET: Home/ExportCsv - Export to CSV
        [RequireRight(RightsCatalog.ContactsView)]
        public async Task<IActionResult> ExportCsv()
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            var contacts = await ApplyContactScope(
                    _context.Contacts
                        .Include(c => c.Group)
                        .OrderBy(c => c.FirstName),
                    currentUser)
                .ToListAsync();

            var fileBytes = await _importExportService.ExportToCsv(contacts);
            var fileName = $"Contacts_{DateTime.Now:yyyyMMdd_HHmmss}.csv";
            
            return File(fileBytes, "text/csv", fileName);
        }

        // GET: Home/ExportPdf - Export to PDF
        [RequireRight(RightsCatalog.ContactsView)]
        public async Task<IActionResult> ExportPdf()
        {
            var currentUser = _userContextService.CurrentUser;
            if (currentUser == null)
            {
                return RedirectToAction("Login", "Account");
            }

            var contacts = await ApplyContactScope(
                    _context.Contacts
                        .Include(c => c.Group)
                        .OrderBy(c => c.FirstName),
                    currentUser)
                .ToListAsync();

            var fileBytes = await _importExportService.ExportToPdf(contacts);
            var fileName = $"Contacts_{DateTime.Now:yyyyMMdd_HHmmss}.pdf";
            
            return File(fileBytes, "application/pdf", fileName);
        }

        // GET: Home/DownloadTemplate - Download import template
        public async Task<IActionResult> DownloadTemplate(string type)
        {
            if (type == "excel")
            {
                var fileBytes = await _importExportService.GenerateExcelTemplate();
                return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Contact_Import_Template.xlsx");
            }
            else if (type == "csv")
            {
                var fileBytes = await _importExportService.GenerateCsvTemplate();
                return File(fileBytes, "text/csv", "Contact_Import_Template.csv");
            }

            return NotFound();
        }

        private IQueryable<Contact> ApplyContactScope(IQueryable<Contact> query, AppUser currentUser)
        {
            if (currentUser.IsAdmin)
            {
                return query;
            }

            var scopedContactGroupId = ResolveContactGroupIdForUser(currentUser);
            if (!scopedContactGroupId.HasValue)
            {
                return query.Where(c => false);
            }

            var groupId = scopedContactGroupId.Value;
            return query.Where(c => c.GroupId == groupId);
        }

        private bool CanAccessContact(AppUser currentUser, Contact contact)
        {
            if (currentUser.IsAdmin)
            {
                return true;
            }

            var scopedContactGroupId = ResolveContactGroupIdForUser(currentUser);
            return scopedContactGroupId.HasValue && contact.GroupId == scopedContactGroupId.Value;
        }

        private int? ResolveContactGroupIdForUser(AppUser user)
        {
            if (user.IsAdmin)
            {
                return null;
            }

            if (user.GroupId <= 0)
            {
                return null;
            }

            var userGroupName = _context.UserGroups
                .Where(g => g.Id == user.GroupId)
                .Select(g => g.Name)
                .FirstOrDefault();

            if (!string.IsNullOrWhiteSpace(userGroupName) && userGroupName.StartsWith("ContactGroup - ", StringComparison.OrdinalIgnoreCase))
            {
                var contactGroupName = userGroupName.Substring("ContactGroup - ".Length).Trim();
                var mappedContactGroupId = _context.ContactGroups
                    .Where(cg => cg.Name == contactGroupName)
                    .Select(cg => (int?)cg.Id)
                    .FirstOrDefault();

                if (mappedContactGroupId.HasValue)
                {
                    return mappedContactGroupId.Value;
                }
            }

            var directMatch = _context.ContactGroups
                .Where(cg => cg.Id == user.GroupId)
                .Select(cg => (int?)cg.Id)
                .FirstOrDefault();

            return directMatch;
        }

        #endregion
    }
}