//  IssueAPIClient.mm

#import "IssueAPIClient.h"

@implementation IssueAPIClient

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

@end
