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

#import "AccidentsVC.h"
#import "AccidentsMainVC.h"
#import "ActionSheetPicker.h"
#import "ActionSheetLocalePicker.h"
#import "AFNetworking.h"
#import "ApiUtillity.h"
#import "AccidentsMainVC.h"
#import "IQUIView+IQKeyboardToolbar.h"
#import "AccidentsMainVC.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "AccidentsListVC.h"
#import "AddImageCell.h"
#import "UIImageView+UIActivityIndicatorForSDWebImage.h"
#import <Photos/Photos.h>
#import <QuartzCore/QuartzCore.h>
#import "ConnectToServer.h"








@interface AccidentsVC ()<WittnessDelegate,UIImagePickerControllerDelegate>{
    NSString *SelectedDate;
    NSString *SelectedTime;
    
    NSInteger SelectedProject;
    NSInteger SelectedJob;
    NSDate *today;
    BOOL RadioFlag;
    BOOL IsSelectImage;
    NSMutableArray *ImagesDataArray;
    NSUInteger isSetProfile;
    UIImage *scaledimage;
    BOOL isSelectProfile;
    BOOL isUpdateProfile;
    NSString *ImageName;
    NSString *ImagePreviewLink;
    NSUInteger tag;
    
    NSMutableArray *ProjectArray;
    NSMutableArray *UserDataArray;
    NSMutableArray *JobArray;
    
    NSMutableArray *WittnessNameArray;
    NSMutableArray *WittnessMobileArray;
    NSMutableArray *WittnessDescArray;
    NSMutableArray *GetImageData;
    
    
    //Edited
    NSString *editedDateTime;
    NSMutableArray *editedWitnessArray;
}
@property (nonatomic, strong) NSDate *selectedDate;
@property (nonatomic, strong) NSDate *selectedTime;

@end

@implementation AccidentsVC
@synthesize delegate;
@synthesize actionSheetPicker = _actionSheetPicker;

#pragma mark- ViewDidload
- (void)viewDidLoad {
    [super viewDidLoad];
    IsSelectImage=0;
    
    
    [self SetPrevNextButton];
    
    JobArray = [[NSMutableArray alloc]init];
    UserDataArray = [[NSMutableArray alloc]init];
    ProjectArray = [[NSMutableArray alloc]init];
    ImagesDataArray=[[NSMutableArray alloc]init];
    
    
    
    WittnessNameArray = [[NSMutableArray alloc]init];
    WittnessMobileArray = [[NSMutableArray alloc]init];
    WittnessDescArray = [[NSMutableArray alloc]init];
    
    SelectedDate = [[NSString alloc]init];
    SelectedTime = [[NSString alloc]init];
    
    editedDateTime = [[NSString alloc]init];
    editedWitnessArray = [[NSMutableArray alloc]init];
    
    GetImageData=[NSMutableArray arrayWithObjects:@"https://www.w3schools.com/css/trolltunga.jpg",@"https://cdn.pixabay.com/photo/2017/01/06/19/15/soap-bubble-1958650_960_720.jpg",@"http://www.gettyimages.ca/gi-resources/images/Embed/new/embed2.jpg",@"https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_960_720.png",@"https://cdn.pixabay.com/photo/2017/01/06/19/15/soap-bubble-1958650_960_720.jpg", nil];
    
    
    
    //For Piker
    //    SelectedProject = 0;
    //    SelectedJob = 0;
    
    //For Radio Button
    RadioFlag = 0;
    [_btn_Radio_PropertyDamage setImage:[UIImage imageNamed:@"ic_Radio_Selected.png"] forState:UIControlStateNormal];
    _txt_Radio_Other.userInteractionEnabled = false;
    
    //For Piker Date
    today = [NSDate date];
    self.selectedDate = today;
    
    
    if ([_isEdited  isEqual: @"YES"]) {
        editedWitnessArray = [_EditedArray valueForKey:@"witness"];
        
        _txt_Name.text = [_EditedArray valueForKey:@"name"];
        _txt_PhoneNumber.text = [_EditedArray valueForKey:@"phone"];
        _txt_CompanyName.text = [_EditedArray valueForKey:@"company"];
        
        _btn_Project.userInteractionEnabled=false;
        
        
        for (NSString *str in [_EditedArray valueForKey:@"photos"])
        {
            NSArray *languagesuserArray = [str componentsSeparatedByString:@"/"];
            
            [ImagesDataArray addObject:@{@"is_link":[languagesuserArray lastObject],@"image":str}];
            
        }
        
        [ImagesDataArray addObject:@{}];
        
        
        NSString *img = [_EditedArray valueForKey:@"photo"];
        
        [_Imgview_AddPhoto sd_setImageWithURL:[NSURL URLWithString:img] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        
        
        NSString *DateTime,*incident_type;
        NSArray *date;
        DateTime = [_EditedArray valueForKey:@"incident_datetime"];
        date = [DateTime componentsSeparatedByString:@" "];
        editedDateTime = DateTime;
        
        NSString *Time = [[NSString alloc]initWithString:date[0]];
        Time = [Time stringByAppendingString:@" "];
        Time = [Time stringByAppendingString:date[1]];
        Time = [Time uppercaseString];
        
        [_btn_IncidentDate setTitle:date[0] forState:UIControlStateNormal];
        [_btn_IncidentTime setTitle:Time forState:UIControlStateNormal];
        
        
        incident_type = [_EditedArray valueForKey:@"incident_type"];
        if ([incident_type  isEqual: @"Property Damage"]) {
            RadioFlag = 0;
            [_btn_Radio_PropertyDamage setImage:[UIImage imageNamed:@"ic_Radio_Selected.png"] forState:UIControlStateNormal];
            [_btn_Radio_Other setImage:[UIImage imageNamed:@"ic_Radio_UnSelected.png"] forState:UIControlStateNormal];
            _txt_Radio_Other.userInteractionEnabled = false;
            _txt_Radio_Other.text = @"";
            [_txt_Radio_Other resignFirstResponder];
        }
        else{
            RadioFlag = 1;
            _txt_Radio_Other.userInteractionEnabled = true;
            _txt_Radio_Other.text = incident_type;
            [_btn_Radio_PropertyDamage setImage:[UIImage imageNamed:@"ic_Radio_UnSelected.png"] forState:UIControlStateNormal];
            [_btn_Radio_Other setImage:[UIImage imageNamed:@"ic_Radio_Selected.png"] forState:UIControlStateNormal];
        }
        
        _textview_Write.text = [_EditedArray valueForKey:@"description"];
        
        
        if (_EditedsplitPhoneArray.count != 0 && _EditedsplitNameArray.count != 0 && _EditedsplitDescArray.count != 0) {
            int i;
            for (i = 0; i < _EditedsplitNameArray.count; i++) {
                [WittnessNameArray addObject:[_EditedsplitNameArray objectAtIndex:i]];
                [WittnessMobileArray addObject:[_EditedsplitPhoneArray objectAtIndex:i]];
                [WittnessDescArray addObject:[_EditedsplitDescArray objectAtIndex:i]];
            }
            
            NSString *wittnessName,*wittnessNumber;
            wittnessName = [NSString stringWithFormat:@"%lu witness Name",(unsigned long)WittnessNameArray.count];
            wittnessNumber = [NSString stringWithFormat:@"%lu witness Number",(unsigned long)_EditedsplitPhoneArray.count];
            
            _txt_WitnessName.textColor = [UIColor lightGrayColor];
            _txt_WitnessNumber.textColor = [UIColor lightGrayColor];
            
            _txt_WitnessName.text = [NSString stringWithFormat:@"%@",wittnessName];
            _txt_WitnessNumber.text = [NSString stringWithFormat:@"%@",wittnessNumber];
            
            _txt_WitnessName.userInteractionEnabled = false;
            _txt_WitnessNumber.userInteractionEnabled = false;
        }
    }
    else
    {
        [ImagesDataArray addObject:@{}];
        
    }
    
    
    
    
}


-(void)viewWillAppear:(BOOL)animated{
    
    SelectedProject = [ApiUtillity getProjectNumber];
    SelectedJob = [ApiUtillity getJobNumber];
    
    //    [self GetMainData];
    [self getUserDefaultData];
    
    NSLog(@"WittnessNameArray :- %@ AND WittnessMobileArray :- %@",WittnessNameArray,WittnessMobileArray);
    
    
    
    
    
}

- (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_ImgviewSelect:(id)sender {
    
    
    
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"" message:@"Upload Image" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@" Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            UIImagePickerController *imagePickController=[[UIImagePickerController alloc]init];
            imagePickController.sourceType=UIImagePickerControllerSourceTypeCamera;
            
            
            imagePickController.delegate=self;
            imagePickController.allowsEditing=TRUE;
            [self presentViewController:imagePickController animated:true completion:nil];
        }
        
        
    }];
    UIAlertAction *Gallery = [UIAlertAction actionWithTitle:@"Gallery" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *imagePickController=[[UIImagePickerController alloc]init];
        imagePickController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        imagePickController.delegate=self;
        imagePickController.allowsEditing=TRUE;
        [self presentViewController:imagePickController animated:true completion:nil];
        
    }];
    UIAlertAction *Cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [Alert addAction:camera];
    [Alert addAction:Gallery];
    [Alert addAction:Cancel];
    // [self presentViewController:Alert animated:true completion:nil];
    
    
    // Remove arrow from action sheet.
    [Alert.popoverPresentationController setPermittedArrowDirections:0];
    
    
    //For set action sheet to middle of view.
    CGRect rect = self.view.frame;
    rect.origin.x = self.view.frame.size.width / 20;
    rect.origin.y = self.view.frame.size.height / 20;
    Alert.popoverPresentationController.sourceView = self.view;
    Alert.popoverPresentationController.sourceRect = rect;
    
    [self presentViewController:Alert animated:YES completion:nil];
    
    
}




- (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;
                                           
                                           [_btn_Project setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                           //Set JOb Title
                                           //                                           JobArray = [[ProjectArray objectAtIndex:selectedIndex]valueForKey:@"jobs"];
                                           //                                           [_btn_Job setTitle:[[JobArray objectAtIndex:0] valueForKey:@"job_title"] forState:UIControlStateNormal];
                                           
                                           //Set UserDefault Project_ID
                                           NSString *ProjectId = [[ProjectArray objectAtIndex:selectedIndex]valueForKey:@"project_id"];
                                           [[NSUserDefaults standardUserDefaults] setObject:ProjectId forKey:@"PROJECT_ID"];
                                           //Set UserDefault JOb_Id
                                           //                                           NSString *JobId = [[JobArray objectAtIndex:0]valueForKey:@"job_id"];
                                           //                                           [[NSUserDefaults standardUserDefaults] setObject:JobId forKey:@"JOB_ID"];
                                       }
                                     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"];
                                       }
                                     cancelBlock:^(ActionSheetStringPicker *picker) {
                                         NSLog(@"Block Picker Canceled");
                                     }
                                          origin:sender];
}


- (IBAction)btn_Handler_AddMoreWittness:(id)sender {
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        AccidentsMainVC *VC = (AccidentsMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"AccidentsMainVC"];
        VC.delegate = self;
        VC.isEdited = @"YES";
        VC.EditedsplitNameArray = WittnessNameArray;
        VC.EditedsplitPhoneArray = WittnessMobileArray;
        VC.EditedsplitDescArray = WittnessDescArray;
        [self.navigationController pushViewController:VC animated:true];
    }
    else{
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStory_iPad" bundle:nil];
        AccidentsMainVC *VC = (AccidentsMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"AccidentsMainVC"];
        VC.delegate = self;
        VC.isEdited = @"YES";
        VC.EditedsplitNameArray = WittnessNameArray;
        VC.EditedsplitPhoneArray = WittnessMobileArray;
        VC.EditedsplitDescArray = WittnessDescArray;
        [self.navigationController pushViewController:VC animated:true];
    }
    
}


- (IBAction)btn_Handler_IncidentDate:(id)sender {
    [self.view endEditing:true];
    [ActionSheetDatePicker showPickerWithTitle:@"Select Incident Date" datePickerMode:UIDatePickerModeDate selectedDate:self.selectedDate minimumDate:nil maximumDate:today target:self action:@selector(dateWasSelected:element:) origin:sender];
}

- (IBAction)btn_Handler_IncidentTime:(id)sender {
    [self.view endEditing:true];
    NSInteger minuteInterval = 1;
    //clamp date
    NSInteger referenceTimeInterval = (NSInteger)[self.selectedTime timeIntervalSinceReferenceDate];
    NSInteger remainingSeconds = referenceTimeInterval % (minuteInterval *60);
    NSInteger timeRoundedTo5Minutes = referenceTimeInterval - remainingSeconds;
    if(remainingSeconds>((minuteInterval*60)/2)) {
        /// round up
        timeRoundedTo5Minutes = referenceTimeInterval +((minuteInterval*60)-remainingSeconds);
    }
    
    /*
     if (![self.selectedTime isEqual:[NSNull null]]) {
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
     [dateFormatter setDateFormat:@"HH:mm a"];
     
     NSString *Date = [dateFormatter stringFromDate:self.selectedTime];
     
     NSArray *MainDate = [[self.selectedDate description] componentsSeparatedByString:@" "];
     NSString *Date1 = [MainDate objectAtIndex:0];
     NSString *Date2 = [MainDate objectAtIndex:1];
     NSString *code = [Date substringFromIndex: [Date length] - 2];
     
     
     NSCalendar *gregorian = [[NSCalendar alloc]
     initWithCalendarIdentifier:NSCalendarIdentifierIndian];
     NSDateComponents *weekdayComponents =
     [gregorian components:(NSCalendarUnitDay | NSCalendarUnitWeekday) fromDate:self.selectedTime];
     [weekdayComponents setHour:12];
     [weekdayComponents setMinute:10];
     }
     else{
     self.selectedTime = [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)timeRoundedTo5Minutes];
     }*/
    
    
    NSString *TimeMain = _btn_IncidentTime.titleLabel.text;
    
    if ([TimeMain isEqualToString:@"Incident Time"]) {
        self.selectedTime = [NSDate date];
        
    }
    else
    {
        if ([_isEdited  isEqual: @"YES"])
        {
            NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
            [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mma"];
            self.selectedTime = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@",TimeMain]];
        }
        else
        {
            self.selectedTime = [NSDate date];

        }
    }
    
    //    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"NL"];
    
    ActionSheetDatePicker *datePicker = [[ActionSheetDatePicker alloc] initWithTitle:@"Select Incident Time" datePickerMode:UIDatePickerModeTime selectedDate:self.selectedTime target:self action:@selector(timeWasSelected:element:) origin:sender];
    datePicker.minuteInterval = minuteInterval;
   // [datePicker setMinimumDate:[NSDate date]];
    [datePicker setMaximumDate:[NSDate date]];
    
    
    
    //    datePicker.locale = locale;
    
    
    [datePicker showActionSheetPicker];
}

- (IBAction)btn_Handler_Radio_Property:(id)sender {
    RadioFlag = 0;
    [_btn_Radio_PropertyDamage setImage:[UIImage imageNamed:@"ic_Radio_Selected.png"] forState:UIControlStateNormal];
    [_btn_Radio_Other setImage:[UIImage imageNamed:@"ic_Radio_UnSelected.png"] forState:UIControlStateNormal];
    _txt_Radio_Other.userInteractionEnabled = false;
    [_txt_Radio_Other resignFirstResponder];
}

- (IBAction)btn_Handler_Radio_Other:(id)sender {
    RadioFlag = 1;
    _txt_Radio_Other.userInteractionEnabled = true;
    [_txt_Radio_Other becomeFirstResponder];
    [_btn_Radio_PropertyDamage setImage:[UIImage imageNamed:@"ic_Radio_UnSelected.png"] forState:UIControlStateNormal];
    [_btn_Radio_Other setImage:[UIImage imageNamed:@"ic_Radio_Selected.png"] forState:UIControlStateNormal];
}

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


- (NSString *)encodeToBase64String:(UIImage *)image {
    return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
#pragma mark- Image Resizing Method


- (UIImage *)imageWithImage:(UIImage *)image convertToSize:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return destImage;
}


#pragma mark- UIImagePickerController Methode
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    
    
    //   UIImage *img = [UIImage imageNamed:@"logo.png"];
    
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    
    if (width > 1024 && height > 1024)
    {
        NSLog(@"");
        scaledimage=[self imageWithImage:image convertToSize:CGSizeMake(1000, 1000)];
        CGFloat width1 = scaledimage.size.width;
        CGFloat height1 = scaledimage.size.height;
        NSLog(@"Width Of Image:--- %f",width1);
        NSLog(@"height1 Of Image:--- %f",height1);
        
        
        
    }
    else
    {
        scaledimage=[info objectForKey:UIImagePickerControllerOriginalImage];
        CGFloat width1 = scaledimage.size.width;
        CGFloat height1 = scaledimage.size.height;
        NSLog(@"Width Of Image:--- %f",width1);
        NSLog(@"height1 Of Image:--- %f",height1);
        
        
        
    }
    
    if (isSetProfile == 1) {
        isSelectProfile = 1;
    }
    else{
        [self SendImageData];
        
        
    }
    
    [self dismissViewControllerAnimated:true completion:nil];
}




#pragma mark- CollectionView Methode
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [ImagesDataArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (ImagesDataArray.count-1 == indexPath.row) {
        AddImageCell *cell = [_Collectionview_Image dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        
        [[cell.Btn_Add layer] setBorderWidth:2.0f];
        [[cell.Btn_Add layer] setBorderColor:[UIColor darkGrayColor].CGColor];
        [[cell.Btn_Add layer] setCornerRadius:15.0f];
        cell.Btn_Add.clipsToBounds = true;
        
        [cell.Btn_Add addTarget:self action:@selector(AddNewImage) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    else{
        AddImageCell
        *cell = [_Collectionview_Image dequeueReusableCellWithReuseIdentifier:@"AddImageCell" forIndexPath:indexPath];
        [cell.Btn_Delete addTarget:self action:@selector(btn_Handler_DeleteImage:) forControlEvents:UIControlEventTouchUpInside];
        cell.Btn_Delete.tag = indexPath.row;
        
        
        NSString *temp = [[ImagesDataArray objectAtIndex:indexPath.row] valueForKey:@"is_link"];
        
        [cell.imageview_incident setImageWithURL:[NSURL URLWithString:[[ImagesDataArray objectAtIndex:indexPath.row] valueForKey:@"image"]] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        
        
        
        return cell;
    }
}

- (IBAction)btn_Handler_DeleteImage:(id)sender
{
    UIButton *btn = (UIButton*)sender;
    [ImagesDataArray removeObjectAtIndex:btn.tag];
    [_Collectionview_Image reloadData];
}


- (void)AddNewImage {
    isSetProfile = 0;
    
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"Select Image" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (status == AVAuthorizationStatusDenied) {
                
                UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"camera_access" message:@"permission_camera" preferredStyle:UIAlertControllerStyleAlert];
                [controller addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }]];
                [controller addAction:[UIAlertAction actionWithTitle:@"Open" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }]];
                
                [self presentViewController:controller animated:true completion:nil];
            }
            else{
                UIImagePickerController *imagePickController=[[UIImagePickerController alloc]init];
                imagePickController.sourceType=UIImagePickerControllerSourceTypeCamera;
                imagePickController.delegate=self;
                imagePickController.allowsEditing=TRUE;
                [self presentViewController:imagePickController animated:true completion:nil];
            }
        }
    }];
    UIAlertAction *Gallery = [UIAlertAction actionWithTitle:@"Gallery" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusDenied) {
            UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"photo_access" message:@"permission_photo" preferredStyle:UIAlertControllerStyleAlert];
            [controller addAction:[UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            [controller addAction:[UIAlertAction actionWithTitle:@"Open" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }]];
            
            [self presentViewController:controller animated:true completion:nil];
        }
        else{
            UIImagePickerController *imagePickController=[[UIImagePickerController alloc]init];
            imagePickController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickController.delegate=self;
            imagePickController.allowsEditing=TRUE;
            [self presentViewController:imagePickController animated:true completion:nil];
        }
    }];
    UIAlertAction *Cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [Alert addAction:camera];
    [Alert addAction:Gallery];
    [Alert addAction:Cancel];
    [self presentViewController:Alert animated:true completion:nil];
    
}

#pragma mark - Image Upload One By One Method

-(void) SendImageData{
    
    
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *params = @{@"photo":[UIImagePNGRepresentation(scaledimage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/upload_record_pic.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSString *DataArray;
            if ((DataArray = [responseObject valueForKey:@"success"]))
            {
                NSLog(@"Weather record created");
                //                name
                //                preview
                ImageName = [responseObject valueForKey:@"name"];
                ImagePreviewLink=[responseObject valueForKey:@"preview"];
                
                [ImagesDataArray insertObject:@{@"is_link":ImageName,@"image":ImagePreviewLink} atIndex:ImagesDataArray.count-1];
                [_Collectionview_Image reloadData];
                [_Collectionview_Image scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:ImagesDataArray.count-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionRight 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");
            [self SendImageData];
            //[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];
        
    }];
}





#pragma mark- All Method
- (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"];
                    
                    //SET PROJECT AND JOB DATA...
                    NSString *TempProjectID,*TempJobID;
                    if ((TempProjectID = [[NSUserDefaults standardUserDefaults]objectForKey:@"PROJECT_ID"]) && (TempJobID = [[NSUserDefaults standardUserDefaults]objectForKey:@"JOB_ID"])) {
                        int TempproID = [TempProjectID intValue];
                        int TempjobID = [TempJobID intValue];
                        
                        int i;
                        for (i=0; i<ProjectArray.count; i++) {
                            NSString *proID,*jobID;
                            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];
                                JobArray = [[ProjectArray objectAtIndex:i]valueForKey:@"jobs"];
                                int x;
                                for (x=0; x<JobArray.count; x++) {
                                    jobID = [[JobArray objectAtIndex:x] valueForKey:@"job_id"];
                                    if ([jobID intValue] == TempjobID) {
                                        [_btn_Job setTitle:[[JobArray objectAtIndex:x] valueForKey:@"job_title"] forState:UIControlStateNormal];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        [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"];
    //    JobArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"SubArray"];
    
    //SET PROJECT AND JOB DATA...
    NSString *TempProjectID,*TempJobID;
    if ((TempProjectID = [[NSUserDefaults standardUserDefaults]objectForKey:@"PROJECT_ID"])) {
        int TempproID = [TempProjectID intValue];
        int TempjobID = [TempJobID intValue];
        NSLog(@"Tempjobid:-- %d",TempjobID);
        
        
        int i;
        for (i=0; i<ProjectArray.count; i++) {
            NSString *proID,*jobID;
            NSLog(@"Job id :--- %@",jobID);
            
            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];
                //                JobArray = [[ProjectArray objectAtIndex:i]valueForKey:@"jobs"];
                //                int x;
                //                for (x=0; x<JobArray.count; x++) {
                //                    jobID = [[JobArray objectAtIndex:x] valueForKey:@"job_id"];
                //                    if ([jobID intValue] == TempjobID) {
                //                        [_btn_Job setTitle:[[JobArray objectAtIndex:x] valueForKey:@"job_title"] forState:UIControlStateNormal];
                //                    }
                //                }
            }
        }
    }
}

-(void) sendAccidentData{
    
    NSString *ProID,*JobID,*UID,*Desc,*picture;
    NSMutableArray *ImageData;
    
    
    
    
    if (IsSelectImage==1)
    {
        picture = [self encodeToBase64String:_Imgview_AddPhoto.image];
        if (!picture.length) {
            picture = @"";
        }
    }
    else
    {
        picture=@"";
    }
    
    
    
    
    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 (!(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";
    }
    
    NSString *Name,*PhoneNumber,*CompanyName,*incidentDateTime,*incident_type;
    if (![_txt_Name.text  isEqual: @""]) {
        Name = _txt_Name.text;
    }
    else{
        return;
    }
    
    if (![_txt_PhoneNumber.text  isEqual: @""]) {
        PhoneNumber = _txt_PhoneNumber.text;
    }
    else{
        PhoneNumber = @"";
    }
    
    if (![_txt_CompanyName.text  isEqual: @""]) {
        CompanyName = _txt_CompanyName.text;
    }
    else{
        CompanyName = @"";
    }
    
    if (![SelectedTime  isEqual: @""] && ![SelectedDate  isEqual: @""]) {
        
        incidentDateTime = SelectedDate;
        incidentDateTime = [incidentDateTime stringByAppendingString:@" "];
        incidentDateTime = [incidentDateTime stringByAppendingString:SelectedTime];
        //        incidentDateTime = [incidentDateTime stringByAppendingString:@":15"];
    }
    else{
        return;
    }
    
    if (RadioFlag == 0) {
        incident_type = @"Property Damage";
    }
    else if (RadioFlag == 1){
        if (![_txt_Radio_Other.text  isEqual: @""]) {
            incident_type = _txt_Radio_Other.text;
        }
        else{
            incident_type = @"Property Damage";
        }
    }
    
    if (![_textview_Write.text  isEqual: @""] || ![_textview_Write.text  isEqual: @"Write Detailed Description..."]) {
        Desc = _textview_Write.text;
    }
    else{
        Desc = @"";
    }
    
    NSString *nameArray,*PhoneArray;
    nameArray = [[NSString alloc]init];
    PhoneArray = [[NSString alloc]init];
    
    
    if (WittnessNameArray.count != 0 && WittnessMobileArray.count != 0) {
        int i;
        for (i = 0; i < WittnessNameArray.count; i++) {
            
            if (WittnessNameArray.count == 1) {
                nameArray = [WittnessNameArray objectAtIndex:0];
                PhoneArray = [WittnessMobileArray objectAtIndex:0];
            }
            else{
                if (i == 0) {
                    
                    nameArray = [WittnessNameArray objectAtIndex:0];
                    nameArray = [nameArray stringByAppendingString:@","];
                    
                    PhoneArray = [WittnessMobileArray objectAtIndex:0];
                    PhoneArray = [PhoneArray stringByAppendingString:@","];
                }
                else{
                    if (WittnessNameArray.count-1 == i) {
                        nameArray = [nameArray stringByAppendingString:[WittnessNameArray objectAtIndex:i]];
                        
                        PhoneArray = [PhoneArray stringByAppendingString:[WittnessMobileArray objectAtIndex:i]];
                    }
                    else{
                        nameArray = [nameArray stringByAppendingString:[WittnessNameArray objectAtIndex:i]];
                        nameArray = [nameArray stringByAppendingString:@","];
                        
                        PhoneArray = [PhoneArray stringByAppendingString:[WittnessMobileArray objectAtIndex:i]];
                        PhoneArray = [PhoneArray stringByAppendingString:@","];
                        
                    }
                }
                
            }
        }
    }
    else{
        
        if (![_txt_WitnessName.text  isEqual: @""] && ![_txt_WitnessNumber.text  isEqual: @""]) {
            //Fille Two
            nameArray = _txt_WitnessName.text;
            PhoneArray = _txt_WitnessNumber.text;
        }
        else if ([_txt_WitnessName.text  isEqual: @""] || [_txt_WitnessNumber.text  isEqual: @""]){
            if (![_txt_WitnessName.text  isEqual: @""] && [_txt_WitnessNumber.text  isEqual: @""]) {
                nameArray = _txt_WitnessName.text;
                PhoneArray = @"";
            }
            else{
                /*
                 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Fill Name" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                 [alert show];
                 return;
                 */
            }
        }
    }
    
    
    if (WittnessNameArray.count == 0 && WittnessMobileArray.count == 0) {
        if (![_txt_WitnessName.text  isEqual: @""] && ![_txt_WitnessNumber.text  isEqual: @""]) {
            //Fille Two
            [WittnessNameArray addObject:_txt_WitnessName.text];
            [WittnessMobileArray addObject:_txt_WitnessNumber.text];
        }
        else if ([_txt_WitnessName.text  isEqual: @""] || [_txt_WitnessNumber.text  isEqual: @""]){
            if (![_txt_WitnessName.text  isEqual: @""] && [_txt_WitnessNumber.text  isEqual: @""]) {
                [WittnessNameArray addObject:_txt_WitnessName.text];
                PhoneArray = @"";
            }
            else{
                /*
                 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Fill Name" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                 [alert show];
                 return;
                 */
            }
        }
    }
    
    if (!ImagesDataArray.count) {
        [ImagesDataArray addObject:@""];
    }
    
    [ImagesDataArray removeLastObject];
    if (ImagesDataArray.count) {
        ImageData = [[NSMutableArray alloc]initWithArray:[ImagesDataArray valueForKey:@"is_link"]];
    }
    else{
        ImageData = [[NSMutableArray alloc]initWithArray:@[]];
    }
    
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];
    
    
    NSDictionary *params = @{@"uid":UID,@"project_id":ProID,@"job_id":JobID,@"name":Name,@"phone":PhoneNumber,@"company":CompanyName,@"incident_datetime":incidentDateTime,@"incident_type":incident_type,@"description":Desc,@"wname":WittnessNameArray,@"wphone":WittnessMobileArray,@"details":WittnessDescArray,@"photo":ImageData};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/accident_save.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSLog(@"%@",responseObject);
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                NSLog(@"incident record created");
                
                NSMutableArray *record = [responseObject valueForKey:@"records"];
                [delegate getRecordArray:record];
                
                [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view WithMessage:@"Record Added"];
                
                //                AccidentsListVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"AccidentsListVC"];
                //                [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) sendEditedAccidentData{
    
    NSString *ProID,*JobID,*UID,*Desc,*picture;
    NSData *GetUserData;
    NSMutableArray *ImageData;
    
    
    if (IsSelectImage==1)
    {
        picture = [self encodeToBase64String:_Imgview_AddPhoto.image];
        if (!picture.length) {
            picture = @"";
        }
    }
    else
    {
        picture=@"";
    }
    
    
    
    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 (!(ProID = [[NSUserDefaults standardUserDefaults] objectForKey:@"PROJECT_ID"]))
    {
        return;
    }
    if ((!(JobID = [[NSUserDefaults standardUserDefaults] objectForKey:@"JOB_ID"]))) {
        JobID = @"-1";
    }
    
    NSString *Name,*PhoneNumber,*CompanyName,*incidentDateTime,*incident_type,*incident_id;
    incident_id = [_EditedArray valueForKey:@"id"];
    
    if (![_txt_Name.text  isEqual: @""]) {
        Name = _txt_Name.text;
    }
    else{
        return;
    }
    
    if (![_txt_PhoneNumber.text  isEqual: @""]) {
        PhoneNumber = _txt_PhoneNumber.text;
    }
    else{
        PhoneNumber = @"";
    }
    
    if (![_txt_CompanyName.text  isEqual: @""]) {
        CompanyName = _txt_CompanyName.text;
    }
    else{
        CompanyName = @"";
    }
    
    if (![SelectedTime  isEqual: @""] || ![SelectedDate  isEqual: @""]) {
        incidentDateTime = SelectedDate;
        incidentDateTime = [incidentDateTime stringByAppendingString:@" "];
        incidentDateTime = [incidentDateTime stringByAppendingString:SelectedTime];
        //        incidentDateTime = [incidentDateTime stringByAppendingString:@":15"];
    }
    else{
        incidentDateTime = editedDateTime;
    }
    
    if (RadioFlag == 0) {
        incident_type = @"Property Damage";
    }
    else if (RadioFlag == 1){
        if (![_txt_Radio_Other.text  isEqual: @""]) {
            incident_type = _txt_Radio_Other.text;
        }
        else{
            incident_type = @"Property Damage";
        }
    }
    
    if (![_textview_Write.text  isEqual: @""] || ![_textview_Write.text  isEqual: @"Write Detailed Description..."]) {
        Desc = _textview_Write.text;
    }
    else{
        Desc = @"";
    }
    
    NSString *nameArray,*PhoneArray;
    nameArray = [[NSString alloc]init];
    PhoneArray = [[NSString alloc]init];
    
    
    if (WittnessNameArray.count != 0 && WittnessMobileArray.count != 0) {
        int i;
        for (i = 0; i < WittnessNameArray.count; i++) {
            
            if (WittnessNameArray.count == 1) {
                nameArray = [WittnessNameArray objectAtIndex:0];
                PhoneArray = [WittnessMobileArray objectAtIndex:0];
            }
            else{
                if (i == 0) {
                    
                    nameArray = [WittnessNameArray objectAtIndex:0];
                    nameArray = [nameArray stringByAppendingString:@","];
                    
                    PhoneArray = [WittnessMobileArray objectAtIndex:0];
                    PhoneArray = [PhoneArray stringByAppendingString:@","];
                }
                else{
                    if (WittnessNameArray.count-1 == i) {
                        nameArray = [nameArray stringByAppendingString:[WittnessNameArray objectAtIndex:i]];
                        
                        PhoneArray = [PhoneArray stringByAppendingString:[WittnessMobileArray objectAtIndex:i]];
                    }
                    else{
                        nameArray = [nameArray stringByAppendingString:[WittnessNameArray objectAtIndex:i]];
                        nameArray = [nameArray stringByAppendingString:@","];
                        
                        PhoneArray = [PhoneArray stringByAppendingString:[WittnessMobileArray objectAtIndex:i]];
                        PhoneArray = [PhoneArray stringByAppendingString:@","];
                        
                    }
                }
                
            }
            
        }
    }
    else{
        if (![_txt_WitnessName.text  isEqual: @""] && ![_txt_WitnessNumber.text  isEqual: @""]) {
            //Fille Two
            nameArray = _txt_WitnessName.text;
            PhoneArray = _txt_WitnessNumber.text;
        }
        else if ([_txt_WitnessName.text  isEqual: @""] || [_txt_WitnessNumber.text  isEqual: @""]){
            if (![_txt_WitnessName.text  isEqual: @""] && [_txt_WitnessNumber.text  isEqual: @""]) {
                nameArray = _txt_WitnessName.text;
                PhoneArray = @"";
            }
            else{
                if (_EditedsplitNameArray.count != 0) {
                    int i;
                    for (i = 0; i < _EditedsplitNameArray.count; i++) {
                        
                        if (_EditedsplitNameArray.count == 1) {
                            nameArray = [_EditedsplitNameArray objectAtIndex:0];
                            PhoneArray = [_EditedsplitPhoneArray objectAtIndex:0];
                        }
                        else{
                            if (i == 0) {
                                
                                nameArray = [_EditedsplitNameArray objectAtIndex:0];
                                nameArray = [nameArray stringByAppendingString:@","];
                                
                                PhoneArray = [_EditedsplitPhoneArray objectAtIndex:0];
                                PhoneArray = [PhoneArray stringByAppendingString:@","];
                            }
                            else{
                                if (_EditedsplitNameArray.count-1 == i) {
                                    nameArray = [nameArray stringByAppendingString:[_EditedsplitNameArray objectAtIndex:i]];
                                    
                                    PhoneArray = [PhoneArray stringByAppendingString:[_EditedsplitPhoneArray objectAtIndex:i]];
                                }
                                else{
                                    nameArray = [nameArray stringByAppendingString:[_EditedsplitNameArray objectAtIndex:i]];
                                    nameArray = [nameArray stringByAppendingString:@","];
                                    
                                    PhoneArray = [PhoneArray stringByAppendingString:[_EditedsplitPhoneArray objectAtIndex:i]];
                                    PhoneArray = [PhoneArray stringByAppendingString:@","];
                                    
                                }
                            }
                            
                        }
                        
                    }
                }
            }
        }
    }
    
    
    if (WittnessNameArray.count == 0 && WittnessMobileArray.count == 0) {
        if (![_txt_WitnessName.text  isEqual: @""] && ![_txt_WitnessNumber.text  isEqual: @""]) {
            //Fille Two
            [WittnessNameArray addObject:_txt_WitnessName.text];
            [WittnessMobileArray addObject:_txt_WitnessNumber.text];
        }
        else if ([_txt_WitnessName.text  isEqual: @""] || [_txt_WitnessNumber.text  isEqual: @""]){
            if (![_txt_WitnessName.text  isEqual: @""] && [_txt_WitnessNumber.text  isEqual: @""]) {
                [WittnessNameArray addObject:_txt_WitnessName.text];
                PhoneArray = @"";
            }
            else{
                /*
                 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Fill Name" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                 [alert show];
                 return;
                 */
            }
        }
    }
    
    if (!ImagesDataArray.count) {
        [ImagesDataArray addObject:@""];
    }
    
    [ImagesDataArray removeLastObject];
    if (ImagesDataArray.count) {
        ImageData = [[NSMutableArray alloc]initWithArray:[ImagesDataArray valueForKey:@"is_link"]];
    }
    else{
        ImageData = [[NSMutableArray alloc]initWithArray:@[]];
    }
    
    
    
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:150.0];
    
    NSDictionary *params = @{@"incident_id":incident_id,@"uid":UID,@"project_id":ProID,@"job_id":JobID,@"name":Name,@"phone":PhoneNumber,@"company":CompanyName,@"incident_datetime":incidentDateTime,@"incident_type":incident_type,@"description":Desc,@"wname":WittnessNameArray,@"wphone":WittnessMobileArray,@"details":WittnessDescArray,@"photo":ImageData};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/accident_save.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSLog(@"%@",responseObject);
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                NSLog(@"incident record Updated");
                
                NSMutableArray *record = [responseObject valueForKey:@"records"];
                [delegate getRecordArray:record];
                
                [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view WithMessage:@"Record updated"];
                
                //                AccidentsListVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"AccidentsListVC"];
                //                [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 == 3840) {
            UIAlertView *alert = [[UIAlertView alloc]init];
            alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@" Error Domain" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        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];
        }
        else{
            [ApiUtillity dissmissSVProgressHUDView:self.view];
        }
    }];
    
}

-(void)WittnessNameArray:(NSMutableArray *)NameArray WittnessMobileArray:(NSMutableArray *)MobileArray WittnessDescArray:(NSMutableArray *)DescArray{
    NSLog(@"NameArray :-%@ AND MobileArray :-%@ AND Desc :-%@",NameArray,MobileArray,DescArray);
    WittnessNameArray = NameArray;
    WittnessMobileArray = MobileArray;
    WittnessDescArray = DescArray;
}

- (void)dateWasSelected:(NSDate *)selectedDate element:(id)element
{
    self.selectedDate = selectedDate;
    NSArray *MainDate = [[self.selectedDate description] componentsSeparatedByString:@" "];
    NSString *Date = [MainDate objectAtIndex:0];
    
    //    NSArray *seperatedate = [Date componentsSeparatedByString:@"-"];
    //    dob = [dob stringByAppendingString:seperatedate[2]];
    //    dob = [dob stringByAppendingString:@"-"];
    //    dob = [dob stringByAppendingString:seperatedate[1]];
    //    dob = [dob stringByAppendingString:@"-"];
    //    dob = [dob stringByAppendingString:seperatedate[0]];
    //    NSLog(@"%@",dob);
    //    self.btnSelectDate.titleLabel.text = Date;
    
    [_btn_IncidentDate setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btn_IncidentDate setTitle:Date forState:UIControlStateNormal];
    SelectedDate = Date;
}

-(void)timeWasSelected:(NSDate *)selectedTime element:(id)element {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
    [dateFormatter setDateFormat:@"hh:mm a"];
    //    [dateFormatter setDateFormat:@"H:mm a"];
    //    [element setText:[dateFormatter stringFromDate:selectedTime]];
    
    [_btn_IncidentTime setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_btn_IncidentTime setTitle:[dateFormatter stringFromDate:selectedTime] forState:UIControlStateNormal];
    SelectedTime = [dateFormatter stringFromDate:selectedTime];
    NSLog(@"%@",selectedTime);
    
}

#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];
    }
}
-(void)textViewDidBeginEditing:(UITextView *)textView{
    tag = textView.tag;
}

#pragma TextField Delegate
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    tag = textField.tag;
}



-(void) SetPrevNextButton{
    
    [_txt_Name addPreviousNextDoneOnKeyboardWithTarget:self previousAction:@selector(previousAction:) nextAction:@selector(nextAction:) doneAction:@selector(doneAction:)];
    [_txt_PhoneNumber addPreviousNextDoneOnKeyboardWithTarget:self previousAction:@selector(previousAction:) nextAction:@selector(nextAction:) doneAction:@selector(doneAction:)];
    [_txt_CompanyName addPreviousNextDoneOnKeyboardWithTarget:self previousAction:@selector(previousAction:) nextAction:@selector(nextAction:) doneAction:@selector(doneAction:)];
    [_textview_Write addPreviousNextDoneOnKeyboardWithTarget:self previousAction:@selector(previousAction:) nextAction:@selector(nextAction:) doneAction:@selector(doneAction:)];
}

/*! previousAction. */
-(void)previousAction:(id)button
{
    //previousAction
    //nextAction
    if (_txt_Name.tag == tag) {
        [_txt_Name resignFirstResponder];
        return;
    }
    if (_txt_PhoneNumber.tag == tag) {
        [_txt_Name becomeFirstResponder];
        [_txt_PhoneNumber resignFirstResponder];
        return;
    }
    if (_txt_CompanyName.tag == tag) {
        [_txt_PhoneNumber becomeFirstResponder];
        [_txt_CompanyName resignFirstResponder];
        return;
    }
    if (_textview_Write.tag == tag) {
        [_txt_CompanyName becomeFirstResponder];
        [_textview_Write resignFirstResponder];
        return;
    }
}

/*! nextAction. */
-(void)nextAction:(id)button
{
    NSLog(@"%@",button);
    //nextAction
    if (_txt_Name.tag == tag) {
        [_txt_Name resignFirstResponder];
        [_txt_PhoneNumber becomeFirstResponder];
        return;
    }
    if (_txt_PhoneNumber.tag == tag) {
        [_txt_PhoneNumber resignFirstResponder];
        [_txt_CompanyName becomeFirstResponder];
        return;
    }
    if (_txt_CompanyName.tag == tag) {
        [_txt_CompanyName resignFirstResponder];
        [_textview_Write becomeFirstResponder];
        return;
    }
    if (_textview_Write.tag == tag) {
        [_textview_Write resignFirstResponder];
        return;
    }
}

/*! doneAction. */
-(void)doneAction:(UIBarButtonItem*)barButton
{
    //doneAction
    [self.view endEditing:true];
}

@end
