//
//  SubDeliveryVC.m
//  Gilliatte
//
//  Created by Lead on 12/08/16.
//  Copyright © 2016 Lead infosoft. All rights reserved.
//

#import "SubDeliveryVC.h"
#import "ActionSheetPicker.h"
#import "AFNetworking.h"
#import "ApiUtillity.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "Base64.h"
#import "SubDeliveryMainVC.h"


@interface SubDeliveryVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIPopoverControllerDelegate>{
    NSInteger SelectedProject;
    NSInteger SelectedJob;
    NSInteger SelectedSub;
    
    NSString *userName;
    
    NSMutableArray *ProjectArray;
    NSMutableArray *EmployeeArray;
    NSMutableArray *SubArray;
    NSMutableArray *UserDataArray;
    NSMutableArray *JobArray;
    
    NSMutableArray *getSubDeliveryData;
    
    UIPopoverController *popover;
    NSString *imageData;
}

@end

@implementation SubDeliveryVC
@synthesize delegate;

#pragma mark- ViewDidload
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    SelectedProject = 0;
//    SelectedJob = 0;
//    SelectedSub = 0;
    userName = [[NSString alloc]init];
    
    getSubDeliveryData = [[NSMutableArray alloc]init];
    imageData = [[NSString alloc]init];
    
    JobArray = [[NSMutableArray alloc]init];
    UserDataArray = [[NSMutableArray alloc]init];
    ProjectArray = [[NSMutableArray alloc]init];
    EmployeeArray = [[NSMutableArray alloc]init];
    SubArray = [[NSMutableArray alloc]init];
    
    _imageview_Upload.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapGesture:)];
    tapGesture1.numberOfTapsRequired = 1;
    [_imageview_Upload addGestureRecognizer:tapGesture1];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    SelectedProject = [ApiUtillity getProjectNumber];
    SelectedJob = [ApiUtillity getJobNumber];
    SelectedSub = [ApiUtillity getSubNumber];
    
//    [self GetMainData];
    [self getUserDefaultData];
    
    if ([_isEdited  isEqual: @"YES"]) {
        _txt_SubName.text = [_EditedArray valueForKey:@"name"];
        _textview_Write.text = [_EditedArray valueForKey:@"description"];
        
        _btn_Project.userInteractionEnabled=false;
        _btn_Job.userInteractionEnabled=false;
        _txt_SubName.userInteractionEnabled=false;
        _btn_Sub.userInteractionEnabled=false;
        _btn_Add.userInteractionEnabled=false;
        _Btn_Title_SubMenu.userInteractionEnabled=false;
        
        
        [_indicator startAnimating];
        NSString *img = [_EditedArray valueForKey:@"img"];
        [_imageview_Upload sd_setImageWithURL:[NSURL URLWithString:img] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            imageData = [self encodeToBase64String:_imageview_Upload.image];
            [_indicator stopAnimating];
        }];
    }
    else{
        [_indicator stopAnimating];
        [_indicator hidesWhenStopped];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark- ButtonAction
- (IBAction)btn_bar_Back:(id)sender {
    [self.navigationController popViewControllerAnimated:true];
}
- (IBAction)btn_Handler_Project:(id)sender {
    NSLog(@"%@",ProjectArray);
    NSMutableArray *ProjectSubArray = [[NSMutableArray alloc]init];
    NSArray *Project = [[NSArray alloc]init];
    int i;
    for (i=0; i<ProjectArray.count; i++) {
        [ProjectSubArray addObject:[[ProjectArray objectAtIndex:i]valueForKey:@"project_name"]];
    }
    Project = ProjectSubArray;
    [ActionSheetStringPicker showPickerWithTitle:@"Select Project"
                                            rows:Project
                                initialSelection:SelectedProject
                                       doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                                           NSLog(@"Picker: %@, Index: %ld, value: %@",
                                                 picker, (long)selectedIndex, selectedValue);
                                           SelectedProject = selectedIndex;
                                           SelectedJob = 0;
                                           
                                           //Set Project Title
                                           [_btn_Project setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                           
                                           //Set Sub Title
                                           SubArray = [[ProjectArray objectAtIndex:selectedIndex]valueForKey:@"subs"];
                                           
                                           
                                           if (SubArray.count > 0)
                                           {
                                               _txt_SubName.text = [[SubArray objectAtIndex:0] valueForKey:@"name"];
                                               [_btn_Sub setTitle:[[SubArray objectAtIndex:0] valueForKey:@"name"] forState:UIControlStateNormal];
                                           }
                                           else
                                           {
                                               _txt_SubName.text = @"";
                                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                               message:@"No Subs Available For This Project."
                                                                                              delegate:self
                                                                                     cancelButtonTitle:@"OK"
                                                                                     otherButtonTitles:nil];
                                               [alert show];
                                               return ;
                                               
                                           }
                                           
                                           
                                           //Set UserDefault Project_ID
                                           NSString *ProjectId = [[ProjectArray objectAtIndex:selectedIndex]valueForKey:@"project_id"];
                                           [[NSUserDefaults standardUserDefaults] setObject:ProjectId forKey:@"PROJECT_ID"];
                                           
                                           //Set UserDefault SUB_ID
                                           NSString *SubID = [[SubArray objectAtIndex:0]valueForKey:@"id"];
                                           [[NSUserDefaults standardUserDefaults] setObject:SubID forKey:@"SUB_ID"];
                                           
                                           [self getSubDeliveryData];
                                       }
                                     cancelBlock:^(ActionSheetStringPicker *picker) {
                                         NSLog(@"Block Picker Canceled");}
                                          origin:sender];
}

- (IBAction)btn_Handler_Job:(id)sender {
    NSArray *Job = [[NSArray alloc]init];
    NSMutableArray *JobSubArray = [[NSMutableArray alloc]init];
    //    JobArray = [[ProjectArray objectAtIndex:SelectedProjectB]valueForKey:@"jobs"];
    int i;
    for (i=0; i<JobArray.count; i++) {
        [JobSubArray addObject:[[JobArray objectAtIndex:i] valueForKey:@"job_title"]];
    }
    Job = JobSubArray;
    [ActionSheetStringPicker showPickerWithTitle:@"Select Job"
                                            rows:Job
                                initialSelection:SelectedJob
                                       doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                                           NSLog(@"Picker: %@, Index: %ld, value: %@",
                                                 picker, (long)selectedIndex, selectedValue);
                                           SelectedJob = selectedIndex;
                                           
                                           [_btn_Job setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                           
                                           //Set UserDefault JOb_Id
//                                           NSString *JobId = [[JobArray objectAtIndex:selectedIndex]valueForKey:@"job_id"];
//                                           [[NSUserDefaults standardUserDefaults] setObject:JobId forKey:@"JOB_ID"];
                                           
//                                           [self getSubDeliveryData];
                                       }
                                     cancelBlock:^(ActionSheetStringPicker *picker) {
                                         NSLog(@"Block Picker Canceled");
                                     }
                                          origin:sender];
}

- (IBAction)btn_Handler_Sub:(id)sender {
    NSArray *Sub = [[NSArray alloc]init];
    NSMutableArray *SubNameArray = [[NSMutableArray alloc]init];
    int i;
    for (i=0; i<SubArray.count; i++) {
        [SubNameArray addObject:[[SubArray objectAtIndex:i] valueForKey:@"name"]];
    }
    Sub = SubNameArray;
    if (SubArray.count <= 0)
    {
        return;
        
    }
    
    [ActionSheetStringPicker showPickerWithTitle:@"Select Sub"
                                            rows:Sub
                                initialSelection:SelectedSub
                                       doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                                           
                                           if (SubArray.count > 0)
                                           {
                                           NSLog(@"Picker: %@, Index: %ld, value: %@",
                                                 picker, (long)selectedIndex, selectedValue);
                                           SelectedSub = selectedIndex;
                                               
                                           [_btn_Sub setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                           
                                           //Set UserDefault Sub_Id
                                           NSString *SubId = [[SubArray objectAtIndex:selectedIndex]valueForKey:@"id"];
                                           [[NSUserDefaults standardUserDefaults] setObject:SubId forKey:@"SUB_ID"];

//                                               [self getUserDefaultData];
//                                           [self getSubDeliveryData];
                                       }
                                       }
     
                                     cancelBlock:^(ActionSheetStringPicker *picker) {
                                         NSLog(@"Block Picker Canceled");
                                     }
                                          origin:sender];
}

- (IBAction)btn_Handler_Add:(id)sender {
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"Add" message:@"Add Sub user" preferredStyle:UIAlertControllerStyleAlert];
//    [Alert.view setTintColor:[UIColor blackColor]];
    
    [Alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"Enter Sub Name";
        textField.textColor = [UIColor blackColor];
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.borderStyle = UITextBorderStyleNone;
    }];
    
    [Alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        userName = @"";
    }]];
    
    [Alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSArray *textFieldData = Alert.textFields;
        UITextField *Quantity = textFieldData[0];
        NSLog(@"%@",Quantity.text);
        
        userName = Quantity.text;
        
        [self sendSubUser];
        
    }]];
    
    dispatch_async(dispatch_get_main_queue(), ^ {
        [self presentViewController:Alert animated:YES completion:nil];
    });
}


- (IBAction)btn_Handler_SubDropDown:(id)sender {
    NSArray *Sub = [[NSArray alloc]init];
    NSMutableArray *SubNameArray = [[NSMutableArray alloc]init];
    int i;
    for (i=0; i<SubArray.count; i++) {
        [SubNameArray addObject:[[SubArray objectAtIndex:i] valueForKey:@"name"]];
    }
    Sub = SubNameArray;
    [ActionSheetStringPicker showPickerWithTitle:@"Select Sub"
                                            rows:Sub
                                initialSelection:SelectedSub
                                       doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                                           NSLog(@"Picker: %@, Index: %ld, value: %@",
                                                 picker, (long)selectedIndex, selectedValue);
                                           SelectedSub = selectedIndex;
                                           
                                           [_btn_Sub setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                           
                                           _txt_SubName.text = selectedValue;
                                           
                                           //Set UserDefault Sub_Id
                                           NSString *SubId = [[SubArray objectAtIndex:selectedIndex]valueForKey:@"id"];
                                           [[NSUserDefaults standardUserDefaults] setObject:SubId forKey:@"SUB_ID"];
                                           
                                                                               //       [self getSubDeliveryData];
                                       }
                                     cancelBlock:^(ActionSheetStringPicker *picker) {
                                         NSLog(@"Block Picker Canceled");
                                     }
                                          origin:sender];
}


- (IBAction)btn_Handler_Save:(id)sender {
    
    if ([_isEdited  isEqual: @"YES"]){
        [self sendEditedSubDeliveryData];
    }
    else{
        [self sendSubDeliveryData];
    }
}


#pragma mark- All Methode
- (void) GetMainData{
    [ApiUtillity setSVProgressHUDView:self.view];
    NSString *UID = [[NSString alloc]init];
    
    NSData *GetUserData;
    if ((GetUserData = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_PROFILE"])) {
        NSMutableArray *savedArray = [NSKeyedUnarchiver unarchiveObjectWithData:GetUserData];
        NSMutableArray *UserArray = [[NSMutableArray alloc]init];
        UserArray = savedArray;
        
        NSLog(@"%@",UserArray);
        UID = [NSString stringWithFormat:@"%@",[UserArray valueForKey:@"uid"]];
    }
    NSString *Token;
    NSString *UUID;
    
    if ((Token = [[NSUserDefaults standardUserDefaults] objectForKey:@"PUSH_TOKEN"]) && (UUID = [[NSUserDefaults standardUserDefaults] objectForKey:@"UUID"])) {
    }
    //IF RUN IPHONE DEVICE
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    
    NSDictionary *params = @{@"uid": UID,@"dev_type":@"1",@"dev_token":Token,@"code":UUID};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/get_initial.php?" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (responseObject != nil) {
            NSString *SuccessString;
            if ((SuccessString = [responseObject valueForKey:@"success"])) {
                if ([SuccessString isEqualToString:@"ok"]) {
                    UserDataArray = [responseObject valueForKey:@"user"];
                    NSLog(@"%@",UserDataArray);
                    
                    NSData *SaveUserData = [NSKeyedArchiver archivedDataWithRootObject:UserDataArray];
                    [[NSUserDefaults standardUserDefaults] setObject:SaveUserData forKey:@"USER_PROFILE"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    ProjectArray = [responseObject valueForKey:@"projects"];
                    EmployeeArray = [responseObject valueForKey:@"employees"];
                    SubArray = [responseObject valueForKey:@"subs"];
                    
                    //StoreDataOfSelection
                    [[NSUserDefaults standardUserDefaults] setObject:ProjectArray forKey:@"ProjectArray"];
                    [[NSUserDefaults standardUserDefaults] setObject:EmployeeArray forKey:@"EmployeeArray"];
                    [[NSUserDefaults standardUserDefaults] setObject:SubArray forKey:@"SubArray"];
                }
            }
        }
        [ApiUtillity dissmissSVProgressHUDView:self.view];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        NSInteger statusCode = error.code;
        NSLog(@"%d",(int)statusCode);
        
        if(statusCode == -1001) {
            // request timed out
            NSLog(@"request timed out");
            [ApiUtillity setSVProgressHUDInfoView:self.view];
        }
        else if (statusCode == -1005){
            [ApiUtillity setSVProgressHUDInfoView:self.view];
        }
        else if (statusCode == -1009 || statusCode == -1004) {
            // no internet connectivity
            NSLog(@"No Internet Connection");
            UIAlertView *alert = [[UIAlertView alloc]init];
            alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"No Internet Connection" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alert show];
        }
            [ApiUtillity dissmissSVProgressHUDView:self.view];
        
    }];
    
}


- (void) getUserDefaultData{
    ProjectArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"ProjectArray"];
    SubArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"SubArray"];
    
    //SET PROJECT AND JOB DATA...
    NSString *TempProjectID,*TempJobID,*TempSubID;
    
    if ((TempProjectID = [[NSUserDefaults standardUserDefaults]objectForKey:@"PROJECT_ID"])) {
        int TempproID = [TempProjectID intValue];
        int TempjobID = [TempJobID intValue];
        NSLog(@"TempjobID:--- %d",TempjobID);
        
        
        //FOR Project & Job...
        int i;
        for (i=0; i<ProjectArray.count; i++) {
            NSString *proID,*subID;
            proID = [[ProjectArray objectAtIndex:i] valueForKey:@"project_id"];
            if ([proID intValue] == TempproID) {
                //SET UI DATA
                [_btn_Project setTitle:[[ProjectArray objectAtIndex:i]valueForKey:@"project_name"] forState:UIControlStateNormal];
                SubArray = [[ProjectArray objectAtIndex:i]valueForKey:@"subs"];
                
                if ((TempSubID = [[NSUserDefaults standardUserDefaults]objectForKey:@"SUB_ID"])) {
                    int TempsubID = [TempSubID intValue];
                    int x;
                    for (x=0; x<SubArray.count; x++) {
                        subID = [[SubArray objectAtIndex:x] valueForKey:@"id"];
                        if ([subID intValue] == TempsubID){
                            //SET UI DATA
                            [_btn_Sub setTitle:[[SubArray objectAtIndex:x] valueForKey:@"name"] forState:UIControlStateNormal];
                        }
                    }
                }
            }
        }
    }
    
    /*
     if ((TempSubID = [[NSUserDefaults standardUserDefaults]objectForKey:@"SUB_ID"])) {
     //For Sub...
     int TempsubID = [TempSubID intValue];
     int y;
     for (y=0; y<SubArray.count; y++) {
     NSString *subID;
     subID = [[SubArray objectAtIndex:y] valueForKey:@"id"];
     if ([subID intValue] == TempsubID) {
     //SET UI DATA
     [_btn_Sub setTitle:[[SubArray objectAtIndex:y]valueForKey:@"name"] forState:UIControlStateNormal];
     }
     }
     }*/
    
}

-(void) getSubDeliveryData{
    
    NSString *ProID,*JobID,*SubID,*Date,*UID,*Type;
    NSData *GetUserData;
    if ((GetUserData = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_PROFILE"])) {
        NSMutableArray *savedArray = [NSKeyedUnarchiver unarchiveObjectWithData:GetUserData];
        NSMutableArray *UserArray = [[NSMutableArray alloc]init];
        UserArray = savedArray;
        
        NSLog(@"%@",UserArray);
        UID = [NSString stringWithFormat:@"%@",[UserArray valueForKey:@"uid"]];
    }
    if (!(Date = [[NSUserDefaults standardUserDefaults] objectForKey:@"SELECTED_DATE"]))
    {
        return;
    }
    else{
        NSArray *DateSeperate = [Date componentsSeparatedByString:@"/"];
        NSString *Day,*Month,*Year,*OriginalDate;
        OriginalDate = [[NSString alloc]init];
        Day = [DateSeperate objectAtIndex:0];
        Month = [DateSeperate objectAtIndex:1];
        Year = [DateSeperate objectAtIndex:2];
        
        OriginalDate = [OriginalDate stringByAppendingString:Year];
        OriginalDate = [OriginalDate stringByAppendingString:@"-"];
        OriginalDate = [OriginalDate stringByAppendingString:Month];
        OriginalDate = [OriginalDate stringByAppendingString:@"-"];
        OriginalDate = [OriginalDate stringByAppendingString:Day];
        
        Date = OriginalDate;
    }
    if (!(ProID = [[NSUserDefaults standardUserDefaults] objectForKey:@"PROJECT_ID"]))
    {
        return;
    }
    if ((!(JobID = [[NSUserDefaults standardUserDefaults] objectForKey:@"JOB_ID"]))) {
        return;
    }
    if ((!(SubID = [[NSUserDefaults standardUserDefaults] objectForKey:@"SUB_ID"]))) {
        return;
    }
    
    Type = @"subdelivery";
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    
    NSDictionary *params = @{@"date":Date,@"uid":UID,@"project_id":ProID,@"job_id":JobID,@"sub_id":SubID,@"type":Type};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/record_get.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        NSMutableArray *records;
        records = [responseObject valueForKey:@"records"];
        if (records.count != 0) {
            NSString *Suceess;
            if (responseObject != nil) {
                if ((Suceess = [responseObject valueForKey:@"success"])) {
                    if ([Suceess  isEqual: @"ok"]) {
                        //                    [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view];
                        getSubDeliveryData = [responseObject valueForKey:@"records"][0];
                        _EditedArray = getSubDeliveryData;
                        
                        _textview_Write.text = [getSubDeliveryData valueForKey:@"description"];
                        NSString *img = [getSubDeliveryData valueForKey:@"img"];
                        [_imageview_Upload sd_setImageWithURL:[NSURL URLWithString:img] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                            imageData = [self encodeToBase64String:_imageview_Upload.image];
                        }];
                        
                    }
                }
            }
        }
        else{
            _textview_Write.text = @"";
            _imageview_Upload.image = [UIImage imageNamed:@"ic_Upload_Image.png"];
        }
        [ApiUtillity dissmissSVProgressHUDView:self.view];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [ApiUtillity dissmissSVProgressHUDView:self.view];
        
        NSLog(@"Error: %@", error);
        NSInteger statusCode = error.code;
        NSLog(@"%d",(int)statusCode);
        if(statusCode == -1001) {
            // request timed out
            NSLog(@"request timed out");
        }else if (statusCode == -1009 || statusCode == -1004) {
            // no internet connectivity
            NSLog(@"No Internet Connection");
            UIAlertView *alert = [[UIAlertView alloc]init];
            alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"No Internet Connection" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
    
}

-(void) sendSubUser{
    
    NSString *UID,*Type,*Name;
    NSData *GetUserData;
    if ((GetUserData = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_PROFILE"])) {
        NSMutableArray *savedArray = [NSKeyedUnarchiver unarchiveObjectWithData:GetUserData];
        NSMutableArray *UserArray = [[NSMutableArray alloc]init];
        UserArray = savedArray;
        
        NSLog(@"%@",UserArray);
        UID = [NSString stringWithFormat:@"%@",[UserArray valueForKey:@"uid"]];
    }
    
    NSString *TempProjectID;
    
    if (!(TempProjectID = [[NSUserDefaults standardUserDefaults]objectForKey:@"PROJECT_ID"])) {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Pleaze Select Project" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    Type = @"sub";
    Name = userName;
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    
    NSDictionary *params = @{@"uid":UID,@"project_id":TempProjectID,@"name":Name};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/add_sub.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        NSMutableArray *records;
        records = [responseObject valueForKey:@"rows"];
        if (records.count != 0) {
            NSString *Suceess,*subID;
            if (responseObject != nil) {
                if ((Suceess = [responseObject valueForKey:@"success"])) {
                    if ([Suceess  isEqual: @"Inserted"]) {
                        if ((subID = [responseObject valueForKey:@"id"])) {
                            NSMutableArray *subArray;
                            subArray = [responseObject valueForKey:@"rows"];
                            int i;
                            for (i = 0; i < subArray.count; i++) {
                                NSString *subId = [[subArray valueForKey:@"id"] objectAtIndex:i];
                                
                                if ([subId isEqualToString:subID]) {
                                    [_btn_Sub setTitle:[[subArray objectAtIndex:i]valueForKey:@"name"] forState:UIControlStateNormal];
                                    //Set UserDefault Sub_Id
                                    [[NSUserDefaults standardUserDefaults] setObject:subId forKey:@"SUB_ID"];
                                    
                                    [self GetMainData];
                                }
                            }
                        }
                    }
                }
            }
        }
    [ApiUtillity dissmissSVProgressHUDView:self.view];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [ApiUtillity dissmissSVProgressHUDView:self.view];
        
        NSLog(@"Error: %@", error);
        NSInteger statusCode = error.code;
        NSLog(@"%d",(int)statusCode);
        if(statusCode == -1001) {
            // request timed out
            NSLog(@"request timed out");
        }else if (statusCode == -1009 || statusCode == -1004) {
            // no internet connectivity
            NSLog(@"No Internet Connection");
            UIAlertView *alert = [[UIAlertView alloc]init];
            alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"No Internet Connection" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
    
}

-(void) sendSubDeliveryData{
    
    NSString *ProID,*JobID,*SubID,*SubName,*Date,*UID,*Desc,*Type;
    NSData *GetUserData;
    if ((GetUserData = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_PROFILE"])) {
        NSMutableArray *savedArray = [NSKeyedUnarchiver unarchiveObjectWithData:GetUserData];
        NSMutableArray *UserArray = [[NSMutableArray alloc]init];
        UserArray = savedArray;
        
        NSLog(@"%@",UserArray);
        UID = [NSString stringWithFormat:@"%@",[UserArray valueForKey:@"uid"]];
    }
    if (!(Date = [[NSUserDefaults standardUserDefaults] objectForKey:@"SELECTED_DATE"]))
    {
        return;
    }
    else{
        NSArray *DateSeperate = [Date componentsSeparatedByString:@"/"];
        NSString *Day,*Month,*Year,*OriginalDate;
        OriginalDate = [[NSString alloc]init];
        Day = [DateSeperate objectAtIndex:0];
        Month = [DateSeperate objectAtIndex:1];
        Year = [DateSeperate objectAtIndex:2];
        
        OriginalDate = [OriginalDate stringByAppendingString:Year];
        OriginalDate = [OriginalDate stringByAppendingString:@"-"];
        OriginalDate = [OriginalDate stringByAppendingString:Month];
        OriginalDate = [OriginalDate stringByAppendingString:@"-"];
        OriginalDate = [OriginalDate stringByAppendingString:Day];
        
        Date = OriginalDate;
    }
    if (!(ProID = [[NSUserDefaults standardUserDefaults] objectForKey:@"PROJECT_ID"]))
    {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Select Project." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if ((!(JobID = [[NSUserDefaults standardUserDefaults] objectForKey:@"JOB_ID"]))) {
        JobID = @"-1";
    }
    if ((!(SubID = [[NSUserDefaults standardUserDefaults] objectForKey:@"SUB_ID"]))) {
        SubID = @"-1";
    }
    if ([_txt_SubName.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Enter Sub Name" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    else{
        SubName = _txt_SubName.text;
    }
    if ([_textview_Write.text  isEqual: @""] || [_textview_Write.text  isEqual: @"Write Here..."]) {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Enter Description." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    else{
        Desc = _textview_Write.text;
    }
    if (imageData == nil) {
        imageData = @"nil";
    }
    
    Type = @"subdelivery";
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    
    NSDictionary *params = @{@"date":Date,@"uid":UID,@"project_id":ProID,@"job_id":JobID,@"sub_id":SubID,@"delivery_name":SubName,@"photo":imageData,@"description":Desc,@"type":Type};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/record_add.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                NSLog(@"Subdelivery record created");
                
                NSMutableArray *record = [responseObject valueForKey:@"records"];
                [delegate getRecordArray:record];
                
                //Set UserDefault Sub_Id
                [_btn_Sub setTitle:@"Sub" forState:UIControlStateNormal];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"SUB_ID"];
                
                [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view WithMessage:@"Record Added"];
                
//                SubDeliveryMainVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"SubDeliveryMainVC"];
//                [self.navigationController pushViewController:vc animated:true];
                
                [self.navigationController popViewControllerAnimated:true];
            }
        }
        [ApiUtillity dissmissSVProgressHUDView:self.view];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        NSInteger statusCode = error.code;
        NSLog(@"%d",(int)statusCode);
        
        if(statusCode == -1001) {
            // request timed out
            NSLog(@"request timed out");
            [ApiUtillity setSVProgressHUDInfoView:self.view];
        }
        else if (statusCode == -1005){
            [ApiUtillity setSVProgressHUDInfoView:self.view];
        }
        else if (statusCode == -1009 || statusCode == -1004) {
            // no internet connectivity
            NSLog(@"No Internet Connection");
            UIAlertView *alert = [[UIAlertView alloc]init];
            alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"No Internet Connection" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alert show];
        }
            [ApiUtillity dissmissSVProgressHUDView:self.view];
        
    }];
    
}

-(void) sendEditedSubDeliveryData{
    
    NSString *ProID,*JobID,*SubID,*Date,*UID,*Desc,*Type,*RecordId,*SubName;
    NSData *GetUserData;
    if ((GetUserData = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_PROFILE"])) {
        NSMutableArray *savedArray = [NSKeyedUnarchiver unarchiveObjectWithData:GetUserData];
        NSMutableArray *UserArray = [[NSMutableArray alloc]init];
        UserArray = savedArray;
        
        NSLog(@"%@",UserArray);
        UID = [NSString stringWithFormat:@"%@",[UserArray valueForKey:@"uid"]];
    }
    if (!(Date = [[NSUserDefaults standardUserDefaults] objectForKey:@"SELECTED_DATE"]))
    {
        return;
    }
    else{
        NSArray *DateSeperate = [Date componentsSeparatedByString:@"/"];
        NSString *Day,*Month,*Year,*OriginalDate;
        OriginalDate = [[NSString alloc]init];
        Day = [DateSeperate objectAtIndex:0];
        Month = [DateSeperate objectAtIndex:1];
        Year = [DateSeperate objectAtIndex:2];
        
        OriginalDate = [OriginalDate stringByAppendingString:Year];
        OriginalDate = [OriginalDate stringByAppendingString:@"-"];
        OriginalDate = [OriginalDate stringByAppendingString:Month];
        OriginalDate = [OriginalDate stringByAppendingString:@"-"];
        OriginalDate = [OriginalDate stringByAppendingString:Day];
        
        Date = OriginalDate;
    }
    
    if ([_textview_Write.text  isEqual: @""] || [_textview_Write.text  isEqual: @"Write Here..."]) {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Enter Description" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    else{
        Desc = _textview_Write.text;
    }
    if ([_txt_SubName.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Enter Sub Name." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    else{
        SubName = _txt_SubName.text;
    }
    
    
    if (imageData == nil) {
        imageData = @"nil";
    }
    
    ProID = [_EditedArray valueForKey:@"project_id"];
    JobID = [_EditedArray valueForKey:@"job_id"];
    JobID = @"-1";
    SubID = [_EditedArray valueForKey:@"sub_id"];
    RecordId = [_EditedArray valueForKey:@"id"];
    Type = @"subdelivery";
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    
    NSDictionary *params = @{@"id":RecordId,@"date":Date,@"uid":UID,@"project_id":ProID,@"job_id":JobID,@"sub_id":SubID,@"photo":imageData,@"description":Desc,@"type":Type,@"delivery_name":SubName,};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/record_add.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                NSLog(@"Subdelivery record updated");
                
                NSMutableArray *record = [responseObject valueForKey:@"records"];
                [delegate getRecordArray:record];
                
                //Set UserDefault Sub_Id
                [_btn_Sub setTitle:@"Sub" forState:UIControlStateNormal];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"SUB_ID"];
                
                [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view WithMessage:@"Record updated"];
                
//                SubDeliveryMainVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"SubDeliveryMainVC"];
//                [self.navigationController pushViewController:vc animated:true];
                
                
                [self.navigationController popViewControllerAnimated:true];
            }
        }
        [ApiUtillity dissmissSVProgressHUDView:self.view];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        NSInteger statusCode = error.code;
        NSLog(@"%d",(int)statusCode);
        
        if(statusCode == -1001) {
            // request timed out
            NSLog(@"request timed out");
            [ApiUtillity setSVProgressHUDInfoView:self.view];
        }
        else if (statusCode == -1005){
            [ApiUtillity setSVProgressHUDInfoView:self.view];
        }
        else if (statusCode == -1009 || statusCode == -1004) {
            // no internet connectivity
            NSLog(@"No Internet Connection");
            UIAlertView *alert = [[UIAlertView alloc]init];
            alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"No Internet Connection" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alert show];
        }
            [ApiUtillity dissmissSVProgressHUDView:self.view];
        
    }];
    
}


//Encoding :--
- (NSString *)encodeToBase64String:(UIImage *)image {
    NSData* data = UIImageJPEGRepresentation(image, 1.0f);
    return [Base64 encode:data];
}
//Decoding :--
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
    NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return [UIImage imageWithData:data];
}


- (void) tapGesture: (id)sender
{
    UIActionSheet *actionSheetPop;
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"Upload Image" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"Gallery" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self actionSheet:actionSheetPop clickedButtonAtIndex:0];
    }]];
    
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self actionSheet:actionSheetPop clickedButtonAtIndex:1];
    }]];
    
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }]];
    
    UIPopoverPresentationController *popPresenter = [actionSheet
                                                     popoverPresentationController];
    popPresenter.sourceView = self.imageview_Upload;
    popPresenter.sourceRect = self.imageview_Upload.frame;
    [self presentViewController:actionSheet animated:YES completion:nil];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%ld",(long)buttonIndex);
    
    if (buttonIndex == 0) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
            popover.delegate = self;
            popover=[[UIPopoverController alloc]initWithContentViewController:picker];
            [popover presentPopoverFromRect:self.imageview_Upload.frame inView:self.imageview_Upload permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
            
        }
        else{
            [self presentViewController:picker animated:YES completion:NULL];
        }
    }
    else if (buttonIndex == 1){
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            [self presentViewController:picker animated:YES completion:NULL];
        }
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    self.imageview_Upload.image = chosenImage;
    
    imageData = [self encodeToBase64String:_imageview_Upload.image];
    
    if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        [popover dismissPopoverAnimated:YES];
        [picker dismissViewControllerAnimated:YES completion:nil];
    } else {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:NULL];
}


#pragma Textview Delegate
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    if ([_textview_Write.text  isEqual: @"Write Here..."]) {
        _textview_Write.text = @"";
        _textview_Write.textColor = [UIColor blackColor];
    }
    _textview_Write.textColor = [UIColor blackColor];
    return YES;
}
-(void)textViewDidChange:(UITextView *)textView{
    if (_textview_Write.text.length == 0) {
        _textview_Write.textColor = [UIColor lightGrayColor];
        _textview_Write.text = @"Write Here...";
        [_textview_Write resignFirstResponder];
    }
}
@end