//  APIClient.mm

#import "APIClient.h"

@implementation APIClient

+ (void)fetchAccessItem:(NSString *)unitId
                        completion:(void(^)(BOOL success, NSDictionary * _Nullable response, NSError * _Nullable error))completion {

    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/plan/getAccessItem?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSDictionary *deviceInfo = @{
        @"OS": @"AND",
        @"IMEI": @"AND:2a2f13ff17b1cbb5",
        @"OS_VERSION": @"35",
        @"MODEL": @"2306EPN60G",
        @"APP_VERSION": @"1.22.26"
    };

    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
            @"drawing_plan_id": unitId ?: @"",
            @"information": deviceInfo,
        }
    };
  
    NSLog(@"🌍 SUBMIT URL: %@", urlString);
    NSLog(@"📦 SUBMIT Body JSON: %@", jsonBody);
    
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];

    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(NO, nil, jsonError);
        return;
    }

    request.HTTPBody = bodyData;

    NSLog(@"🔄 SUBMIT (NO REP) Request started...");

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil, error);
            });
            return;
        }

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

        if (parseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", parseError);
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil, parseError);
            });
            return;
        }

        NSLog(@"✅ SUBMIT (NO REP) API Response:\n%@", json);

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

    [task resume];
}

+ (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];
  }

+ (void)fetchAppointment:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/appointment/getSlot?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    // ✅ Build JSON body
    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
            @"project_id": @"8",
            @"drawing_plan_id": @"135"
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ Appointment API Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

+ (void)fetchGeneralInfo:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/plan/getUnitInfo?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    // ✅ Build JSON body
    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
            @"drawing_plan_id": @"135"
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ General Info API Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

+ (void)submitAppointment:(NSDictionary *)appointmentData
                        completion:(void(^)(BOOL success, NSDictionary * _Nullable response, NSError * _Nullable error))completion {

    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/appointment/makeAppointment?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];

    NSLog(@"🌍 SUBMIT (NO REP) URL: %@", urlString);
    NSLog(@"📦 SUBMIT (NO REP) Body JSON: %@", appointmentData);

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSDictionary *bodyDict = @{@"data": appointmentData};
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:bodyDict options:0 error:&jsonError];

    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(NO, nil, jsonError);
        return;
    }

    request.HTTPBody = bodyData;

    NSLog(@"🔄 SUBMIT (NO REP) Request started...");

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil, error);
            });
            return;
        }

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

        if (parseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", parseError);
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil, parseError);
            });
            return;
        }

        NSLog(@"✅ SUBMIT (NO REP) API Response:\n%@", json);

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

    [task resume];
}

+ (void)submitRepresentativeAppointment:(NSDictionary *)repData
                              completion:(void(^)(BOOL success, NSDictionary * _Nullable response, NSError * _Nullable error))completion {


    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/appointment/makeAppointment?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];
    NSLog(@"🌍 SUBMIT URL: %@", urlString);

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

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

    NSMutableData *body = [NSMutableData data];

    // Add repData fields as text fields
    for (NSString *key in repData) {
        NSString *value = [NSString stringWithFormat:@"%@", repData[key]]; // ensure string
        NSString *field = [NSString stringWithFormat:
            @"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",
            boundary, key, value];
        [body appendData:[field dataUsingEncoding:NSUTF8StringEncoding]];
    }

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

    NSLog(@"🔄 Request started with body (%lu bytes)", (unsigned long)body.length);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil, error);
            });
            return;
        }

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

        if (parseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", parseError);
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil, parseError);
            });
            return;
        }

        NSLog(@"✅ API Response:\n%@", json);
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(YES, json, nil);
        });
    }];

    [task resume];
}

+ (void)fetchCancelAppointment:(id)appointmentId
               reason:(NSString *)reason
            completion:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/appointment/cancelAppointment?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];

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

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    // ✅ Build JSON body
    NSDictionary *jsonBody = @{
        @"data": @{
            @"project_id": @"8",
            @"appointment_id": appointmentId,
            @"reason": reason
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ Fetch Cancel Appointment Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

+ (void)fetchDashboardInfo:(void (^)(NSDictionary *data, NSError *error))completion {
  NSString *urlString = @"https://kitadev.commudesk.com/api/owner/plan/getIssueUpdateAppointmentInfo";
  NSURL *url = [NSURL URLWithString:urlString];
  
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  request.HTTPMethod = @"POST";
  
  // 🪪 Authorization header
  NSString *token = @"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
  [request setValue:[NSString stringWithFormat:@"Bearer %@", token] forHTTPHeaderField:@"Authorization"];
  
  // 🧱 Create multipart form-data body
  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 append 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 form fields
  appendFormField(@"data[os]", @"AND");
  appendFormField(@"data[drawing_plan_id]", @"135");
  
  NSString *infoJson = @"{\"OS\":\"AND\",\"IMEI\":\"AND:2a2f13ff17b1cbb5\",\"OS_VERSION\":\"35\",\"MODEL\":\"2306EPN60G\",\"APP_VERSION\":\"1.22.26\"}";
  appendFormField(@"data[information]", infoJson);
  
  [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
  
  request.HTTPBody = body;
  
  // 🌍 Debug logs
  NSLog(@"🌍 URL: %@", urlString);
  NSLog(@"🪪 Authorization: Bearer %@", token);
  NSLog(@"📦 Body:\n%@", [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding]);
  
  NSURLSessionDataTask *task = [[NSURLSession sharedSession]
                                dataTaskWithRequest:request
                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
      NSLog(@"❌ Network error: %@", error);
      if (completion) completion(nil, error);
      return;
    }
    
    NSError *jsonErr;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonErr];
    NSLog(@"🧩 Dashboard Info response: %@", json);
    
    if (completion) {
      dispatch_async(dispatch_get_main_queue(), ^{
        completion(json, jsonErr);
      });
    }
  }];
  [task resume];
}

+ (void)fetchAnnouncement:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ Keep token in URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/clientAnnouncement?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];

    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 form fields (same as DashboardInfo)
    appendFormField(@"data[os]", @"AND");
    appendFormField(@"data[project_id]", @"8");
    appendFormField(@"data[client_id]", @"3");

    NSString *infoJson = @"{\"OS\":\"AND\",\"IMEI\":\"AND:2a2f13ff17b1cbb5\",\"OS_VERSION\":\"35\",\"MODEL\":\"2306EPN60G\",\"APP_VERSION\":\"1.22.26\"}";
    appendFormField(@"data[information]", infoJson);

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

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

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

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

        NSError *jsonErr;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonErr];
        NSLog(@"✅ Announcement API response:\n%@", json);

        NSDictionary *appData = json[@"AppData"];
        NSArray *announcements = @[];

        if ([appData[@"status"] isEqualToString:@"success"]) {
            announcements = json[@"Data"];
            NSLog(@"📣 Got %lu announcements", (unsigned long)announcements.count);
        } else {
            NSLog(@"⚠️ Announcement fetch failed: %@", appData[@"message"]);
        }

        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
              completion(json, jsonErr);
            });
        }
    }];
    [task resume];
}

+ (void)fetchHistory:(NSString *)issueID
                    completion:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/issue/getIssueHistory?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];

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

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    // ✅ Build JSON body
    NSDictionary *deviceInfo = @{
        @"OS": @"AND",
        @"IMEI": @"AND:2a2f13ff17b1cbb5",
        @"OS_VERSION": @"35",
        @"MODEL": @"2306EPN60G",
        @"APP_VERSION": @"1.22.26"
    };

    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
            @"issue_id": issueID,
            @"information": deviceInfo
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ Issues API Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

+(void)fetchAddInfo:(NSString *)issueID
                    remarks:(NSString *)remarks
                    completion:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/issue/addInfo?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];

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

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    // ✅ Build JSON body
    NSDictionary *deviceInfo = @{
        @"OS": @"AND",
        @"IMEI": @"AND:2a2f13ff17b1cbb5",
        @"OS_VERSION": @"35",
        @"MODEL": @"2306EPN60G",
        @"APP_VERSION": @"1.22.26"
    };

    NSDictionary *jsonBody = @{
        @"data": @{
            @"issue_id": issueID,
            @"remarks": remarks,
            @"os": @"AND",
            @"full_response": @"false",
            @"information": deviceInfo
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ Issues API Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

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

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

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    // ✅ Build JSON body
    NSDictionary *deviceInfo = @{
        @"OS": @"AND",
        @"IMEI": @"AND:2a2f13ff17b1cbb5",
        @"OS_VERSION": @"35",
        @"MODEL": @"2306EPN60G",
        @"APP_VERSION": @"1.22.26"
    };

    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
            @"drawing_plan_id": @"135",
            @"information": deviceInfo
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ Issues API Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

+ (void)fetchVoidIssue:(id)issueID
               remarks:(NSString *)remarks
            completion:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/issue/voidIssue?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];

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

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
  
    // json checks
    NSArray *issueArray = issueID;
      if (![issueID isKindOfClass:[NSArray class]]) {
          issueArray = @[ issueID ?: @"" ];
      }
      NSString *remarksSafe = remarks ?: @"";

    // ✅ Build JSON body
    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
            @"issue_id": issueArray,
            @"remarks": remarksSafe
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ Void Issues API Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

+ (void)fetchDeleteIssue:(NSString *)issueID
               remarks:(NSString *)remarks
            completion:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/issue/deleteIssue?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];

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

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
  
    // ✅ Build JSON body
    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
            @"issue_id": issueID ?: @"",
            @"remarks": remarks ?: @""
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ Delete Issues API Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

+ (void)fetchCommonArea:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/plan/getCommonArea?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    // ✅ Device info dictionary
    NSDictionary *deviceInfo = @{
        @"OS": @"AND",
        @"IMEI": @"AND:2a2f13ff17b1cbb5",
        @"OS_VERSION": @"35",
        @"MODEL": @"2306EPN60G",
        @"APP_VERSION": @"1.22.26"
    };

    // ✅ Build JSON body
    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
            @"project_id": @"8",
            @"information": deviceInfo,
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ Common Area API Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

+ (void)fetchGeneralSettings:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/plan/getCommonArea?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    // ✅ Build JSON body
    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
            @"project_id": @"8",
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ General Settings API Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

+ (void)fetchDefectMatrix:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/issue/getGeneralSettingByUnit?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    // ✅ Device info dictionary
    NSDictionary *deviceInfo = @{
        @"OS": @"AND",
        @"IMEI": @"AND:2a2f13ff17b1cbb5",
        @"OS_VERSION": @"35",
        @"MODEL": @"2306EPN60G",
        @"APP_VERSION": @"1.22.26"
    };

    // ✅ Build JSON body
    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
            @"project_id": @"8",
            @"drawing_plan_id": @"135",
            @"information": deviceInfo,
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ Defect Matrix API Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

+ (void)fetchProjectList:(void (^)(NSDictionary *data, NSError *error))completion {
    // ✅ URL
    NSString *urlString = @"https://kitadev.commudesk.com/api/owner/project/listProject?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImF0aGlyYWh6YWlkaUBjb252ZXAuY29tIiwicGFzc3dvcmQiOiIkMnkkMTAkNU9xYklqMnZ6UHJwckJrcVd5c3I2LmJCc1hVYS9Hd014eUhnL3RhUUhPUkNQcGdmTG8yakciLCJzdWIiOjIxNzAsImlzcyI6Imh0dHBzOi8va2l0YWRldi5jb21tdWRlc2suY29tL2FwaS9vd25lci9hdXRoL3Bhc3N3b3JkbGVzc19sb2dpbiIsImlhdCI6MTc2MDMxNTM1MiwiZXhwIjoyMDc1ODg0ODcyLCJuYmYiOjE3NjAzMTUzNTIsImp0aSI6IktoQmNyQnJEdDVNdDZlWmMifQ.JnxGbZ7hTeoOr6oibIzZMphgyKtTo2Aq9Efx6mrGfFA";
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";

    // ✅ JSON headers
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    // ✅ Build JSON body
    NSDictionary *jsonBody = @{
        @"data": @{
            @"os": @"AND",
        }
    };

    // ✅ Convert dictionary → NSData
    NSError *jsonError;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:jsonBody options:0 error:&jsonError];
    if (jsonError) {
        NSLog(@"❌ JSON Serialization Error: %@", jsonError);
        if (completion) completion(nil, jsonError);
        return;
    }
    request.HTTPBody = bodyData;

    // 🧭 Debug logs
    NSLog(@"🌍 URL: %@", urlString);
    NSLog(@"📦 Body JSON: %@", jsonBody);

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

        if (error) {
            NSLog(@"❌ Network Error: %@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) completion(nil, error);
            });
            return;
        }

        NSError *jsonParseError;
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];

        if (jsonParseError) {
            NSLog(@"⚠️ JSON Parse Error: %@", jsonParseError);
        } else {
            NSLog(@"✅ Project List API Response:\n%@", jsonResponse);
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) completion(jsonResponse, jsonParseError);
        });
    }];

    [task resume];
}

#pragma mark - Helper Methods
+ (NSString *)multipartFormField:(NSString *)name value:(NSString *)value boundary:(NSString *)boundary {
    return [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"data[%@]\"\r\n\r\n%@\r\n", boundary, name, value];
}

+ (NSData *)multipartFormFile:(NSString *)filePath fieldName:(NSString *)fieldName fileName:(NSString *)fileName mimeType:(NSString *)mimeType boundary:(NSString *)boundary {
    NSMutableData *data = [NSMutableData data];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    
    [data appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"data[%@]\"; filename=\"%@\"\r\n", fieldName, fileName] dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", mimeType] dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:fileData];
    [data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    return data;
}

@end
