//  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:(void (^)(NSDictionary *data, NSError *error))completion{
    // ✅ Build URL
    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]", @"8");
    appendFormField(@"data[location_id]", @"1458"); //temp number

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


@end

