//  AddIssueAPIClient.mm

#import "AddIssueAPIClient.h"

@implementation AddIssueAPIClient

+ (void)fetchGetUnitPlan:(void (^)(NSDictionary *data, NSError *error))completion {

    // ✅ Construct URL (with token)
    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/plan/getLocationByUnit?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";

    // 🧱 multipart/form-data setup (same as fetchAnnouncement)
    NSString *boundary = [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];

    NSMutableData *body = [NSMutableData data];

    // 👇 Helper block to add form fields
    void (^appendFormField)(NSString *, NSString *) = ^(NSString *key, NSString *value) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary]
                          dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:
                           @"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key]
                          dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n", value]
                          dataUsingEncoding:NSUTF8StringEncoding]];
    };

    // 🧩 Add POST fields
    appendFormField(@"data[os]", @"AND");
    appendFormField(@"data[drawing_plan_id]",@"135");

    // You can reuse your existing getDeviceInfo() method to produce this JSON string
    NSString *deviceInfo = @"{\"OS\":\"AND\",\"IMEI\":\"AND:2a2f13ff17b1cbb5\",\"OS_VERSION\":\"35\",\"MODEL\":\"2306EPN60G\",\"APP_VERSION\":\"1.22.26\"}";
    appendFormField(@"data[information]", deviceInfo);

    // 🔚 End boundary
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary]
                      dataUsingEncoding:NSUTF8StringEncoding]];
    request.HTTPBody = body;

    // 🌍 Debug logs
    NSLog(@"🌍 [fetchUnitPlan] URL: %@", urlString);
    NSLog(@"📦 [fetchUnitPlan] Body:\n%@", [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding]);

    // 🌐 Perform request
    NSURLSessionDataTask *task = [[NSURLSession sharedSession]
        dataTaskWithRequest:request
          completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        if (error) {
            NSLog(@"❌ [fetchUnitPlan] Network error: %@", error);
            if (completion) completion(nil, error);
            return;
        }

        NSError *jsonErr;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonErr];

        if (jsonErr) {
            NSLog(@"❌ [fetchUnitPlan] JSON parse error: %@", jsonErr);
            if (completion) completion(nil, jsonErr);
            return;
        }

        NSLog(@"✅ [fetchUnitPlan] Response:\n%@", json);

        NSDictionary *appData = json[@"AppData"];
        if ([appData[@"status"] isEqualToString:@"success"]) {
            NSLog(@"📄 Successfully fetched unit plan for ID");
        } else if (appData[@"error_code"] && [appData[@"error_code"] integerValue] == 503) {
            NSLog(@"⚠️ Server under maintenance (503)");
        } else {
            NSLog(@"⚠️ API returned failure: %@", appData[@"message"]);
        }

        // ✅ Call back on main thread
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(json, nil);
            });
        }
    }];

    [task resume];
}

+ (void)fetchSettingsByLocation:(NSString *)locationID
                     projectID:(NSString *)projectID
                    completion:(void (^)(NSDictionary *data, NSError *error))completion {
    NSString *urlString = @"https://kitadev.commudesk.com/api/issue/getGeneralSettingByLocation?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";

    // 🧱 multipart/form-data setup
    NSString *boundary = [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];

    NSMutableData *body = [NSMutableData data];

    // Helper block for adding form fields
    void (^appendFormField)(NSString *, NSString *) = ^(NSString *key, NSString *value) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary]
                          dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:
                           @"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key]
                          dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n", value]
                          dataUsingEncoding:NSUTF8StringEncoding]];
    };

    // 🧩 Add POST fields
    appendFormField(@"data[os]", @"AND");
    appendFormField(@"data[project_id]", projectID ?: @"0");
    appendFormField(@"data[location_id]", locationID ?: @"0");

    NSString *deviceInfo = @"{\"OS\":\"AND\",\"IMEI\":\"AND:2a2f13ff17b1cbb5\",\"OS_VERSION\":\"35\",\"MODEL\":\"2306EPN60G\",\"APP_VERSION\":\"1.22.26\"}";
    appendFormField(@"data[information]", deviceInfo);
  
    // End boundary
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary]
                      dataUsingEncoding:NSUTF8StringEncoding]];
    request.HTTPBody = body;

    // 🌍 Debug logs
    NSLog(@"🌍 [fetchSettingsByLocation] URL: %@", urlString);
    NSLog(@"📦 [fetchSettingsByLocation] Body:\n%@", [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding]);

    // 🌐 Send request
    NSURLSessionDataTask *task = [[NSURLSession sharedSession]
        dataTaskWithRequest:request
          completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        if (error) {
            NSLog(@"❌ [fetchSettingsByLocation] Network error: %@", error);
            if (completion) completion(nil, error);
            return;
        }

        NSError *jsonErr;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonErr];
        if (jsonErr) {
            NSLog(@"❌ JSON parse error: %@", jsonErr);
            if (completion) completion(nil, jsonErr);
            return;
        }

        NSLog(@"✅ [fetchSettingsByLocation] Response:\n%@", json);

        NSDictionary *appData = json[@"AppData"];
        NSString *status = appData[@"status"];

        if ([status isEqualToString:@"success"]) {
            NSLog(@"📄 Successfully fetched settings for location");
        }
        else if ([appData[@"error_code"] integerValue] == 503) {
            NSLog(@"⚠️ Maintenance mode (503)");
        }
        else {
            NSLog(@"⚠️ Failed: %@", appData[@"message"]);
        }

        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(json, nil);
            });
        }
    }];

    [task resume];
}

+ (void)submitAddIssue:(NSDictionary *)issueData
                images:(NSArray<UIImage *> * _Nullable)images
            completion:(void (^)(NSDictionary * _Nullable response, NSError * _Nullable error))completion {

  NSString *urlString = @"https://kitadev.commudesk.com/api/owner/issue/addIssue?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
  
    // 🧱 Multipart body
    NSString *boundary = [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]
   forHTTPHeaderField:@"Content-Type"];

    NSMutableData *body = [NSMutableData data];

    // Helper for adding form fields
    void (^appendFormField)(NSString *, NSString *) = ^(NSString *key, NSString *value) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key]
                          dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n", value]
                          dataUsingEncoding:NSUTF8StringEncoding]];
    };

    // 🔹 Append form data fields
    for (NSString *key in issueData.allKeys) {
        id value = issueData[key];
        if ([value isKindOfClass:[NSNumber class]]) value = [(NSNumber *)value stringValue];
        if ([value isKindOfClass:[NSString class]]) {
            appendFormField([NSString stringWithFormat:@"data[%@]", key], value);
        }
    }

    // 🔹 Append OS info
    appendFormField(@"data[os]", @"AND");

    // 🔹 Append images
    if (images.count > 0) {
        for (int i = 0; i < images.count; i++) {
            id maybeImage = images[i];
            if (![maybeImage isKindOfClass:[UIImage class]]) {
                NSLog(@"⚠️ Skipping non-UIImage at index %d: %@", i, maybeImage);
                continue; // skip invalid entries
            }

            UIImage *image = (UIImage *)maybeImage;
            NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
            if (!imageData) continue;

            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary]
                              dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:
                               @"Content-Disposition: form-data; name=\"data[image][%d]\"; filename=\"image%d.jpg\"\r\n", i, i]
                              dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:imageData];
            [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }

    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary]
                      dataUsingEncoding:NSUTF8StringEncoding]];
    request.HTTPBody = body;

    // Debug
    NSLog(@"📦 [AddIssue] Uploading %lu image(s)", (unsigned long)images.count);

    NSURLSessionDataTask *task = [[NSURLSession sharedSession]
        dataTaskWithRequest:request
          completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"❌ [AddIssue] Network error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{ if (completion) completion(nil, error); });
            return;
        }

        NSError *jsonErr;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonErr];
        if (jsonErr) {
            NSString *raw = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"⚠️ [AddIssue] JSON parse error: %@\nRaw response: %@", jsonErr, raw);
            dispatch_async(dispatch_get_main_queue(), ^{ if (completion) completion(nil, jsonErr); });
            return;
        }

        NSLog(@"✅ [AddIssue] Response: %@", json);
        dispatch_async(dispatch_get_main_queue(), ^{ if (completion) completion(json, nil); });
    }];

    [task resume];
}


+ (void)submitUpdateIssue:(NSDictionary *)updateData
                images:(NSArray<UIImage *> * _Nullable)images
               completion:(void (^)(NSDictionary * _Nullable response, NSError * _Nullable error))completion {
  
  NSString *urlString = @"https://kitadev.commudesk.com/api/owner/issue/updateIssue?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";    NSURL *url = [NSURL URLWithString:urlString];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  request.HTTPMethod = @"POST";
  
  // 🧱 Multipart body setup
  NSString *boundary = [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];
  [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]
 forHTTPHeaderField:@"Content-Type"];
  
  NSMutableData *body = [NSMutableData data];
  
  // Helper for form fields
  void (^appendFormField)(NSString *, NSString *) = ^(NSString *key, NSString *value) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary]
                      dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:
                       @"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key]
                      dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", value]
                      dataUsingEncoding:NSUTF8StringEncoding]];
  };
  
  // 🔹 Append update fields (all under data[])
  for (NSString *key in updateData.allKeys) {
    id value = updateData[key];
    if ([value isKindOfClass:[NSNumber class]]) value = [(NSNumber *)value stringValue];
    if ([value isKindOfClass:[NSString class]]) {
      appendFormField([NSString stringWithFormat:@"data[%@]", key], value);
    }
  }
  
  // 🔹 Always include OS
  appendFormField(@"data[plan_id]", @"135");
  appendFormField(@"data[location_id]", updateData[@"location_id"]);
  appendFormField(@"data[issue_id]", updateData[@"issue_id"]);
  appendFormField(@"data[issue_setting_id]", updateData[@"issue_setting_id"]);
  appendFormField(@"data[position_x]", updateData[@"position_x"]);
  appendFormField(@"data[position_y]", updateData[@"position_y"]);
  appendFormField(@"data[comment]", updateData[@"comment"]);
  appendFormField(@"data[os]", updateData[@"os"]);
  
  // 🔹 Add `information` field (as JSON string)
//  NSString *deviceInfo = @"{\"OS\":\"AND\",\"IMEI\":\"AND:2a2f13ff17b1cbb5\",\"OS_VERSION\":\"35\",\"MODEL\":\"2306EPN60G\",\"APP_VERSION\":\"1.22.26\"}";
//  appendFormField(@"information", deviceInfo);
  
  // 🔹 Append image files
  for (int i = 0; i < images.count; i++) {
      id maybeImage = images[i];
      if (![maybeImage isKindOfClass:[UIImage class]]) {
        NSLog(@"⚠️ Skipping non-UIImage at index %d: %@", i, maybeImage);
        continue; // skip invalid entries
      }
      
      UIImage *image = (UIImage *)maybeImage;
      NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
      if (!imageData) continue;
      
      [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary]
                        dataUsingEncoding:NSUTF8StringEncoding]];
      [body appendData:[[NSString stringWithFormat:
                         @"Content-Disposition: form-data; name=\"data[image][%d]\"; filename=\"image%d.jpg\"\r\n", i, i]
                        dataUsingEncoding:NSUTF8StringEncoding]];
      [body appendData:[@"Content-Type: image/jpeg\r\n\r\n"
                        dataUsingEncoding:NSUTF8StringEncoding]];
      [body appendData:imageData];
      [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary]
                      dataUsingEncoding:NSUTF8StringEncoding]];
    request.HTTPBody = body;
    
    NSLog(@"📦 [UpdateIssue] Uploading %lu image(s)", (unsigned long)images.count);
    
    // 🔹 Execute request
    NSURLSessionDataTask *task = [[NSURLSession sharedSession]
                                  dataTaskWithRequest:request
                                  completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
      
      if (error) {
        NSLog(@"❌ [UpdateIssue] Network error: %@", error);
        dispatch_async(dispatch_get_main_queue(), ^{
          if (completion) completion(nil, error);
        });
        return;
      }
      
      NSError *jsonErr;
      NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonErr];
      if (jsonErr) {
        NSString *raw = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"⚠️ [UpdateIssue] JSON parse error: %@\nRaw: %@", jsonErr, raw);
        dispatch_async(dispatch_get_main_queue(), ^{
          if (completion) completion(nil, jsonErr);
        });
        return;
      }
      
      NSLog(@"✅ [UpdateIssue] Response: %@", json);
      dispatch_async(dispatch_get_main_queue(), ^{
        if (completion) completion(json, nil);
      });
    }];
    [task resume];
  }


@end
