#import "DetailsViewController.h"
#import "APIClient.h"
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "OfflineSyncManager.h"
#import "NetworkManager.h"
#import "ImageCacheHelper.h"

@interface AddIssueDetailsViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITextField *locationField;
@property (nonatomic, strong) UITextView *commentField;
@property (nonatomic, strong) UIButton *submitButton;
@property (nonatomic, strong) UIButton *resetButton;
@property (nonatomic, strong) NSArray *categories;
@property (nonatomic, strong) NSArray *types;
@property (nonatomic, strong) NSArray *issues;
@property (nonatomic, weak) UIButton *typeButton;
@property (nonatomic, weak) UIButton *issueButton;
@property (nonatomic, copy) NSString *selectedTypeName;
@property (nonatomic, copy) NSString * selectedIssueID;
@property (nonatomic, assign) BOOL isEditMode;
@property (nonatomic, strong) NSMutableArray *existingImages;
@property (nonatomic, strong) NSMutableArray *addedImages;
@property (nonatomic, strong) NSString *catName;
@property (nonatomic, strong) NSString *issueName;

@end

@implementation AddIssueDetailsViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.isEditMode = [self.action isEqualToString:@"edit_issue"];
  self.existingImages = [NSMutableArray array];
  self.addedImages = [NSMutableArray array];
  self.view.backgroundColor = UIColor.whiteColor;
  
  NSLog(@"📦 Data being brought over:\n planID: %@\n locationID: %@\n selectedLocationName: %@\n defectMatrix: %@\n projectName: %@\n projectCode: %@\n XCoordinates: %f\n YCoordinates: %f\n action: %@\n issueFullData: %@\n issueContent: %@\n locationData: %@",
        self.planID,
        self.locationID,
        self.selectedLocationName,
        self.defectMatrix,
        self.projectName,
        self.projectCode,
        self.planX,
        self.planY,
        self.action,
        self.issueFullData,
        self.issueContent,
        self.locationData);
  
    NSString *text = [NSString stringWithFormat:@"%@", self.locationData];
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [docsPath stringByAppendingPathComponent:@"locationData.txt"];
    
    // Convert issueData to a readable string
    NSString *plainText = [NSString stringWithFormat:@"%@", self.locationData];
    
    // Write as plain UTF-8 text
    [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    // Log the path so you can find it
    NSLog(@"📁 issueData saved as plain text to: %@", filePath);
  
    NSDictionary *locData = self.locationData;
    if ([locData isKindOfClass:[NSDictionary class]]) {
      self.categories = locData[@"category"];
      
      // Extract all types under all categories (for now, assuming one category)
      if (self.categories.count > 0) {
        NSDictionary *firstCat = self.categories.firstObject;
        self.types = firstCat[@"type"];
      }
      
      NSLog(@"✅ Parsed %lu categories, %lu types", (unsigned long)self.categories.count, (unsigned long)self.types.count);
    }
    if (self.categories.count > 0) {
      NSDictionary *firstCat = self.categories.firstObject;
      self.catName = firstCat[@"cat_name"];
      UIButton *catBtn = [self.view viewWithTag:2000];
      if ([catBtn isKindOfClass:[UIButton class]] && self.catName) {
        [catBtn setTitle:self.catName forState:UIControlStateNormal];
        [catBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
      }
    }
    
    // Create all views (don’t position them yet)
    [self createHeader];
    [self createForm];
    
    // Set location if passed from previous screen
    if (self.selectedLocationName && self.selectedLocationName.length > 0) {
      self.locationField.text = self.selectedLocationName;
    }
    self.uploadedImages = [NSMutableArray arrayWithObjects:[NSNull null], [NSNull null], [NSNull null], nil];
    
    if (self.isEditMode) {
      UILabel *title = [self.headerView viewWithTag:101];
      title.text = @"Edit Issue Details";
      [self.submitButton setTitle:@"Save Changes" forState:UIControlStateNormal];
    }
    if (self.isEditMode && [self.issueFullData isKindOfClass:[NSDictionary class]]) {
      NSDictionary *issue = self.issueFullData;
      
      NSLog(@"🧠 Prefilling edit fields with issueFullData: %@", issue);
      
      // 🗒 Prefill comment field (use 'remarks' key)
      NSString *remarks = issue[@"remarks"];
      if ([remarks isKindOfClass:[NSString class]]) {
        self.commentField.text = remarks;
      }
      
      // 🏷 Prefill dropdown titles
      self.catName = issue[@"category"];
      NSString *typeName = issue[@"type"];
      self.issueName = issue[@"issue"];
      
      UIButton *catBtn = [self.view viewWithTag:2000]; // Category
      UIButton *typeBtn = [self.view viewWithTag:2001]; // Type
      UIButton *issueBtn = [self.view viewWithTag:2002]; // Issue
      
      if ([catBtn isKindOfClass:[UIButton class]] && self.catName.length > 0) {
        [catBtn setTitle:self.catName forState:UIControlStateNormal];
        [catBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
      }
      
      if ([typeBtn isKindOfClass:[UIButton class]] && typeName.length > 0) {
        [typeBtn setTitle:typeName forState:UIControlStateNormal];
        [typeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.selectedTypeName = typeName;
      }
      
      if ([issueBtn isKindOfClass:[UIButton class]] && self.issueName.length > 0) {
        [issueBtn setTitle:self.issueName forState:UIControlStateNormal];
        [issueBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.selectedIssueID = [NSString stringWithFormat:@"%@", issue[@"issue_id"] ?: @""];
      }
      
      // 📍 Prefill position
      if (issue[@"pos_x"]) self.planX = [issue[@"pos_x"] floatValue];
      if (issue[@"pos_y"]) self.planY = [issue[@"pos_y"] floatValue];
      
      // 🧭 Prefill location name
      NSString *locName = issue[@"location_name"];
      if ([locName isKindOfClass:[NSString class]]) {
        self.locationField.text = locName;
      }
      
      // 🖼 Prefill images under "first"
      NSArray *firstImages = self.issueFullData[@"first"];
      if ([firstImages isKindOfClass:[NSArray class]] && firstImages.count > 0) {
        for (int i = 0; i < MIN(firstImages.count, 3); i++) {
          NSDictionary *imgDict = firstImages[i];
          NSString *urlStr = imgDict[@"thumb_image"] ?: imgDict[@"image"];
          if (![urlStr isKindOfClass:[NSString class]]) continue;
          
          [self.existingImages addObject:urlStr];
          NSURL *url = [NSURL URLWithString:urlStr];
          if (!url) continue;
          
          [ImageCacheHelper loadImageWithURL:url completion:^(UIImage *img) {
            if (!img) return;
            
            dispatch_async(dispatch_get_main_queue(), ^{
              if (i < self.uploadedImages.count)
                self.uploadedImages[i] = img;
              else
                [self.uploadedImages addObject:img];
              
              UIButton *btn = [self.view viewWithTag:1000 + i];
              if ([btn isKindOfClass:[UIButton class]]) {
                [btn setImage:img forState:UIControlStateNormal];
                btn.imageView.contentMode = UIViewContentModeScaleAspectFill;
                btn.clipsToBounds = YES;
                [self addRemoveButtonToUpload:btn atIndex:i];
              }
            });
          }];
        }
      }
      NSLog(@"✅ Prefilled Edit Mode UI successfully");
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    CGFloat topInset = self.view.safeAreaInsets.top;
    CGFloat headerHeight = 48.0;

    // Header layout
    self.headerView.frame = CGRectMake(0, topInset, self.view.bounds.size.width, headerHeight);
  
    // Title Label
    UILabel *title = [self.headerView viewWithTag:101];
     if (title) {
         title.frame = CGRectMake(0, 8, self.headerView.bounds.size.width, 32);
     }

    // Scroll view layout (below header)
    CGFloat scrollY = topInset + headerHeight;
    self.scrollView.frame = CGRectMake(0, scrollY, self.view.bounds.size.width, self.view.bounds.size.height - scrollY);
}

#pragma mark - Setup

- (void)createHeader {
    // Header container
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerView];
    
    // Back button (SF Symbol)
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.translatesAutoresizingMaskIntoConstraints = NO;

    UIImage *backImage = [UIImage systemImageNamed:@"chevron.left"];
    backImage = [backImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [backButton setImage:backImage forState:UIControlStateNormal];
    backButton.tintColor = [UIColor whiteColor];
    backButton.backgroundColor = [UIColor clearColor];
    [backButton addTarget:self action:@selector(dismissSelf)
         forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:backButton];
    
    // Title label
    UILabel *title = [[UILabel alloc] init];
    title.translatesAutoresizingMaskIntoConstraints = NO;
    title.text = @"Add Issue Details";
    title.textColor = UIColor.whiteColor;
    title.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    title.textAlignment = NSTextAlignmentCenter;
    title.tag = 101;
    [self.headerView addSubview:title];
    
    // ✅ Reset button (refresh icon)
    self.resetButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.resetButton.translatesAutoresizingMaskIntoConstraints = NO;
    if (self.isEditMode){
      self.resetButton.hidden = YES;
    }

    UIImage *refreshImage = [UIImage systemImageNamed:@"arrow.clockwise"];
    refreshImage = [refreshImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [self.resetButton setImage:refreshImage forState:UIControlStateNormal];
    self.resetButton.tintColor = [UIColor whiteColor];
    self.resetButton.backgroundColor = [UIColor clearColor];
    [self.resetButton addTarget:self
                         action:@selector(handleReset)
               forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.resetButton];
    
    // Status bar background (same color as header)
    UIView *statusBarBackground = [[UIView alloc] init];
    statusBarBackground.backgroundColor = self.headerView.backgroundColor;
    statusBarBackground.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:statusBarBackground];

    // Auto Layout
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        // Header
        [self.headerView.topAnchor constraintEqualToAnchor:safe.topAnchor],
        [self.headerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.headerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.headerView.heightAnchor constraintEqualToConstant:48],

        // Back button
        [backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:8],
        [backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [backButton.widthAnchor constraintEqualToConstant:44],
        [backButton.heightAnchor constraintEqualToConstant:44],

        // Title centered
        [title.centerXAnchor constraintEqualToAnchor:self.headerView.centerXAnchor],
        [title.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],

        // ✅ Reset button (right)
        [self.resetButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-8],
        [self.resetButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        [self.resetButton.widthAnchor constraintEqualToConstant:44],
        [self.resetButton.heightAnchor constraintEqualToConstant:44],

        // Status bar color fill
        [statusBarBackground.topAnchor constraintEqualToAnchor:self.view.topAnchor],
        [statusBarBackground.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [statusBarBackground.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [statusBarBackground.bottomAnchor constraintEqualToAnchor:safe.topAnchor],
    ]];
}

- (void)createForm {
    UIScrollView *scroll = [[UIScrollView alloc] init];
    scroll.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:scroll];
    self.scrollView = scroll;
    
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        [scroll.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor],
        [scroll.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [scroll.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [scroll.bottomAnchor constraintEqualToAnchor:safe.bottomAnchor],
    ]];
    
    UIView *content = [[UIView alloc] init];
    content.translatesAutoresizingMaskIntoConstraints = NO;
    [scroll addSubview:content];
    [NSLayoutConstraint activateConstraints:@[
        [content.topAnchor constraintEqualToAnchor:scroll.topAnchor],
        [content.leadingAnchor constraintEqualToAnchor:scroll.leadingAnchor],
        [content.trailingAnchor constraintEqualToAnchor:scroll.trailingAnchor],
        [content.bottomAnchor constraintEqualToAnchor:scroll.bottomAnchor],
        [content.widthAnchor constraintEqualToAnchor:scroll.widthAnchor],
    ]];

    CGFloat spacing = 16;
    UIView *lastView = nil;

    // “For” label
    UILabel *forLabel = [self makeLabelWithText:@"For" bold:NO size:14];
    [content addSubview:forLabel];
    [forLabel.topAnchor constraintEqualToAnchor:content.topAnchor constant:spacing].active = YES;
    [forLabel.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20].active = YES;
    
    // 🧩 Build dynamic text safely
    NSString *unitText = @"";
    if (self.projectName && self.projectCode) {
        unitText = [NSString stringWithFormat:@"%@, %@", self.projectName, self.projectCode];
    } else if (self.projectName) {
        unitText = self.projectName;
    } else if (self.projectCode) {
        unitText = self.projectCode;
    } else {
        unitText = @"-"; // fallback if both missing
    }

    // 🏷 Create the label
    UILabel *unitLabel = [self makeLabelWithText:unitText bold:YES size:16];
    [content addSubview:unitLabel];
    [unitLabel.topAnchor constraintEqualToAnchor:forLabel.bottomAnchor constant:4].active = YES;
    [unitLabel.leadingAnchor constraintEqualToAnchor:forLabel.leadingAnchor].active = YES;
    lastView = unitLabel;
  
    // Location section
    UILabel *locationTitle = [self makeLabelWithText:@"*Location" bold:YES size:15];
    [content addSubview:locationTitle];
    [locationTitle.topAnchor constraintEqualToAnchor:lastView.bottomAnchor constant:spacing].active = YES;
    [locationTitle.leadingAnchor constraintEqualToAnchor:forLabel.leadingAnchor].active = YES;

    UIView *locationContainer = [self makeRoundedBox];
    [content addSubview:locationContainer];
    [NSLayoutConstraint activateConstraints:@[
        [locationContainer.topAnchor constraintEqualToAnchor:locationTitle.bottomAnchor constant:8],
        [locationContainer.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20],
        [locationContainer.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-20],
        [locationContainer.heightAnchor constraintEqualToConstant:44],
    ]];
    lastView = locationContainer;

    // === Location Field (read-only) ===
    UITextField *locationField = [[UITextField alloc] init];
    locationField.translatesAutoresizingMaskIntoConstraints = NO;
    locationField.text = self.selectedLocationName ?: @"Select location";
    locationField.font = [UIFont systemFontOfSize:15];
    locationField.textColor = [UIColor blackColor];
    locationField.enabled = NO;
    [locationContainer addSubview:locationField];
    self.locationField = locationField;

    [NSLayoutConstraint activateConstraints:@[
        [locationField.leadingAnchor constraintEqualToAnchor:locationContainer.leadingAnchor constant:8],
        [locationField.trailingAnchor constraintEqualToAnchor:locationContainer.trailingAnchor constant:-8],
        [locationField.centerYAnchor constraintEqualToAnchor:locationContainer.centerYAnchor],
    ]];

//     === Reselect Button (inside the container, right-aligned) ===
    UIButton *reselectBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    reselectBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [reselectBtn setTitle:@"Reselect" forState:UIControlStateNormal];
    [reselectBtn setTitleColor:[UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1]
                      forState:UIControlStateNormal];
    reselectBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [reselectBtn addTarget:self action:@selector(dismissSelf) forControlEvents:UIControlEventTouchUpInside];
    [locationContainer addSubview:reselectBtn];

    [NSLayoutConstraint activateConstraints:@[
        [reselectBtn.trailingAnchor constraintEqualToAnchor:locationContainer.trailingAnchor constant:-8],
        [reselectBtn.centerYAnchor constraintEqualToAnchor:locationContainer.centerYAnchor],
        [reselectBtn.heightAnchor constraintEqualToConstant:16],
        [reselectBtn.widthAnchor constraintEqualToConstant:16],
        
        // shrink locationField width so it doesn’t overlap
        [locationField.leadingAnchor constraintEqualToAnchor:reselectBtn.trailingAnchor constant:8],
    ]];

    // Category, Type, Issue — dropdown style
    NSArray *titles = @[@"*Category", @"*Type", @"*Issue"];

    for (int i = 0; i < titles.count; i++) {
        NSString *t = titles[i];
        
        // Label for field title
        UILabel *lbl = [self makeLabelWithText:t bold:NO size:13];
        [content addSubview:lbl];
        [NSLayoutConstraint activateConstraints:@[
            [lbl.topAnchor constraintEqualToAnchor:(lastView ? lastView.bottomAnchor : content.topAnchor) constant:(lastView ? 24 : 0)],
            [lbl.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20],
            [lbl.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-20],
        ]];
        
        // Create dropdown button
        UIButton *dropdown = [self makeDropdownWithPlaceholder:[NSString stringWithFormat:@"- Select %@ -", [t componentsSeparatedByString:@" "].lastObject]];
        dropdown.tag = 2000 + i;
        [content addSubview:dropdown];
        [NSLayoutConstraint activateConstraints:@[
            [dropdown.topAnchor constraintEqualToAnchor:lbl.bottomAnchor constant:8],
            [dropdown.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20],
            [dropdown.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-20],
            [dropdown.heightAnchor constraintEqualToConstant:44],
        ]];
        
        // Keep references for Type & Issue
        if (i == 1) self.typeButton = dropdown;
        if (i == 2) self.issueButton = dropdown;
        
        // === Category Auto-Load + Disable Interaction ===
        if (i == 0) {
            NSArray *categories = self.locationData[@"category"];
            if (categories.count > 0) {
                NSDictionary *firstCategory = categories.firstObject;
                NSDictionary *cat = self.categories.firstObject;
                self.catName = cat[@"cat_name"] ?: @"-";
                [dropdown setTitle:self.catName forState:UIControlStateNormal];
                [dropdown setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            } else {
                [dropdown setTitle:@"(No Category)" forState:UIControlStateNormal];
                [dropdown setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
              
            }
            
            dropdown.enabled = NO;   // make it non-clickable
            dropdown.alpha = 0.6;    // visually indicate read-only
        }

        lastView = dropdown;
    }

    // Comment box
    UILabel *commentLabel = [self makeLabelWithText:@"Comment" bold:YES size:15];
    [content addSubview:commentLabel];
    [commentLabel.topAnchor constraintEqualToAnchor:lastView.bottomAnchor constant:spacing].active = YES;
    [commentLabel.leadingAnchor constraintEqualToAnchor:forLabel.leadingAnchor].active = YES;

    UITextView *comment = [[UITextView alloc] init];
    comment.translatesAutoresizingMaskIntoConstraints = NO;
    comment.layer.borderWidth = 1.0;
    comment.layer.cornerRadius = 8;
    comment.layer.borderColor = [UIColor lightGrayColor].CGColor;
    comment.backgroundColor = [UIColor whiteColor];
    comment.font = [UIFont systemFontOfSize:15];
    comment.textColor = [UIColor blackColor];
    [content addSubview:comment];
    [NSLayoutConstraint activateConstraints:@[
        [comment.topAnchor constraintEqualToAnchor:commentLabel.bottomAnchor constant:8],
        [comment.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20],
        [comment.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-20],
        [comment.heightAnchor constraintEqualToConstant:100],
    ]];
    self.commentField = comment;
    lastView = comment;

    // Image upload section
    UILabel *uploadLabel = [self makeLabelWithText:@"*Image Upload" bold:YES size:15];
    [content addSubview:uploadLabel];
    [uploadLabel.topAnchor constraintEqualToAnchor:lastView.bottomAnchor constant:spacing].active = YES;
    [uploadLabel.leadingAnchor constraintEqualToAnchor:forLabel.leadingAnchor].active = YES;

    UIStackView *uploadRow = [[UIStackView alloc] init];
    uploadRow.axis = UILayoutConstraintAxisHorizontal;
    uploadRow.spacing = 12;
    uploadRow.distribution = UIStackViewDistributionFillEqually;
    uploadRow.translatesAutoresizingMaskIntoConstraints = NO;
    [content addSubview:uploadRow];
    [NSLayoutConstraint activateConstraints:@[
        [uploadRow.topAnchor constraintEqualToAnchor:uploadLabel.bottomAnchor constant:8],
        [uploadRow.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20],
        [uploadRow.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-20],
        [uploadRow.heightAnchor constraintEqualToConstant:90],
    ]];

    for (int i = 0; i < 3; i++) {
        UIButton *uploadBtn = [self makeUploadBox];
        uploadBtn.tag = 1000 + i; // unique ID for each button
        [uploadRow addArrangedSubview:uploadBtn];
    }
    lastView = uploadRow;

    // Submit button
    UIButton *submit = [UIButton buttonWithType:UIButtonTypeSystem];
    submit.translatesAutoresizingMaskIntoConstraints = NO;
    submit.backgroundColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    [submit setTitle:@"Submit" forState:UIControlStateNormal];
    [submit setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    submit.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    submit.layer.cornerRadius = 8;
    [submit addTarget:self action:@selector(handleSubmitTap) forControlEvents:UIControlEventTouchUpInside];
    [content addSubview:submit];
    [NSLayoutConstraint activateConstraints:@[
        [submit.topAnchor constraintEqualToAnchor:lastView.bottomAnchor constant:spacing],
        [submit.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:20],
        [submit.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-20],
        [submit.heightAnchor constraintEqualToConstant:48],
    ]];
    lastView = submit;
    [content.bottomAnchor constraintEqualToAnchor:lastView.bottomAnchor constant:spacing].active = YES;
  
    // 👇 Add tap gesture to dismiss keyboard
    UITapGestureRecognizer *tapToDismiss = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                   action:@selector(dismissKeyboard)];
    tapToDismiss.cancelsTouchesInView = NO; // ensures buttons still respond
    [self.scrollView addGestureRecognizer:tapToDismiss];
}

- (UILabel *)makeLabelWithText:(NSString *)text bold:(BOOL)bold size:(CGFloat)size {
    UILabel *lbl = [[UILabel alloc] init];
    lbl.translatesAutoresizingMaskIntoConstraints = NO;
    lbl.text = text;
    lbl.font = bold ? [UIFont boldSystemFontOfSize:size] : [UIFont systemFontOfSize:size];
    lbl.textColor = [UIColor darkTextColor];
    return lbl;
}

- (UIView *)makeRoundedBox {
    UIView *box = [[UIView alloc] init];
    box.translatesAutoresizingMaskIntoConstraints = NO;
    box.layer.borderWidth = 1.0;
    box.layer.borderColor = [UIColor lightGrayColor].CGColor;
    box.layer.cornerRadius = 8;
    return box;
}

- (UIButton *)makeDropdownWithPlaceholder:(NSString *)placeholder {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.translatesAutoresizingMaskIntoConstraints = NO;
    btn.layer.borderWidth = 1.0;
    btn.layer.cornerRadius = 8;
    btn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    btn.backgroundColor = [UIColor colorWithWhite:0.97 alpha:1];
    
    // Title setup
    [btn setTitle:placeholder forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    // Align text on the left
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, 12, 0, 0);
    
    // Add a dropdown chevron (SF Symbol)
    UIImage *chevron = [UIImage systemImageNamed:@"chevron.down"];
    UIImageView *arrow = [[UIImageView alloc] initWithImage:chevron];
    arrow.translatesAutoresizingMaskIntoConstraints = NO;
    arrow.tintColor = [UIColor grayColor];
    [btn addSubview:arrow];
    
    // Position arrow on right side
    [NSLayoutConstraint activateConstraints:@[
        [arrow.centerYAnchor constraintEqualToAnchor:btn.centerYAnchor],
        [arrow.trailingAnchor constraintEqualToAnchor:btn.trailingAnchor constant:-12],
        [arrow.widthAnchor constraintEqualToConstant:12],
        [arrow.heightAnchor constraintEqualToConstant:8]
    ]];
    
    // Bring title above arrow
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 20);
    
    // Add tap handler (for menu)
    [btn addTarget:self action:@selector(handleDropdownTap:) forControlEvents:UIControlEventTouchUpInside];
    
    return btn;
}

- (void)handleDropdownTap:(UIButton *)sender {
    NSInteger tag = sender.tag;
    NSString *title = sender.titleLabel.text ?: @"Select";

    UIAlertController *menu = [UIAlertController alertControllerWithTitle:title
                                                                  message:nil
                                                           preferredStyle:UIAlertControllerStyleActionSheet];

    NSArray *options = @[];

    if (tag == 2001) { // Type dropdown
        NSMutableArray *typeNames = [NSMutableArray array];
        for (NSDictionary *type in self.types) {
            [typeNames addObject:type[@"type_name"] ?: @"Unnamed"];
        }
        options = typeNames;
    } else if (tag == 2002) { // Issue dropdown
        // Need selected type first
        if (!self.selectedTypeName) {
            UIAlertController *warn = [UIAlertController alertControllerWithTitle:@"Select Type First"
                                                                          message:@"Please select a type before choosing an issue."
                                                                   preferredStyle:UIAlertControllerStyleAlert];
            [warn addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
            [self presentViewController:warn animated:YES completion:nil];
            return;
        }

        // Find issues for the selected type
        NSArray *issuesForType = @[];
        for (NSDictionary *type in self.types) {
            if ([type[@"type_name"] isEqualToString:self.selectedTypeName]) {
                issuesForType = type[@"issue"];
                break;
            }
        }

        NSMutableArray *issueNames = [NSMutableArray array];
        for (NSDictionary *issue in issuesForType) {
            [issueNames addObject:issue[@"issue_name"] ?: @"Unnamed"];
        }
        options = issueNames;
    } else {
        // Category (fixed)
        if (self.categories.count > 0) {
            NSDictionary *cat = self.categories.firstObject;
            self.catName = cat[@"cat_name"] ?: @"-";
            [sender setTitle:self.catName forState:UIControlStateNormal];
            [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        return;
    }

    // Build alert actions
    for (NSString *opt in options) {
      [menu addAction:[UIAlertAction actionWithTitle:opt
                                               style:UIAlertActionStyleDefault
                                             handler:^(UIAlertAction * _Nonnull action) {
          [sender setTitle:opt forState:UIControlStateNormal];
          [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

          if (tag == 2001) {
              // === Type dropdown ===
              self.selectedTypeName = opt;
              self.selectedIssueID = nil; // reset previous issue selection
              [self.issueButton setTitle:@"- Select Issue -" forState:UIControlStateNormal];
              [self.issueButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
              NSLog(@"✅ Selected Type: %@", self.selectedTypeName);

          } else if (tag == 2002) {
              // === Issue dropdown ===
              NSArray *issuesForType = @[];
              for (NSDictionary *type in self.types) {
                  if ([type[@"type_name"] isEqualToString:self.selectedTypeName]) {
                      issuesForType = type[@"issue"];
                      break;
                  }
              }

              for (NSDictionary *issue in issuesForType) {
                  NSString *issueName = issue[@"issue_name"];
                  if ([issueName isEqualToString:opt]) {
                      self.selectedIssueID = [NSString stringWithFormat:@"%@", issue[@"issue_id"]];
                      NSLog(@"✅ Selected Issue: %@ (ID: %@)", issueName, self.selectedIssueID);
                      self.issueName = issueName;
                      break;
                  }
              }
          }
      }]];
    }

    [menu addAction:[UIAlertAction actionWithTitle:@"Cancel"
                                             style:UIAlertActionStyleCancel
                                           handler:nil]];

    [self presentViewController:menu animated:YES completion:nil];
}


- (UIButton *)makeUploadBox {
    UIButton *upload = [UIButton buttonWithType:UIButtonTypeCustom]; // ✅ not System
    upload.translatesAutoresizingMaskIntoConstraints = NO;
    upload.layer.borderWidth = 1.0;
    upload.layer.cornerRadius = 8;
    upload.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [upload setTitle:@"Upload" forState:UIControlStateNormal];
    [upload setTitleColor:[UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1] forState:UIControlStateNormal];
    [upload setImage:[UIImage systemImageNamed:@"camera"] forState:UIControlStateNormal];
    upload.tintColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    upload.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 8);
    upload.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [upload addTarget:self action:@selector(handleUploadTap:) forControlEvents:UIControlEventTouchUpInside];
    return upload;
}

- (void)handleUploadTap:(UIButton *)sender {
    NSInteger index = sender.tag - 1000;
    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"Upload Image"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Camera"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action) {
        [self openImagePickerForIndex:index source:UIImagePickerControllerSourceTypeCamera];
    }]];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Gallery"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action) {
        [self openImagePickerForIndex:index source:UIImagePickerControllerSourceTypePhotoLibrary];
    }]];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"
                                              style:UIAlertActionStyleCancel
                                            handler:nil]];

    [self presentViewController:sheet animated:YES completion:nil];
}

- (void)openImagePickerForIndex:(NSInteger)index source:(UIImagePickerControllerSourceType)source {
    if (![UIImagePickerController isSourceTypeAvailable:source]) return;

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = source;
    picker.view.tag = index; // store which slot this is for
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {

    UIImage *image = info[UIImagePickerControllerOriginalImage];
    NSInteger index = picker.view.tag; // will be 0–2 after fix

    // Store image
    if (self.isEditMode) {
        // Only new images go here
        [self.addedImages addObject:image];
    } else {
        // Normal add mode (keep using uploadedImages)
        if (index < self.uploadedImages.count) {
            self.uploadedImages[index] = image;
        } else {
            [self.uploadedImages addObject:image];
        }
    }

    // Update UI
    UIButton *button = [self.view viewWithTag:1000 + index];
  if ([button isKindOfClass:[UIButton class]]) {
    [button setTitle:nil forState:UIControlStateNormal];
    [button setImage:image forState:UIControlStateNormal];
    button.imageView.contentMode = UIViewContentModeScaleAspectFill;
    button.imageView.clipsToBounds = YES;
    button.layer.masksToBounds = YES;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
    button.imageEdgeInsets = UIEdgeInsetsZero;
    
    [self addRemoveButtonToUpload:button atIndex:index];
  }

    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)addRemoveButtonToUpload:(UIButton *)uploadBtn atIndex:(NSInteger)index {
    // Remove existing remove button if any (avoid duplicates)
    for (UIView *sub in uploadBtn.subviews) {
        if (sub.tag == 9000) {
            [sub removeFromSuperview];
        }
    }

    // Create small X button
    UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    removeBtn.tag = 9000;
    removeBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [removeBtn setImage:[UIImage systemImageNamed:@"xmark.circle.fill"] forState:UIControlStateNormal];
    removeBtn.tintColor = [UIColor whiteColor];
    removeBtn.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    removeBtn.layer.cornerRadius = 10;
    removeBtn.clipsToBounds = YES;
    removeBtn.contentEdgeInsets = UIEdgeInsetsMake(4, 4, 4, 4);
    removeBtn.accessibilityIdentifier = [NSString stringWithFormat:@"remove_%ld", (long)index];
    [removeBtn addTarget:self action:@selector(handleRemoveImage:) forControlEvents:UIControlEventTouchUpInside];

    [uploadBtn addSubview:removeBtn];

    // Position in top-right corner
    [NSLayoutConstraint activateConstraints:@[
        [removeBtn.topAnchor constraintEqualToAnchor:uploadBtn.topAnchor constant:4],
        [removeBtn.trailingAnchor constraintEqualToAnchor:uploadBtn.trailingAnchor constant:-4],
        [removeBtn.widthAnchor constraintEqualToConstant:20],
        [removeBtn.heightAnchor constraintEqualToConstant:20],
    ]];
}

- (void)handleRemoveImage:(UIButton *)sender {
    UIView *uploadBtn = sender.superview;
    if (![uploadBtn isKindOfClass:[UIButton class]]) return;

    NSInteger index = ((UIButton *)uploadBtn).tag - 1000;
    if (index < self.uploadedImages.count) {
        [self.uploadedImages removeObjectAtIndex:index];
    }

    // Reset upload button
    UIButton *button = (UIButton *)uploadBtn;
    [button setImage:[UIImage systemImageNamed:@"camera"] forState:UIControlStateNormal];
    [button setTitle:@"Upload" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1] forState:UIControlStateNormal];
    button.tintColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    button.imageView.contentMode = UIViewContentModeCenter;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 8);

    // Remove the small "x" button
    [sender removeFromSuperview];
}

- (void)handleReset {
    NSLog(@"🔄 Reset button tapped");

    // Leave Location and Category as-is
    // Reset Type, Issue, Comment, and Uploaded Images

    // Reset dropdowns for Type and Issue only
    UIButton *typeBtn = [self.view viewWithTag:2001];
    UIButton *issueBtn = [self.view viewWithTag:2002];
    
    if ([typeBtn isKindOfClass:[UIButton class]]) {
        [typeBtn setTitle:@"- Select Type -" forState:UIControlStateNormal];
        [typeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    if ([issueBtn isKindOfClass:[UIButton class]]) {
        [issueBtn setTitle:@"- Select Issue -" forState:UIControlStateNormal];
        [issueBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }

    // Reset comment box
    self.commentField.text = @"";

    // Clear uploaded images
    [self.uploadedImages removeAllObjects];
    // (Optionally refresh your upload boxes visually if they show previews)
    for (int i = 0; i < 3; i++) {
        UIButton *uploadBtn = [self.view viewWithTag:(1000 + i)];
        if ([uploadBtn isKindOfClass:[UIButton class]]) {
            [uploadBtn setBackgroundImage:nil forState:UIControlStateNormal];
            [uploadBtn setTitle:@"+" forState:UIControlStateNormal]; // or whatever placeholder you use
        }
    }

    // Show confirmation alert
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Fields Cleared"
                                                                   message:@"All inputs except Location and Category have been reset."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK"
                                              style:UIAlertActionStyleDefault
                                            handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - Actions

- (void)dismissSelf {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)handleSubmitTap {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Confirm Submission"
                                                                   message:@"Are you sure you want to submit this issue?"
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"Submit"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * _Nonnull action) {
        [self performSubmit]; // 👈 call your existing submission logic here
    }];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel"
                                                           style:UIAlertActionStyleCancel
                                                         handler:nil];

    [alert addAction:cancelAction];
    [alert addAction:confirmAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)performSubmit {
    NSLog(@"Location: %@\nCategory: %@\nType: %@\nIssue: %@", self.locationField.text, self.catName, self.selectedTypeName, self.issueName);
  
    NSDictionary *fieldNames = @{
      @"locationName": self.locationField.text ?: @"",
      @"categoryName": self.catName ?: @"",
      @"typeName": self.selectedTypeName ?: @"",
      @"issueName": self.issueName ?: @"",
    };
    
    if (self.isEditMode) {
        NSLog(@"📝 Updating existing issue instead of adding new one");

        if (self.isEditMode && !self.issueFullData) {
            NSLog(@"⚠️ Edit mode is ON, but no issueFullData passed!");
        }

        // ✅ Build update payload
        NSDictionary *updateData = @{
            @"location_id": self.locationID ?: @"",
            @"issue_id": self.issueFullData[@"issue_reference_id"] ?: @"0",
            @"issue_setting_id": self.selectedIssueID ?: @"",
            @"position_x": @(self.planX).stringValue ?: @"",
            @"position_y": @(self.planY).stringValue ?: @"",
            @"comment": self.commentField.text ?: @"",
            @"os": @"AND"
        };

        NSLog(@"📦 Sending UpdateIssue with data: %@", updateData);
      
        if (![NetworkManager.sharedManager isConnected]) {
            NSDictionary *displayData = @{
                @"projectName": self.projectName ?: @"Unknown Project",
                @"unitName": self.projectCode ?: @"-",
                @"createdBy": @"Athirah Zaidi",
                @"createdAt": [self todayDateString],
                @"issueDisplay": @"Edit Issue",
            };
          NSLog(@"edit issues displayData %@", displayData);

            [[OfflineSyncManager shared] queueUpdateIssue:updateData
                                                  display:displayData
                                                   images:self.addedImages
                                               fieldNames:fieldNames];
            [self showAlertWithTitle:@"Saved Offline"
                             message:@"This will be synced when you're back online."];
          
            UIViewController *presenter = self.presentingViewController;
            if (presenter.presentingViewController) {
                [presenter.presentingViewController dismissViewControllerAnimated:YES completion:nil];
                return;
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
                return;
            }
        }

        [APIClient submitUpdateIssue:updateData
                                       images:self.addedImages
                                   completion:^(BOOL success, NSDictionary *response, NSError *error){
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error) {
                    [self showAlertWithTitle:@"Update Failed" message:error.localizedDescription];
                    return;
                }

                NSDictionary *appData = response[@"AppData"];
                if ([appData[@"status"] isEqualToString:@"success"]) {
                    NSLog(@"✅ Issue updated successfully!");

                    UIAlertController *successAlert =
                        [UIAlertController alertControllerWithTitle:@"Issue Updated"
                                                            message:@"Your changes have been successfully saved."
                                                     preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK"
                                                                 style:UIAlertActionStyleDefault
                                                               handler:^(UIAlertAction * _Nonnull action) {
                        // ✅ Same navigation logic as Add Issue
                        UIViewController *presenter = self.presentingViewController;
                        if (presenter.presentingViewController) {
                            [presenter.presentingViewController dismissViewControllerAnimated:YES completion:nil];
                        } else {
                            [self dismissViewControllerAnimated:YES completion:nil];
                        }
                    }];

                    [successAlert addAction:ok];
                    [self presentViewController:successAlert animated:YES completion:nil];

                } else {
                    NSString *msg = appData[@"message"] ?: @"Unknown error occurred";
                    NSLog(@"⚠️ Update API Error: %@", msg);
                    [self showAlertWithTitle:@"Update Error" message:msg];
                }
            });
        }];
    } else {
        NSLog(@"Calling addIssue API:\n locationID: %@\n planID: %@\n locationID: %@\n selectedIssueID: %@\n XCoordinates: %f\n YCoordinates: %f\n commentField: %@",
              self.locationID,
              self.planID,
              self.locationID,
              self.selectedIssueID,
              self.planX,
              self.planY,
              self.commentField.text);
        
        NSDictionary *issueData = @{
            @"plan_id": self.planID ?: @"0",
            @"location_id": self.locationID ?: @"0",
            @"issue_setting_id": self.selectedIssueID ?: @"",
            @"position_x": [NSString stringWithFormat:@"%f", self.planX ?: 0.0],
            @"position_y": [NSString stringWithFormat:@"%f", self.planY ?: 0.0],
            @"comment": self.commentField.text ?: @"",
            @"os": @"AND"
        };
      
        if (![NetworkManager.sharedManager isConnected]) {
            NSDictionary *displayData = @{
                @"projectName": self.projectName ?: @"Unknown Project",
                @"unitName": self.projectCode ?: @"-",
                @"createdBy": @"Athirah Zaidi",
                @"createdAt": [self todayDateString],
                @"issueDisplay": @"Add Issue",
            };
            NSLog(@"add issue displayData %@", displayData);

            [[OfflineSyncManager shared] queueAddIssue:issueData
                                               display:displayData
                                                images:self.uploadedImages
                                            fieldNames:fieldNames];
            [self showAlertWithTitle:@"Saved Offline"
                             message:@"This will be synced when you're back online."];
          
            UIViewController *presenter = self.presentingViewController;
            if (presenter.presentingViewController) {
                [presenter.presentingViewController dismissViewControllerAnimated:YES completion:nil];
                return;
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
                return;
            }
        }

        [APIClient submitAddIssue:issueData
                                   images:self.uploadedImages
                               completion:^(BOOL success, NSDictionary *response, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error) {
                    NSLog(@"❌ Submission failed: %@", error.localizedDescription);
                    [self showAlertWithTitle:@"Submission Failed"
                                     message:error.localizedDescription ?: @"An unknown error occurred."];
                    return;
                }
                
                NSDictionary *appData = response[@"AppData"];
                if ([appData[@"status"] isEqualToString:@"success"]) {
                    NSLog(@"✅ Issue submitted successfully!");

                    UIAlertController *successAlert =
                        [UIAlertController alertControllerWithTitle:@"Issue Submitted"
                                                            message:@"Your issue has been successfully added."
                                                     preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK"
                                                                 style:UIAlertActionStyleDefault
                                                               handler:^(UIAlertAction * _Nonnull action) {
                        UIViewController *presenter = self.presentingViewController;
                        if (presenter.presentingViewController) {
                            [presenter.presentingViewController dismissViewControllerAnimated:YES completion:nil];
                        } else {
                            [self dismissViewControllerAnimated:YES completion:nil];
                        }
                    }];

                    [successAlert addAction:ok];
                    [self presentViewController:successAlert animated:YES completion:nil];

                } else {
                    NSString *msg = appData[@"message"] ?: @"Unexpected response from server.";
                    NSLog(@"⚠️ API Error: %@", msg);
                    [self showAlertWithTitle:@"Submission Error" message:msg];
                }
            });
        }];
    }
}

- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)dismissKeyboard {
    [self.view endEditing:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    CGRect kbFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat kbHeight = kbFrame.size.height;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, kbHeight + 20, 0);
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;

    // 👇 Optional: make sure comment field is visible
    [self.scrollView scrollRectToVisible:self.commentField.frame animated:YES];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    self.scrollView.contentInset = UIEdgeInsetsZero;
    self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
}

- (NSString *)todayDateString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    formatter.dateFormat = @"yyyy-MM-dd";
    return [formatter stringFromDate:[NSDate date]];
}

@end
