//  AppointmentAPIClient.mm

#import "AppointmentAPIClient.h"

@implementation AppointmentAPIClient

+ (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)submitAppointmentWithData:(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)submitRepresentativeAppointmentWithData:(NSDictionary *)appointmentData
                             representativeData:(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 (REP) URL: %@", urlString);
    NSLog(@"📦 SUBMIT (REP) Appointment Data: %@", appointmentData);
    NSLog(@"📎 SUBMIT (REP) Representative Data: %@", repData);

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

    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 appointment fields
    for (NSString *key in appointmentData) {
        NSString *field = [self multipartFormField:key value:appointmentData[key] boundary:boundary];
        [body appendData:[field dataUsingEncoding:NSUTF8StringEncoding]];
    }

    // Add representative fields
    for (NSString *key in repData) {
        id value = repData[key];

        if ([value isKindOfClass:[NSDictionary class]] && value[@"filePath"]) {
            NSLog(@"📎 Adding file for key '%@': %@", key, value[@"fileName"]);
            [body appendData:[self multipartFormFile:value[@"filePath"]
                                           fieldName:key
                                           fileName:value[@"fileName"]
                                           mimeType:value[@"mimeType"]
                                           boundary:boundary]];
        } else {
            NSString *field = [self multipartFormField:key value:value boundary:boundary];
            [body appendData:[field dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }

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

    request.HTTPBody = body;

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

    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 (REP) 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(@"✅ Void Issues 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
