<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Api extends CI_Controller {
function __construct() {
        parent::__construct();
         $this->load->model('user_model');     
         $this->load->helper(array('url','upload'));    
    }
	
    			/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            27-09-2017 
     * Description:     Login
     */ 
	function login()
     {
		 //$data['username'] =$this->input->post('username');
         $data['username'] =$this->input->post('username');
		 $data['password'] = $this->input->post('password');
         $data['app_version'] = $this->input->post('app_version');
       
         if((isset($data['username']) && $data['username']!=NULL) && (isset($data['password']) && $data['password']!=NULL))
         {
         	$user_exist = $this->user_model->check_email($data);
//print_r($user_exist);die;
         	if(isset($user_exist) && !empty($user_exist))
	        {
	       // print_r($data);
	            $ud = $this->user_model->login_data_app($data);
	            //print_r($ud);
	            if(isset($ud) && !empty($ud))
	            {

						
						$userid=$ud[0]['id'];
						
						if(isset($data['app_version']) && $data['app_version'] !=''){
						$where='id='.$userid;
	            		$this->user_model->update('login',array('app_version'=>$data['app_version']),$where); 
						}
						
						
						if(isset($ud[0]['district_id']) && $ud[0]['district_id'] !=''){
							//$district_id=$ud[0]['district_id'];
							$district_data = $this->user_model->getLocationById($ud[0]['district_id'],'district');
//print_r($district_data);
							$district_id=$district_data[0]['name'];
						}else
						{
							$district_id='';
						}
						if($ud[0]['block_id'] !=0){
							$block_data = $this->user_model->getLocationById($ud[0]['block_id'],'block');
							$block_id=$block_data[0]['name'];
						}else
						{
							$block_id='';
						}
						/*if($ud[0]['taluk_id']) !=0){
							$taluk_data = $this->user_model->getLocationById($ud[0]['taluk_id'],'taluk');
							$taluk_id=$taluk_data[0]['name'];
						}else
						{
							$taluk_id='';
						}*/
$taluk_id='';
						if($ud[0]['muncipality'] !=0){
							$muncipality_data = $this->user_model->getLocationById($ud[0]['muncipality'],'muncipality');
//print_r($muncipality_data);
							$muncipality=$muncipality_data[0]['name'];
						}else
						{
							$muncipality='';
						}
						if($ud[0]['corporation'] !=0){
							$corporation_data = $this->user_model->getLocationById($ud[0]['corporation'],'corporation');
							$corporation=$corporation_data[0]['name'];
						}else
						{
							$corporation='';
						}
						if($ud[0]['panchayath_id'] !=0){
							$panchayath_data = $this->user_model->getLocationById($ud[0]['panchayath_id'],'panchayath');
							$panchayath_id=$panchayath_data[0]['name'];
						}else
						{
							$panchayath_id='';
						}

						if(isset($ud[0]['cds']) && $ud[0]['cds'] !=''){
							$cds=$ud[0]['cds'];
						}else
						{
							$cds='';
						}
						if(isset($ud[0]['ads']) && $ud[0]['ads'] !=''){
							$ads=$ud[0]['ads'];
						}else
						{
							$ads='';
						}
						if(isset($ud[0]['constitution']) && $ud[0]['constitution'] !=''){
							$constitution=$ud[0]['constitution'];
						}else
						{
							$constitution='';
						}
						if($ud[0]['place_category'] == 1)//Rural
						{
							//district, taluk, block, cds, constitution
							$place_category = 'Rural';
							$result = array('status'=>ACTIVE,'userid'=>$userid,'district_id'=>$district_id,'taluk_id'=>$taluk_id,'place_category'=>$ud[0]['place_category'],'block_id'=>$block_id,'cds'=>$cds,'ads'=>$ads,'constitution'=>$constitution,'panchayath_id'=>$panchayath_id);
						}else if($ud[0]['place_category'] == 2) //Urban
						{
							//district, corporation, muncipality, cds, constitution
							$place_category = 'Urban';
							$result = array('status'=>ACTIVE,'userid'=>$userid,'district_id'=>$district_id,'taluk_id'=>$taluk_id,'place_category'=>$ud[0]['place_category'],'muncipality'=>$muncipality,'corporation'=>$corporation,'cds'=>$cds,'ads'=>$ads,'constitution'=>$constitution);
						}else
						{
							$result = array('status'=>ACTIVE,'userid'=>$userid,'district_id'=>'','taluk_id'=>'','place_category'=>'','block_id'=>'','muncipality'=>'','corporation'=>'','cds'=>'','ads'=>'','constitution'=>'');
						}
					
					//$result = array('status'=>ACTIVE,'userid'=>$userid,'district_id'=>$district_id,'taluk_id'=>$taluk_id,'palce_category'=>$palce_category,'block_id'=>$block_id,'muncipality'=>$muncipality,'corporation'=>$corporation,'cds'=>$cds);
	                echo json_encode($result); 
	            }
	            else
	            {
					
	               $result = array('status'=>INACTIVE,'userid'=>'');
	               echo json_encode($result);   
	            }
	        }else
	        {
	        		$result = array('status'=>NOT_FOUND,'userid'=>'');
	            	echo json_encode($result);
	        
	        }
         }
         else 
         {
            $result = array();
            echo json_encode($result);
         }
         
     }
			/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            27-09-2017 
     * Description:     Adding survey details
     */
	public function get_all_location()
		{
			$data['version_district']	=	$this->input->post('version_district');
			$current_db_version			=	$this->user_model->get_location_version();

			/*if($current_db_version[0]['loc_version'] == $data['version_district'])
				{
					$location['location'] 		= 	'';
					$location['version'] 		= 	$current_db_version[0]['loc_version'];
				}
			else	
				{
					$location['location'] 		= 	$this->user_model->get_location_api();
					$location['version'] 		= 	$current_db_version[0]['loc_version'];
				}*/
			$location['location'] 		= 	$this->user_model->get_location_api();
			$location['version'] 		= 	$current_db_version[0]['loc_version'];
			echo json_encode($location);
		}
	
			function test(){
				phpinfo();
			}
	
	function insert_survey()
	{
		$data1['jsonForm'] 	= 	$this->input->post('jsonForm');
		$jsondata			=	json_decode((($data1['jsonForm'])));
		$res 				=	array();
		$api_call['api_call']=	$data1['jsonForm'];
		$api_call['method']	=	'insert_survey';
		$api_log_id 		= 	$this->user_model->save('api_log',$api_call);
		if(isset($jsondata)&&!empty($jsondata))
			{ 
				$i 			=	1;
				foreach($jsondata as $row)
					{
						$survey_flag			=	0;
						$member_flag			=	0;
						$issue_flag				=	0;
						$diseases_flag			=	0;
						$members 				=	array();
						$data['survey_appid'] 	= 	$row->survey_appid;
						$submitTime 			= 	$row->submitTime;
						$survey_time_stamp 		= 	$row->survey_time_stamp;
						$suvey_date 			=  	$row->suvey_date;
						$data['name'] 			= 	urldecode($row->name);
						$data['address'] 		= 	urldecode($row->address);
						$data['agent_id'] 		=  	$row->agent_id;
						$data['caste'] 			=  	$row->cast;
						$data['village'] 		=  	urldecode($row->village);
						$data['category'] 		=  	$row->category;
						$data['dist_code'] 		=  	$row->log_district;
						
						if(isset($row->kudumbasree_opinion) && !empty($row->kudumbasree_opinion))
							{
								$data['kudumbasree_opinion'] =  urldecode($row->kudumbasree_opinion);
							}
						if(isset($row->opinion_details) && !empty($row->opinion_details))
							{
								$data['opinion_details'] =  urldecode($row->opinion_details);
							}
						if(isset($row->ads_opinion) && !empty($row->ads_opinion))
							{
								$data['ads_opinion'] =  urldecode($row->ads_opinion);
							}
						if(isset($row->cds_opinion) && !empty($row->cds_opinion))
							{
								$data['cds_opinion'] =  urldecode($row->cds_opinion);
							}	
						if($row->category == 3)
							{
								$data['general_specify'] 	=  	$row->general_specify;
							}						
						$data['suvey_date'] 	=	date('Y-m-d H:i:s', strtotime($suvey_date));
						$data['survey_time_stamp'] 	=	date('Y-m-d H:i:s', strtotime($survey_time_stamp));
						if(isset($row->place_category) && !empty($row->place_category))
							{
								$data['place_category'] =  $row->place_category;
							}

						if(isset($row->mobile) && !empty($row->mobile))
							{
								$data['mobile'] =  $row->mobile;
							}
						$data['ward_no'] 		=  $row->ward_no;
						$data['cast_other'] 	=  $row->cast_other;
						if(isset($row->ben_house_number) && !empty($row->ben_house_number))
							{
								$data['house_no'] =  $row->ben_house_number;
							}
						if(isset($row->project_category) && !empty($row->project_category))
							{
							$data['project_category'] 			=  $row->project_category;
							$data['project_category_remark'] 	=  urldecode($row->project_category_remark);
							}
						if(isset($row->family_members) && !empty($row->family_members))
							{
							$data['family_members'] =  $row->family_members;
							}
						if(isset($row->ration_card) && !empty($row->ration_card))
							{
								$data['ration_card'] =  $row->ration_card;
							}
						$data['ration_card_no'] 	=  $row->ration_card_no;
						$data['ration_shop_no'] 	=  $row->ration_shop_no;
						
						$data['ration_card_color'] 	=  $row->ration_card_color;						
						$data['land'] 				=  $row->land;
						$data['own_place_category'] =  $row->own_place_category;
						
						$data['is_exist_member']	=  $row->is_exist_member;
						$data['app_version']		=  $row->app_version;
						$data['home_govt']			=  $row->home_govt;
						$data['home_govt_category']	=  $row->home_govt_category;
						$data['continue_service']	=  $row->continue_service;
						if(isset($row->about_informer) && !empty($row->about_informer))
							{
								$data['about_informer'] =  urldecode($row->about_informer);
							}						$data['longitude'] 			=  $row->longitude;
						$data['latitude']			=  $row->latitude;

						if($row->land == 1)//yes
							{
								$data['land_cent'] 			=  $row->land_cent;
							}
						if(isset($row->ayalkootam_member) && !empty($row->ayalkootam_member))
							{ 
								$data['ayalkootam_member'] =  $row->ayalkootam_member;
							}
						$data['ayalkootam_name'] 	=  urldecode($row->ayalkootam_name);
						$data['ayalkootam_ward_no'] =  $row->ayalkootam_ward_no;
						if(isset($row->oldage_home_stay) && !empty($row->oldage_home_stay))
							{ 
								$data['oldage_home_stay'] =  $row->oldage_home_stay;
							}
						if((isset($data['agent_id']) && $data['agent_id']!='') && (isset($data['name']) && $data['name']!='') && (isset($data['survey_appid']) && $data['survey_appid']!='') && (isset($data['survey_time_stamp']) && $data['survey_time_stamp']!='') && (isset($data['place_category']) && $data['place_category']!=0) )
						{ 
						// checking family table
						$data['log_id'] =  	$api_log_id;
						$data['status'] =  	ACTIVE;
						
						$where 			= 	array('agent_id' => $data['agent_id'],'survey_appid'=>$data['survey_appid'],'survey_time_stamp'=>$data['survey_time_stamp']);
						$survey_exist	=	$this->user_model->get_datum('survey_family','family_id',$where);
						if(empty($survey_exist) && count($survey_exist) == 0)
							{
								$family_id = $this->user_model->save('survey_family',$data);
								if($family_id > 0)
									{
										$dist_limit 	= 	mb_substr($data['dist_code'], 0, 3);
										$rand_code		= 	str_pad($family_id, 5, '0', STR_PAD_LEFT);
										$dist_code		=	$dist_limit.'-'.$rand_code;
										$arry 			= 	array('dist_code' => $dist_code);
										$result 		= 	$this->user_model->update('survey_family',$arry,array('family_id'=>$family_id));
										//upload_api($family_id,$i);
										$this->upload_file($family_id,$i);
										$survey_flag 	=	1;
									}
							}
						else
							{	
								$family_id 		=	$survey_exist['family_id'];
								$survey_flag 	=	1;
							}
						// To check the family_members count = to family_member_arr	
						$family_members_count	=	$row->family_members;
							
						if($row->is_exist_member ==2)////member exists (if is_exist_member == 2 )
							{
								// checking family members table
								if(!empty($row->family_member_arr) && $family_id > 0)
									{
										$member_arr  = json_decode(($row->family_member_arr));
										$family_member_arr_count=	count($member_arr);
										foreach($member_arr as $mem_arr)
										{
											if(!empty($mem_arr->member_name))
												{
													$member_time_stamp 	=	date('Y-m-d H:i:s', strtotime($mem_arr->member_time_stamp));
													$member_where = array('agent_id' => $data['agent_id'],'member_appid'=>$mem_arr->member_appid,'member_time_stamp'=>$member_time_stamp,'family_id'=>$family_id);
													$member_exist = $this->user_model->get_datum('family_members','family_id',$member_where);
													if(empty($member_exist) && count($member_exist) == 0)
														{		
															$members['family_id'] 			=	$family_id;
															$members['member_name']			=	urldecode($mem_arr->member_name);
															if(isset($mem_arr->gender) && !empty($mem_arr->gender))
																{
																	$members['gender']		=	$mem_arr->gender;
																}
															if(isset($mem_arr->age) && !empty($mem_arr->age))
																{
																	$members['age']			=	$mem_arr->age;
																}
															$members['family_relation'] 	=	$mem_arr->family_relation;	
															$members['education'] 			=	$mem_arr->education;
															$members['job']					=	$mem_arr->job;
															if($mem_arr->job == 11) //മറ്റുള്ളവ refers job_options_master id
																{
																	$members['job']			=	$mem_arr->memberJobDetails;
																}
															$members['physical_condition']	=	$mem_arr->physical_condition;
															if($mem_arr->physical_condition == 1)//Have issues
																{
																	$members['memberhealthcondition']	=	$mem_arr->memberHealthCondition;
																	$members['memberhealthconditiondetails']	=	urldecode($mem_arr->memberHealthConditionDetails);
																}
															if(isset($mem_arr->pensionAvail) && !empty($mem_arr->pensionAvail))
																{
																	$members['pensionavail']		=	$mem_arr->pensionAvail;
																}										
																$members['pension']				=	$mem_arr->pension;
																if($mem_arr->pension == 6) //????????? refers pension_category_master id
																{
																	$members['member_pension_details']	=	urldecode($mem_arr->member_pension_details);
																}
															$members['monthly_income']		=	$mem_arr->monthly_income;
															$members['aadhar_no']			=	$mem_arr->aadhar_no;
															$members['remarks']				=	urldecode($mem_arr->remarks);
															$members['member_appid']		=	$mem_arr->member_appid;
															$members['agent_id']			=	$data['agent_id'];
															$members['member_time_stamp']	=	$member_time_stamp;
															$member_id 						= 	$this->user_model->save('family_members',$members);
															if($member_id > 0)
																{	
																	// disease issues
																	$member_die  = json_decode(($mem_arr->member_disease));
																	if(!empty($member_die) && isset($member_die))
																		{
																			foreach ($member_die as $disease)
																				{
																					foreach ($disease as $ques => $ans) 
																						{
																							$disease_where 	= array('family_member_id' => $member_id,'question_id'=>$ques);
																							$disease_exist  = $this->user_model->get_datum('diseases_issues','family_member_id',$disease_where);
																							if(empty($disease_exist) && count($disease_exist) == 0)
																							{
																								$d['family_member_id']	=	$member_id;
																								$d['question_id']		=	$ques;
																								$d['answer']			=	$ans;
																								
																								$disease_id[] 			= 	$this->user_model->save('diseases_issues',$d);
																								$diseases_flag 			= 	1;
																							}
																						else
																							{
																								$diseases_flag 					= 1;
																							}
																						}					
																				}
																			$diseases_flag 		= 	1;
																			$member_flag 		=	1;	
																		}
																	else
																		{
																			$diseases_flag 		= 	1;
																			$member_flag 		=	1;
																		}
																	/*NEW ARRAY*/
																	$service_arr  = json_decode(($mem_arr->service_arr));
																	if(!empty($service_arr))
																		{
																			$yes 					=	1;//yes
																			foreach ($service_arr as $eachService) 
																				{
																					$agt_id  		= 	$data['agent_id'];
																					$serv_id  		= 	$eachService->service_appid;
																					$serv_time_stamp = 	$eachService->service_time_stamp;
																					$serv_time_stamp =	date('Y-m-d H:i:s', strtotime($serv_time_stamp));
																					if(!empty($agt_id) && $agt_id != '')
																						{
																							$serve_where = array('agent_id'=>$agt_id,'service_appid'=>$serv_id,'service_time_stamp'=>$serv_time_stamp);
																							$serve_exist = $this->user_model->get_datum('service','id',$serve_where);
																							if(empty($serve_exist) && count($serve_exist) == 0)
																								{   
																									$service['member_name']	=	$members['member_name'];
																									$service['address']		=	$data['address'];
																									$service['age']			=	$members['age'];
																									$service['gender']		=	$members['gender'];
																									
																									if(isset($eachService->toilet) && !empty($eachService->toilet))
																										{
																											$service['toilet']	=	$eachService->toilet;
																										}
																									if(isset($eachService->toilet_amt) && !empty($eachService->toilet_amt))
																										{
																											$service['toilet_amt']		=	$eachService->toilet_amt;
																										}
																									if(isset($eachService->house_modification) && !empty($eachService->house_modification))
																										{
																											$service['house_modification']	=	$eachService->house_modification;
																										}
																									if(isset($eachService->house_modification_amt) && !empty($eachService->house_modification_amt))
																										{
																											$service['house_modification_amt']		=	$eachService->house_modification_amt;
																										}
																									if(isset($eachService->electrification) && !empty($eachService->electrification))
																										{
																											$service['electrification']	=	$eachService->electrification;
																										}
																									if(isset($eachService->electrification_amt) && !empty($eachService->electrification_amt))
																										{
																											$service['electrification_amt']		=	$eachService->electrification_amt;
																										}							
																									if($eachService->food == $yes)
																									{
																										$service['food']		=	$eachService->food;
																										$service['food_amt']	=	$eachService->food_amt;
																									}
																									if($eachService->medical == $yes)
																									{
																										$service['medical']		=	$eachService->medical;
																										$service['medical_amt']	=	$eachService->medical_amt;
																									}
																									if($eachService->dress == $yes)
																									{
																										$service['dress']		=	$eachService->dress;
																										$service['dress_amt']	=	$eachService->dress_amt;
																									}
																									if($eachService->land == $yes)
																									{
																										$service['land']		=	$eachService->land;
																										$service['land_amt']	=	$eachService->land_amt;
																									}
																									
																									if($eachService->home == $yes)
																									{
																										$service['home']		=	$eachService->home;
																										$service['home_amt']	=	$eachService->home_amt;
																									}
																									if($eachService->water == $yes)
																									{
																										$service['water']		=	$eachService->water;
																										$service['water_amt']	=	$eachService->water_amt;
																									}
																									if($eachService->job == $yes)
																									{
																										$service['job']			=	$eachService->job;
																										$service['job_amt']		=	$eachService->job_amt;
																									}
																									if($eachService->pension == $yes)
																									{
																										$service['pension']		=	$eachService->pension;
																										$service['pension_amt']	=	$eachService->pension_amt;
																									}
																									if($eachService->education == $yes)
																									{
																										$service['education']	=	$eachService->education;
																										$service['education_amt']=	$eachService->education_amt;
																									}
																									
																									$service['agent_id']	 =	$data['agent_id'];
																									$service['service_appid']=	$eachService->service_appid;
																									$service['service_time_stamp']	=	$serv_time_stamp;
																									$service['family_id'] 	 =	$family_id;										
																									$data_serve 		= 	$this->user_model->save('service',$service);																
																								}
																							else
																								{
																									$serve_arra_flag			=	1;
																								}
																						}
																				}
																				
																		}
																	/**/	
																}
														}
													else
														{
															$diseases_flag 	= 	1;
															$member_flag 	=	1;
														}
												}
											else
												{
													$diseases_flag 		= 	1;
													$member_flag 		=	1;
												}											
										}
									}
								else
									{
										$member_flag	=	1;
									}
								// checking family issues table
								if(!empty($row->family_issues) && $family_id > 0)
									{
										//1-yes 2-no
										$iss 		= stripslashes($row->family_issues);
										$fam_iss 	= json_decode($iss);
										$sur_arry	= array();
										foreach ($fam_iss[0] as $ques=>$ans) 
											{
												$iss_where		= 	array('question_id'=>$ques,'family_id'=>$family_id);
												$issue_exist	=	$this->user_model->get_datum('family_issues','family_id',$iss_where);
												if(empty($issue_exist) && count($issue_exist) == 0)
													{
														if($ans == 1)//1-yes 2-no
															{
																array_push($sur_arry,$ans);
															}
														$vals 			= 	array('question_id'=>$ques,'answers'=>$ans,'family_id'=>$family_id);
														$data_add 		= 	$this->user_model->save('family_issues',$vals);
														if($data_add > 0)
															{	
																$issue_flag		=	1;
															}
													}
												else
													{
														$issue_flag		=	1;
													}			
											}
										$survey_count_yes 	=	count($sur_arry);											
									}
								else
									{
										$issue_flag 					=	1;
									}
								//checking family more issues => Adikka Kelashangal
								if(!empty($row->family_more_issues) && $family_id > 0)
									{
										$iss 					= 	stripslashes($row->family_more_issues);
										$fam_more_iss 			= 	json_decode($iss);
										$mor_arry				= array();
										foreach ($fam_more_iss[0] as $ques=>$ans) 
											{
												$iss_where		= 	array('question_id'=>$ques,'family_id'=>$family_id);
												$issue_exist	=	$this->user_model->get_datum('family_issues','family_id',$iss_where);
												if(empty($issue_exist) && count($issue_exist) == 0)
													{
														if($ans == 1)//1-yes 2-no
															{
																array_push($mor_arry,$ans);
															}
														$vals 			= 	array('question_id'=>$ques,'answers'=>$ans,'family_id'=>$family_id);
														$data_add 		= 	$this->user_model->save('family_issues',$vals);
														if($data_add > 0)
															{	
																$issue_flag		=	1;
															}
													}
												else
													{
														$issue_flag		=	1;
													}
											}
										$survey_more_count_yes 	=	count($mor_arry);
										if($survey_count_yes >=7 && $survey_more_count_yes >=1)
											{
												$arr 	= array('survey_status' => 1);//approved (7+1 condition)
							        			$res1 	= $this->user_model->update('survey_family',$arr,array('family_id'=>$family_id));
											}
										else
											{
												$arr 	= array('survey_status' => 2);//rejected (7+1 condition fails)
							        			$res1 	= $this->user_model->update('survey_family',$arr,array('family_id'=>$family_id));
											}
									}
								else
									{
										$issue_flag 	=	1;
									}
								if($member_flag ==1 && $survey_flag == 1 && $issue_flag ==1 && $diseases_flag ==1)
									{
										/*To check in family_members TABLE*/
										$cmt_where		= 	array('family_id'=>$family_id);
										$cnt_exist		=	$this->user_model->get_datum('family_members','family_id',$cmt_where);
										$mem_cnt 		=	count($cnt_exist);
										/*To check in diseases_issues TABLE $$%%*/
										$die_where		= 	array('family_member_id'=>$family_id);
										$die_exist		=	$this->user_model->get_datum('diseases_issues','family_member_id',$die_where);
										$die_cnt 		=	count($die_exist);
										/*To check in family_issues TABLE*/
										$fam_where		= 	array('family_id'=>$family_id);
										$fam_exist		=	$this->user_model->get_datum('family_issues','family_id',$fam_where);
										$fam_cnt 		=	count($fam_exist);
										/*To check in service TABLE*/
										$ser_where		= 	array('family_id'=>$family_id);
										$ser_exist		=	$this->user_model->get_datum('service','family_id',$ser_where);
										$ser_cnt 		=	count($ser_exist);
										
										if($mem_cnt == $family_members_count && $die_cnt >0 && $fam_cnt >=10 && $ser_cnt >0)
										{											
											$res[] 	= array('survey_appid'=>$data['survey_appid'],'status'=>ACTIVE,'agent_id'=>$data['agent_id'],'from'=>'2','source'=>'family_success','submitTime'=>$submitTime,'family_id'=>$family_id);
										}
										else
										{
											$res[]  = array('survey_appid'=>$data['survey_appid'],'status'=>INACTIVE,'agent_id'=>$data['agent_id'],'from'=>'2','source'=>'family_mem_count_error','submitTime'=>$submitTime,'family_id'=>$family_id);
										}
									}											
							}
						else //member exists (if is_exist_member == 1 )
							{
								$family_member_arr_count=	$row->family_members;
								if(!empty($row->service_arr))
									{
										$serve1 				=	$row->service_arr;
										$serve2 				= 	stripslashes($serve1);
										$serve_array 			= 	json_decode($serve2);
										$yes 					=	1;//yes
										foreach ($serve_array as $eachService) 
											{
												$agt_id  		= 	$eachService->agent_id;
												$serv_id  		= 	$eachService->service_appid;
												$serv_time_stamp = 	$eachService->service_time_stamp;
												$serv_time_stamp =	date('Y-m-d H:i:s', strtotime($serv_time_stamp));
												if(!empty($agt_id) && $agt_id != '')
													{
														$serve_where = array('agent_id'=>$agt_id,'service_appid'=>$serv_id,'service_time_stamp'=>$serv_time_stamp);
														$serve_exist = $this->user_model->get_datum('service','id',$serve_where);
														if(empty($serve_exist) && count($serve_exist) == 0)
															{   
																$service['member_name']	=	urldecode($eachService->member_name);
																$service['address']		=	urldecode($eachService->address);
																$service['age']			=	$eachService->age;
																$service['gender']		=	$eachService->gender;
																
																if(isset($eachService->service_needed) && !empty($eachService->service_needed))
																{
																	$service['service_needed']	=	$eachService->service_needed;
																}
																if(isset($eachService->service_amt) && !empty($eachService->service_amt))
																{
																	$service['service_amt']		=	$eachService->service_amt;
																}
																																
																if(isset($eachService->toilet) && !empty($eachService->toilet))
																	{
																		$service['toilet']	=	$eachService->toilet;
																	}
																if(isset($eachService->toilet_amt) && !empty($eachService->toilet_amt))
																	{
																		$service['toilet_amt']		=	$eachService->toilet_amt;
																	}
																if(isset($eachService->house_modification) && !empty($eachService->house_modification))
																	{
																		$service['house_modification']	=	$eachService->house_modification;
																	}
																if(isset($eachService->house_modification_amt) && !empty($eachService->house_modification_amt))
																	{
																		$service['house_modification_amt']		=	$eachService->house_modification_amt;
																	}
																if(isset($eachService->electrification) && !empty($eachService->electrification))
																	{
																		$service['electrification']	=	$eachService->electrification;
																	}
																if(isset($eachService->electrification_amt) && !empty($eachService->electrification_amt))
																	{
																		$service['electrification_amt']		=	$eachService->electrification_amt;
																	}
																if($eachService->food == $yes)
																{
																	$service['food']		=	$eachService->food;
																	$service['food_amt']	=	$eachService->food_amt;
																}
																if($eachService->medical == $yes)
																{
																	$service['medical']		=	$eachService->medical;
																	$service['medical_amt']	=	$eachService->medical_amt;
																}
																if($eachService->dress == $yes)
																{
																	$service['dress']		=	$eachService->dress;
																	$service['dress_amt']	=	$eachService->dress_amt;
																}
																if($eachService->land == $yes)
																{
																	$service['land']		=	$eachService->land;
																	$service['land_amt']	=	$eachService->land_amt;
																}
																
																if($eachService->home == $yes)
																{
																	$service['home']		=	$eachService->home;
																	$service['home_amt']	=	$eachService->home_amt;
																}
																if($eachService->water == $yes)
																{
																	$service['water']		=	$eachService->water;
																	$service['water_amt']	=	$eachService->water_amt;
																}
																if($eachService->job == $yes)
																{
																	$service['job']			=	$eachService->job;
																	$service['job_amt']		=	$eachService->job_amt;
																}
																if($eachService->pension == $yes)
																{
																	$service['pension']		=	$eachService->pension;
																	$service['pension_amt']	=	$eachService->pension_amt;
																}
																if($eachService->education == $yes)
																{
																	$service['education']	=	$eachService->education;
																	$service['education_amt']=	$eachService->education_amt;
																}																
																$service['agent_id']	 =	$eachService->agent_id;
																$service['service_appid']=	$eachService->service_appid;
																$service['service_time_stamp']	=	$serv_time_stamp;
																$service['family_id'] 	 =	$family_id;										
																$data_serve 		= 	$this->user_model->save('service',$service);
																if($data_serve)
																	{	
																		$serve_flag		=	1;
																	}
															}
														else
															{
																$serve_flag			=	1;
															}														
														if($serve_flag ==1 && $survey_flag ==1)	
															{
																$res[] 	= array('survey_appid'=>$data['survey_appid'],'status'=>ACTIVE,'agent_id'=>$data['agent_id'],'from'=>'1','source'=>'service success','submitTime'=>$submitTime);
															}	
													}
											}									
									}
								else
									{
										$res[] 	= array('survey_appid'=>$data['survey_appid'],'status1'=>ACTIVE,'agent_id'=>$data['agent_id'],'submitTime'=>$submitTime);
									}	
																		
							}												 
						$i++;
						}
					}
			}
		else
			{
				$res 	= array('survey_appid'=>'','status'=>NOT_FOUND,'agent_id'=>'er','submitTime'=>'');
			}	
		$api_res['response']=	json_encode($res);
		$result 			= 	$this->user_model->update('api_log',$api_res,array('id'=>$api_log_id));
		
		echo json_encode($res);		    	
	}

/*
	 Image upload DEMO
	 */
public function upload_file2($fmly_id,$i)
		{
			if(isset($_FILES["image".$i]))
    	   	{
    	   		if(!is_array($_FILES["image".$i]["name"]))
    	   		{
			$this->load->model('user_model');
			$errors=0;
			define ("MAX_SIZE","400");
			if($_SERVER["REQUEST_METHOD"] == "POST")
			{
			$image =$_FILES["image".$i]["name"];
			$uploadedfile = $_FILES["image".$i]['tmp_name'];

			if ($image) 
			{
				$filename = stripslashes($_FILES["image".$i]['name']);
				$extension = $this->getExtension($filename);
				$extension = strtolower($extension);
				if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
					{
						echo ' Unknown Image extension ';
						$errors=1;
					}
				else
					{
						$size=filesize($_FILES["image".$i]['tmp_name']);

						if ($size > MAX_SIZE*1024)
							{
								echo "You have exceeded the size limit";
								$errors=1;
							}

						if($extension=="jpg" || $extension=="jpeg" )
							{
								$uploadedfile = $_FILES["image".$i]['tmp_name'];
								$src = imagecreatefromjpeg($uploadedfile);
							}
						else if($extension=="png")
							{
								$uploadedfile = $_FILES["image".$i]['tmp_name'];
								$src = imagecreatefrompng($uploadedfile);
							}
						else 
							{
								$src = imagecreatefromgif($uploadedfile);
							}

						list($width,$height)=getimagesize($uploadedfile);

						$newwidth		=	60;
						$newheight		=	($height/$width)*$newwidth;
						$tmp			=	imagecreatetruecolor($newwidth,$newheight);

						$newwidth1		=	25;
						$newheight1		=	($height/$width)*$newwidth1;
						$tmp1			=	imagecreatetruecolor($newwidth1,$newheight1);

						imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

						imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);

						$filename 		= 	"uploads/". $_FILES["image".$i]['name'];
						$filename1 		= 	"uploads/small/". $_FILES["image".$i]['name'];
						$arr 			= 	array('profile_pic' => $_FILES["image".$i]["name"]);
						if($fmly_id)
							{
								$result = $this->user_model->update('survey_family',$arr,array('family_id'=>$fmly_id));
							}

						imagejpeg($tmp,$filename,100);
						imagejpeg($tmp1,$filename1,100);

						imagedestroy($src);
						imagedestroy($tmp);
						imagedestroy($tmp1);
					}
				}
			}
			}}
		}
	function getExtension($str) 
		{
		 $i 	= strrpos($str,".");
		 if (!$i) { return ""; } 
		 $l 	= strlen($str) - $i;
		 $ext 	= substr($str,$i+1,$l);
		 return $ext;
		}
	 public function upload_file($fmly_id,$i)
        {
        	  $this->load->model('user_model');    
        	//$test_count=$this->user_model->test_count();
//print_r($_FILES);die;
    	   	$target_dir = "uploads/";
    	   	if(isset($_FILES["image".$i]))
    	   	{
    	   		if(!is_array($_FILES["image".$i]["name"]))
    	   		{
					$target_file = $target_dir . basename($_FILES["image".$i]["name"]);
					$uploadOk = 1;
					$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
					// Check if image file is a actual image or fake image
					if(isset($_POST["submit"])) 
					{
					    $check = getimagesize($_FILES["image".$i]["tmp_name"]);
					    if($check !== false) {
					        //echo "File is an image - " . $check["mime"] . ".";
					        $uploadOk = 1;
					    } else {
					       //echo "File is not an image.";
					        $uploadOk = 0;
					    }
					}
					// Check if file already exists
					if (file_exists($target_file)) {
					    //echo "Sorry, file already exists.";
					    $uploadOk = 0;
					}
					// Check file size
					if ($_FILES["image".$i]["size"] > 500000) {
					    //echo "Sorry, your file is too large.";
					    $uploadOk = 0;
					}
					// Allow certain file formats
					if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
					&& $imageFileType != "gif" ) {
					    //echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
					    $uploadOk = 0;
					}
					// Check if $uploadOk is set to 0 by an error
					if ($uploadOk == 0) {
					   // echo "Sorry, your file was not uploaded.";
					// if everything is ok, try to upload file
					} 
					else 
						{
						    if (move_uploaded_file($_FILES["image".$i]["tmp_name"], $target_file)) 
							    {
							        //echo "The file ". basename( $_FILES["image".$i]["name"]). " has been uploaded.";
							        $arr = array('profile_pic' => $_FILES["image".$i]["name"]);
							        //$result = $this->user_model->update('survey_family2',$arr,array('family_id'=>$fmly_id));
				                    if($fmly_id)
				                        {
				                            $result = $this->user_model->update('survey_family',$arr,array('family_id'=>$fmly_id));
				                        }
							    } 
						    else 
							    {
							        //echo "Sorry, there was an error uploading your file.";
							    }
						}
				} 
			}
        }


public function insert_agent()
		{
$data['name']			=	$this->input->post('name');
			$data['username']		=	$this->input->post('username');
			$data['email']			=	$this->input->post('email');
			$data['password']		=	$this->input->post('password');
			//$data['confirm_password']=	$this->input->post('confirm_password');
			$data['district_id']	=	$this->input->post('district_id');
			$data['muncipality']	=	$this->input->post('muncipality');
			$data['block_id']		=	$this->input->post('block_id');
			$data['panchayath_id']	=	$this->input->post('panchayath_id');
			$data['corporation']	=	$this->input->post('corporation');
			$data['place_category']	=	$this->input->post('place_category');
$data['cds']			=	$this->input->post('cds');
			$data['ads']			=	$this->input->post('ads');
			$data['constitution']	=	$this->input->post('constitution');
			$e=0;
			
			if(!empty($data['email']))
				{
					if (!filter_var(trim($data['email']), FILTER_VALIDATE_EMAIL) )
						{
						   $data['email'] ='';
						   $e =1;//invalid email
						}
					else
						{ 
						$data['email'] =$data['email'];
						$e =2;//valid email
						}
				}
else{$data['email'] ='';$e =2;}
if(empty($data['cds']) || $data['cds'] == '')		
				{
					$e =3;//cds not found
				}
			if(empty($data['ads']) || $data['ads'] == '')		
				{
					$e =4;//ads not found
				}
			if(empty($data['constitution']) || $data['constitution'] == '')		
				{
					$e =5;//constitution not found
				}
			$data['place_category'] =   $this->input->post('place_category');
			$data['role'] 			=   2;//agent
			if($e == 2)
				{
					$returnFlag     =   $this->user_model->insert_users($data);//checking username and inserting
					if($returnFlag != 'EXISTS')
						{
							$result['status']	=	1;//success
							$result['msg']		=	'success';//success
							$result['userid']	=	$returnFlag;//user id							
						}
					else
						{
							$result['status']	=2;//error
							$result['msg']		=	'user exists';//EXISTS
							$result['userid']	=	'';
						}
				}
			if($e == 1)
				{
					$result['status']	=	3;//error
					$result['msg']		=	'invalid email';//error
					$result['userid']	=	'';
				}
			if($e == 3)
				{
					$result['status']	=	4;//error
					$result['msg']		=	'cds not found';//error
					$result['userid']	=	'';
				}
			if($e == 4)
				{
					$result['status']	=	5;//error
					$result['msg']		=	'ads not found';//error
					$result['userid']	=	'';
				}
			if($e == 5)
				{
					$result['status']	=	6;//error
					$result['msg']		=	'constitution not found';//error
					$result['userid']	=	'';
				}
			echo json_encode($result);die;
			
		
		}

	public function upload_file_test()
        {
        	$target_dir = "uploads/";
    	   	if(isset($_FILES["image"]))
    	   	{
    	   		if(!is_array($_FILES["image"]["name"]))
    	   		{
					$target_file = $target_dir . basename($_FILES["image"]["name"]);
					$uploadOk = 1;
					$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
					// Check if image file is a actual image or fake image
					if(isset($_POST["submit"])) 
					{
					    $check = getimagesize($_FILES["image"]["tmp_name"]);
					    if($check !== false) {
					        echo "File is an image - " . $check["mime"] . ".";
					        $uploadOk = 1;
					    } else {
					       echo "File is not an image.";
					        $uploadOk = 0;
					    }
					}
					// Check if file already exists
					if (file_exists($target_file)) {
					    echo "Sorry, file already exists.";
					    $uploadOk = 0;
					}
					// Check file size
					if ($_FILES["image"]["size"] > 500000) {
					    echo "Sorry, your file is too large.";
					    $uploadOk = 0;
					}
					// Allow certain file formats
					if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
					&& $imageFileType != "gif" ) {
					    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
					    $uploadOk = 0;
					}
					// Check if $uploadOk is set to 0 by an error
					if ($uploadOk == 0) {
					    echo "Sorry, your file was not uploaded.";
					} 
					else 
						{
						    if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) 
							    {
							        echo "Success==>".$_FILES["image"]["name"];
							        
							    } 
						    else 
							    {
							        echo "Sorry, there was an error uploading your file.";
							    }
						}
				} 
			}
        }
	public function change_password()
		{
			$password 			= 	$this->input->post('password');
			$new_password 		= 	$this->input->post('new_password');
			$confirm_password 	= 	$this->input->post('confirm_password');
			$userId 			= 	$this->input->post('userId');
			$app_version 		= 	$this->input->post('app_version');
			if($new_password != $confirm_password)
				{
					$result['status']	=	3;
					$result['msg']		=	'Password mismatch';
				}
			$data['userId'] 	= 	$userId;
			$data['password'] 	= 	hash('SHA512',$password,false);	
			$new_password 		= 	hash('SHA512',$new_password,false);	
			$ud 				= 	$this->user_model->is_user($data);
			if(!empty($ud))
				{
					$arr 				= 	array('password' => $new_password,'app_version'=>$app_version);
					$res 				= 	$this->user_model->update('login',$arr,array('id'=>$userId));
					$result['status']	=	1;
					$result['msg']		=	'Success';
				}
			else
				{
					$result['status']	=	2;
					$result['msg']		=	'Password Error';
				}	
			echo json_encode($result);die;	
		}
}