//  AccessTransactionViewController.mm

#import "AccessTransactionViewController.h"
#import <WebKit/WebKit.h>

@interface AccessTransactionViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIView *header;

// Sections
@property (nonatomic, strong) UIView *detailsCard;
@property (nonatomic, strong) UITableView *itemsTable;
@property (nonatomic, strong) UILabel *tncTitleLabel;
@property (nonatomic, strong) WKWebView *htmlView;
@property (nonatomic, strong) UILabel *remarksTitle;
@property (nonatomic, strong) UILabel *remarksText;
@property (nonatomic, strong) NSLayoutConstraint *itemsTableHeightConstraint;

@end

@implementation AccessTransactionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
  
    [self setupHeader];
    [self setupScrollView];
    [self setupDetailsCard];
    [self setupItemsTable];
    [self setupTermsSection];
    [self setupRemarksSection];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self updateItemsTableHeight];
}

#pragma mark - Header
- (void)setupHeader {
      self.header = [[UIView alloc] init];
      self.header.translatesAutoresizingMaskIntoConstraints = NO;
      self.header.backgroundColor = [UIColor colorWithRed:0 green:0.45 blue:0.55 alpha:1];
      [self.view addSubview:self.header];

      UILabel *titleLabel = [[UILabel alloc] init];
      titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
      titleLabel.textColor = UIColor.whiteColor;
      titleLabel.font = [UIFont boldSystemFontOfSize:18];
      titleLabel.text = @"Transaction Details"; // or Appointment Details
      [self.header addSubview:titleLabel];

      UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
      backBtn.translatesAutoresizingMaskIntoConstraints = NO;
      [backBtn setImage:[UIImage systemImageNamed:@"chevron.backward"] forState:UIControlStateNormal];
      backBtn.tintColor = UIColor.whiteColor;
      [backBtn addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
      [self.header addSubview:backBtn];

      [NSLayoutConstraint activateConstraints:@[
          [self.header.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
          [self.header.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
          [self.header.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
          [self.header.heightAnchor constraintEqualToConstant:48],

          [backBtn.leadingAnchor constraintEqualToAnchor:self.header.leadingAnchor constant:12],
          [backBtn.centerYAnchor constraintEqualToAnchor:self.header.centerYAnchor],

          [titleLabel.centerXAnchor constraintEqualToAnchor:self.header.centerXAnchor],
          [titleLabel.centerYAnchor constraintEqualToAnchor:self.header.centerYAnchor],
      ]];
}

#pragma mark - Scroll View
- (void)setupScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;

    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.contentView];

    [NSLayoutConstraint activateConstraints:@[
        [self.scrollView.topAnchor constraintEqualToAnchor:self.header.bottomAnchor constant:10],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],

        [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
        [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
        [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
        [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
        [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor]
    ]];
}

#pragma mark - Details Card
- (void)setupDetailsCard {
    // Title outside the card
    UILabel *title = [self bold18:@"Details"];
    [self.contentView addSubview:title];

    [NSLayoutConstraint activateConstraints:@[
        [title.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:10],
        [title.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [title.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
    ]];

    // Card
    UIView *card = [[UIView alloc] init];
    card.translatesAutoresizingMaskIntoConstraints = NO;
    card.backgroundColor = UIColor.whiteColor;
    card.layer.cornerRadius = 12;
    card.layer.shadowOpacity = 0.1;
    card.layer.shadowRadius = 4;
    card.layer.shadowOffset = CGSizeMake(0,2);
    [self.contentView addSubview:card];

    UILabel *unitNoLabel = [self regular16:[NSString stringWithFormat:@"Unit No: %@", self.unitID ?: @"--"]];
    UILabel *unitOwnerLabel = [self regular16:[NSString stringWithFormat:@"Unit Owner: %@", self.transactionData[@"owner_name"] ?: @"--"]];

    [card addSubview:unitNoLabel];
    [card addSubview:unitOwnerLabel];

    [NSLayoutConstraint activateConstraints:@[
        [card.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:8],
        [card.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [card.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],

        [unitNoLabel.topAnchor constraintEqualToAnchor:card.topAnchor constant:16],
        [unitNoLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
        [unitNoLabel.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-16],

        [unitOwnerLabel.topAnchor constraintEqualToAnchor:unitNoLabel.bottomAnchor constant:8],
        [unitOwnerLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
        [unitOwnerLabel.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-16],
        [unitOwnerLabel.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-16]
    ]];

    self.detailsCard = card;
}

#pragma mark - Items Table
- (void)setupItemsTable {
    // Title
    UILabel *itemsTitle = [[UILabel alloc] init];
    itemsTitle.translatesAutoresizingMaskIntoConstraints = NO;
    itemsTitle.font = [UIFont boldSystemFontOfSize:18];
    itemsTitle.text = @"Items";
    [self.contentView addSubview:itemsTitle];
    
    // Table
    self.itemsTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.itemsTable.translatesAutoresizingMaskIntoConstraints = NO;
    self.itemsTable.delegate = self;
    self.itemsTable.dataSource = self;
    self.itemsTable.scrollEnabled = NO; // let table expand naturally
    self.itemsTable.estimatedRowHeight = 44;
    self.itemsTable.rowHeight = UITableViewAutomaticDimension;
    self.itemsTable.separatorStyle = UITableViewCellSeparatorStyleNone; // we handle separators manually
    [self.contentView addSubview:self.itemsTable];

    // Table header
    UIView *header = [self createTableHeader];
    self.itemsTable.tableHeaderView = header;

    [header layoutIfNeeded];
    CGRect f = header.frame;
    f.size.height = [header systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    header.frame = f;
    self.itemsTable.tableHeaderView = header;

    // Layout
    [NSLayoutConstraint activateConstraints:@[
        [itemsTitle.topAnchor constraintEqualToAnchor:self.detailsCard.bottomAnchor constant:20],
        [itemsTitle.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],

        [self.itemsTable.topAnchor constraintEqualToAnchor:itemsTitle.bottomAnchor constant:8],
        [self.itemsTable.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.itemsTable.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
//        [self.itemsTable.bottomAnchor constraintEqualToAnchor:self.tncTitleLabel.topAnchor constant:-20], // let scrollview content size determine
    ]];
  
  self.itemsTableHeightConstraint =
      [self.itemsTable.heightAnchor constraintEqualToConstant:10];
  self.itemsTableHeightConstraint.active = YES;

}

- (UIView *)createTableHeader {
    NSArray *titles = @[@"No.", @"Item", @"Possession", @"Qty."];
    CGFloat flexes[] = {0.7, 1.3, 1.3, 0.7};
    CGFloat totalFlex = 0.7 + 1.3 + 1.3 + 0.7;
    CGFloat spacing = 12;

    UIView *header = [[UIView alloc] init];
    header.backgroundColor = UIColor.blackColor;

    UIView *container = [[UIView alloc] init];
    container.translatesAutoresizingMaskIntoConstraints = NO;
    [header addSubview:container];

    // Pin container edges to header
    [NSLayoutConstraint activateConstraints:@[
        [container.topAnchor constraintEqualToAnchor:header.topAnchor],
        [container.leadingAnchor constraintEqualToAnchor:header.leadingAnchor],
        [container.trailingAnchor constraintEqualToAnchor:header.trailingAnchor],
        [container.bottomAnchor constraintEqualToAnchor:header.bottomAnchor]
    ]];

    UILabel *prev = nil;
    for (int i = 0; i < titles.count; i++) {
        UILabel *lbl = [self createHeaderLabel:titles[i]];
        lbl.translatesAutoresizingMaskIntoConstraints = NO;
        [container addSubview:lbl];

        [NSLayoutConstraint activateConstraints:@[
            [lbl.topAnchor constraintEqualToAnchor:container.topAnchor constant:spacing],
            [lbl.bottomAnchor constraintEqualToAnchor:container.bottomAnchor constant:-spacing],
            [lbl.widthAnchor constraintEqualToAnchor:container.widthAnchor multiplier:flexes[i]/totalFlex]
        ]];

        if (prev) {
            [lbl.leadingAnchor constraintEqualToAnchor:prev.trailingAnchor].active = YES;
        } else {
            [lbl.leadingAnchor constraintEqualToAnchor:container.leadingAnchor].active = YES;
        }
        prev = lbl;

        // separator
        if (i < titles.count - 1) {
            UIView *sep = [[UIView alloc] init];
            sep.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
            sep.translatesAutoresizingMaskIntoConstraints = NO;
            [container addSubview:sep];

            [NSLayoutConstraint activateConstraints:@[
                [sep.widthAnchor constraintEqualToConstant:0.5],
                [sep.topAnchor constraintEqualToAnchor:container.topAnchor constant:spacing],
                [sep.bottomAnchor constraintEqualToAnchor:container.bottomAnchor constant:-spacing],
                [sep.leadingAnchor constraintEqualToAnchor:lbl.trailingAnchor]
            ]];
        }
    }

    // Force header height dynamically
    [header layoutIfNeeded];
    CGFloat height = [header systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    header.frame = CGRectMake(0, 0, self.itemsTable.frame.size.width, height);

    return header;
}

- (UILabel *)createHeaderLabel:(NSString *)text {
    UILabel *lbl = [[UILabel alloc] init];
    lbl.text = text;
    lbl.font = [UIFont boldSystemFontOfSize:14];
    lbl.textColor = UIColor.whiteColor;
    lbl.textAlignment = NSTextAlignmentCenter;
    return lbl;
}

- (void)updateItemsTableHeight {
    [self.itemsTable layoutIfNeeded];
    CGFloat height = self.itemsTable.contentSize.height;
    self.itemsTableHeightConstraint.constant = height;
    [self.view layoutIfNeeded];
}

#pragma mark - Terms Section
- (void)setupTermsSection {
    self.tncTitleLabel = [[UILabel alloc] init];
    self.tncTitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.tncTitleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.tncTitleLabel.text = @"Terms & Conditions";
    [self.contentView addSubview:self.tncTitleLabel];

    self.htmlView = [[WKWebView alloc] init];
    self.htmlView.translatesAutoresizingMaskIntoConstraints = NO;
    self.htmlView.scrollView.scrollEnabled = NO; // disable internal scrolling
    self.htmlView.navigationDelegate = (id<WKNavigationDelegate>)self; // set delegate for dynamic height
    [self.contentView addSubview:self.htmlView];

    [NSLayoutConstraint activateConstraints:@[
        [self.tncTitleLabel.topAnchor constraintEqualToAnchor:self.itemsTable.bottomAnchor constant:20],
        [self.tncTitleLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],

        [self.htmlView.topAnchor constraintEqualToAnchor:self.tncTitleLabel.bottomAnchor constant:8],
        [self.htmlView.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.htmlView.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        // initial height, will update dynamically
        [self.htmlView.heightAnchor constraintEqualToConstant:100]
    ]];

    // Load styled HTML
    if (self.termsContent && self.termsContent.length > 0) {
        NSString *styledHTML = [NSString stringWithFormat:
            @"<html>"
            "<head>"
            "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0\">"
            "<style>"
            "body { font-size: 14px; font-family: -apple-system; line-height: 1.5; padding: 12px; background-color: #F9F9F9; }"
            "p { margin-bottom: 12px; }"
            "</style>"
            "</head>"
            "<body>%@</body>"
            "</html>", self.termsContent];

        [self.htmlView loadHTMLString:styledHTML baseURL:nil];
    }
}

#pragma mark - WKNavigationDelegate
// Adjust webview height dynamically after content loads
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [webView evaluateJavaScript:@"document.body.scrollHeight;" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        if (!error && result) {
            CGFloat height = [result doubleValue];
            for (NSLayoutConstraint *constraint in webView.constraints) {
                if (constraint.firstAttribute == NSLayoutAttributeHeight) {
                    constraint.constant = height;
                    [UIView animateWithDuration:0.25 animations:^{
                        [self.view layoutIfNeeded];
                    }];
                    break;
                }
            }
        }
    }];
}

#pragma mark - Remarks Section
- (void)setupRemarksSection {
    // --- Remarks Title ---
    self.remarksTitle = [self bold18:@"Remarks"];
    [self.contentView addSubview:self.remarksTitle];

    // --- Remarks Text ---
    self.remarksText = [[UILabel alloc] init];
    self.remarksText.translatesAutoresizingMaskIntoConstraints = NO;
    self.remarksText.font = [UIFont systemFontOfSize:15];
    self.remarksText.numberOfLines = 0;
    self.remarksText.text = self.transactionData[@"remarks"] ?: @"--";
    [self.contentView addSubview:self.remarksText];

    // --- Submitted By ---
    UILabel *submittedTitle = [self bold18:@"Submitted By"];
    [self.contentView addSubview:submittedTitle];

    UIImageView *submittedSignature = [[UIImageView alloc] init];
    submittedSignature.translatesAutoresizingMaskIntoConstraints = NO;
    submittedSignature.contentMode = UIViewContentModeScaleAspectFit;
    submittedSignature.clipsToBounds = YES;
    submittedSignature.layer.borderColor = UIColor.blackColor.CGColor;
    submittedSignature.layer.borderWidth = 1.0;
    submittedSignature.layer.cornerRadius = 4.0; // optional rounded corners
    submittedSignature.clipsToBounds = YES;
    submittedSignature.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapSubmitted = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapSignature:)];
    [submittedSignature addGestureRecognizer:tapSubmitted];
    NSURL *submittedURL = [NSURL URLWithString:self.transactionData[@"signature_submit"]];
    if (submittedURL) {
        // Simple async load
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL:submittedURL];
            if (data) {
                UIImage *img = [UIImage imageWithData:data];
                dispatch_async(dispatch_get_main_queue(), ^{
                    submittedSignature.image = img;
                });
            }
        });
    }
    [self.contentView addSubview:submittedSignature];

    UILabel *submittedName = [self regular16:[NSString stringWithFormat:@"Name: %@", self.transactionData[@"name_submit"] ?: @"--"]];
    [self.contentView addSubview:submittedName];

    UILabel *submittedDate = [self regular16:[NSString stringWithFormat:@"Date: %@", self.transactionData[@"signature_submit_datetime"] ?: @"--"]];
    [self.contentView addSubview:submittedDate];

    // --- Received By ---
    UILabel *receivedTitle = [self bold18:@"Received By"];
    [self.contentView addSubview:receivedTitle];

    UIImageView *receivedSignature = [[UIImageView alloc] init];
    receivedSignature.translatesAutoresizingMaskIntoConstraints = NO;
    receivedSignature.contentMode = UIViewContentModeScaleAspectFit;
    receivedSignature.clipsToBounds = YES;
    receivedSignature.layer.borderColor = UIColor.blackColor.CGColor;
    receivedSignature.layer.borderWidth = 1.0;
    receivedSignature.layer.cornerRadius = 4.0;
    receivedSignature.clipsToBounds = YES;
    receivedSignature.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapReceived = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapSignature:)];
    [receivedSignature addGestureRecognizer:tapReceived];
    NSURL *receivedURL = [NSURL URLWithString:self.transactionData[@"signature_receive"]];
    if (receivedURL) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL:receivedURL];
            if (data) {
                UIImage *img = [UIImage imageWithData:data];
                dispatch_async(dispatch_get_main_queue(), ^{
                    receivedSignature.image = img;
                });
            }
        });
    }
    [self.contentView addSubview:receivedSignature];

    UILabel *receivedName = [self regular16:[NSString stringWithFormat:@"Name: %@", self.transactionData[@"name_receive"] ?: @"--"]];
    [self.contentView addSubview:receivedName];

    UILabel *receivedDate = [self regular16:[NSString stringWithFormat:@"Date: %@", self.transactionData[@"signature_receive_datetime"] ?: @"--"]];
    [self.contentView addSubview:receivedDate];

    // --- Constraints ---
    CGFloat spacing = 8;
    [NSLayoutConstraint activateConstraints:@[
        // Remarks
        [self.remarksTitle.topAnchor constraintEqualToAnchor:self.htmlView.bottomAnchor constant:10],
        [self.remarksTitle.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.remarksText.topAnchor constraintEqualToAnchor:self.remarksTitle.bottomAnchor constant:spacing],
        [self.remarksText.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [self.remarksText.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],

        // Submitted By
        [submittedTitle.topAnchor constraintEqualToAnchor:self.remarksText.bottomAnchor constant:spacing*2],
        [submittedTitle.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],

        [submittedSignature.topAnchor constraintEqualToAnchor:submittedTitle.bottomAnchor constant:spacing],
        [submittedSignature.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [submittedSignature.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        [submittedSignature.heightAnchor constraintEqualToConstant:180],

        [submittedName.topAnchor constraintEqualToAnchor:submittedSignature.bottomAnchor constant:spacing],
        [submittedName.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],

        [submittedDate.topAnchor constraintEqualToAnchor:submittedName.bottomAnchor constant:spacing],
        [submittedDate.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],

        // Received By
        [receivedTitle.topAnchor constraintEqualToAnchor:submittedDate.bottomAnchor constant:spacing*2],
        [receivedTitle.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],

        [receivedSignature.topAnchor constraintEqualToAnchor:receivedTitle.bottomAnchor constant:spacing],
        [receivedSignature.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],
        [receivedSignature.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-16],
        [receivedSignature.heightAnchor constraintEqualToConstant:180],

        [receivedName.topAnchor constraintEqualToAnchor:receivedSignature.bottomAnchor constant:spacing],
        [receivedName.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],

        [receivedDate.topAnchor constraintEqualToAnchor:receivedName.bottomAnchor constant:spacing],
        [receivedDate.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:16],

        [receivedDate.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-40]
    ]];
}

- (void)onTapSignature:(UITapGestureRecognizer *)sender {
    UIImageView *imgView = (UIImageView *)sender.view;
    if (!imgView.image) return;

    // Create full-screen viewer
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view.backgroundColor = UIColor.blackColor;

    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:vc.view.bounds];
    scroll.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    scroll.minimumZoomScale = 1.0;
    scroll.maximumZoomScale = 3.0;
    scroll.delegate = (id<UIScrollViewDelegate>)self;
    [vc.view addSubview:scroll];

    UIImageView *zoomImage = [[UIImageView alloc] initWithImage:imgView.image];
    zoomImage.frame = scroll.bounds;
    zoomImage.contentMode = UIViewContentModeScaleAspectFit;
    zoomImage.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [scroll addSubview:zoomImage];
  
    // Tag to identify for zoom delegate
    zoomImage.tag = 100;
  
    UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissViewer)];
    [vc.view addGestureRecognizer:dismissTap];

    // Present full-screen
    [self presentViewController:vc animated:YES completion:nil];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return [scrollView viewWithTag:100];
}

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

#pragma mark - Table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *items = self.transactionData[@"items"];
    return items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"TransactionItemCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    // Clear previous content
    for (UIView *v in cell.contentView.subviews) [v removeFromSuperview];

    NSDictionary *item = self.transactionData[@"items"][indexPath.row];

    UIView *container = [[UIView alloc] init];
    container.translatesAutoresizingMaskIntoConstraints = NO;
    [cell.contentView addSubview:container];
    
    [NSLayoutConstraint activateConstraints:@[
        [container.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor],
        [container.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor],
        [container.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor],
        [container.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor]
    ]];

    // Columns
    NSArray *texts = @[
        [NSString stringWithFormat:@"%ld", indexPath.row+1],
        item[@"name"] ?: @"--",
        self.transactionData[@"possession"] ?: @"--",
        [NSString stringWithFormat:@"%@", item[@"quantity"] ?: @"0"]
    ];
    CGFloat flexes[] = {0.7, 1.3, 1.3, 0.7};
    CGFloat totalFlex = 0.7+1.3+1.3+0.7;

    UILabel *prev = nil;
    for (int i = 0; i < texts.count; i++) {
        UILabel *col = [self createCellLabel:texts[i]];
        col.textAlignment = NSTextAlignmentCenter;
        [container addSubview:col];
        col.translatesAutoresizingMaskIntoConstraints = NO;
        col.adjustsFontSizeToFitWidth = YES;
        col.minimumScaleFactor = 0.5;

        [NSLayoutConstraint activateConstraints:@[
            [col.topAnchor constraintEqualToAnchor:container.topAnchor constant:12],
            [col.bottomAnchor constraintEqualToAnchor:container.bottomAnchor constant:-12],
            [col.widthAnchor constraintEqualToAnchor:container.widthAnchor multiplier:flexes[i]/totalFlex]
        ]];

        if (prev) {
            [col.leadingAnchor constraintEqualToAnchor:prev.trailingAnchor].active = YES;
        } else {
            [col.leadingAnchor constraintEqualToAnchor:container.leadingAnchor].active = YES;
        }
        prev = col;

        // separator
        if (i < texts.count - 1) {
            UIView *sep = [[UIView alloc] init];
            sep.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
            sep.translatesAutoresizingMaskIntoConstraints = NO;
            [container addSubview:sep];
            [NSLayoutConstraint activateConstraints:@[
                [sep.widthAnchor constraintEqualToConstant:0.5],
                [sep.topAnchor constraintEqualToAnchor:container.topAnchor constant:12],
                [sep.bottomAnchor constraintEqualToAnchor:container.bottomAnchor constant:-12],
                [sep.leadingAnchor constraintEqualToAnchor:col.trailingAnchor]
            ]];
        }
    }

    return cell;
}

#pragma mark - Helpers
- (void)onBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (UILabel *)bold18:(NSString *)text {
    UILabel *lbl = [[UILabel alloc] init];
    lbl.translatesAutoresizingMaskIntoConstraints = NO;
    lbl.font = [UIFont boldSystemFontOfSize:18];
    lbl.text = text;
    return lbl;
}

- (UILabel *)regular16:(NSString *)text {
    UILabel *lbl = [[UILabel alloc] init];
    lbl.translatesAutoresizingMaskIntoConstraints = NO;
    lbl.font = [UIFont systemFontOfSize:16];
    lbl.textColor = UIColor.darkGrayColor;
    lbl.text = text;
    return lbl;
}

- (NSString *)formattedDate:(NSString *)dateStr {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *date = [df dateFromString:dateStr];
    if (!date) return dateStr;
    
    NSDateFormatter *output = [[NSDateFormatter alloc] init];
    output.dateFormat = @"dd MMM yyyy h:mm a";
    return [output stringFromDate:date];
}

- (UILabel *)createCellLabel:(NSString *)text {
    UILabel *lbl = [[UILabel alloc] init];
    lbl.font = [UIFont systemFontOfSize:15];
    lbl.numberOfLines = 0;
    lbl.lineBreakMode = NSLineBreakByWordWrapping;
    lbl.text = text;
    return lbl;
}

@end

