<?php namespace App\Http\Controllers;

use App\Categories;
use App\Profile;
use App\User;
use App\ProfileCategories;
use App\CategoryIndustry;
use App\CategoryRoles;
use Illuminate\Http\Request;
use Validator;
use Auth;
use Session;
use Config;
use DB;
use App\Experience;
use App\Education;
use App\Location;
use App\Industry;
use App\Roles;
use App\CategoryOthers;
use App\ProfileLinks;
use App\Funding;
use App\Currency;
use App\CurrencyUnits;
use App\GrowthPerYear;
use App\FundingAssets;
use App\BusinessYears;
use URL;
use Input;
use App\Countries;
use App\Awards;
use App\Http\Controllers\FileuploaderController;
use App\Common\AjaxUploadHandler;
use Storage;
// use Image;
use ResizeImage;
use App\FundingAssetsData;
use App\FinancialServices;
use App\ProfileViews;
use App\History;
use App\Users_likes;

class ProfileController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Profile Controller
	|--------------------------------------------------------------------------
	|
	|
	*/

	/**
	 * Profile controller instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		$this->middleware('auth');
                
		
	}

	/**
	 * Show the application Step1 to the user.
	 *
	 * @return Response
	 */
	public function index()
	{
		$profiles = Profile::where("user_id",'=',Auth::user()->id)->get();
		return view('profile.index')->with(['profiles'=>$profiles]);
	}

	public function AuthProfile(Request $request)
	{
		$input = $request->all();
		$check = Profile::where('id','=',$input['auth_profile'])->where('user_id','=',Auth::user()->id)->get();
		if($check[0]->id):
			Session::forget('auth_selected_profile');
			Session::forget('auth_selected_profile_type');	
			Session::put('auth_selected_profile',$check[0]->id);
			Session::put('auth_selected_profile_type',$check[0]->profile_type);	
		endif;
		return redirect(URL::previous());
	}

	public function step1(Request $request)
	{
		if(Auth::user()->selected_profile && Auth::user()->profile_completed>=Config::get('constants.'.Auth::user()->selected_profile.'_LIMIT'))
			return redirect('profiles');

		$validation_errors='';
		$input = $request->all();
                //print_r($input); exit;
		if($request->input('profile_save_type'))
		{
			$validation = Validator::make($input, [
				//'indv[]'       => 'required',
			]);
			
			if($validation->fails()):
				$validation_errors = $validation->errors()->all() ;  
			else :

				if($request->input('indv')):
					$category_type = 'T';	
					$category_data = $request->input('indv');
				else:
					$category_type = 'O';	
					$category_data = $request->input('org');
				endif;
					$cmp = '';	
				if($request->input('profile_save_type')=='finish'):
					$data['name'] = Auth::user()->name;
					$data['user_id'] = Auth::user()->id;
					$data['city'] = Auth::user()->city;
					$data['profile_type'] = $category_type;
                                        
                                        if(isset($input['org'])) {
                                        if(in_array(252,$input['org'])){
                                            $cmp = "Finance";
                                            $funding = 2;
                                        }
                                        else {
                                            $cmp = "Business";
                                            $funding = 1;
                                        }
                                        }
                                        else
                                        {
                                            $cmp = '';
                                            $funding = 0;
                                        }
                                        
                                        //print_r($data); 
					$result = Profile::create($data);
                                        $update = Profile::find($result->id);
                                        $update->status_business = $cmp;
                                        $update->funding = $funding;
                                        $update->update();
                                         
					foreach($category_data as $req)	
					{
						$req_category_data['profile_id'] = $result->id;	
						$req_category_data['category_id'] = $req;
						$insert_req_category = ProfileCategories::create($req_category_data);
					}	
						/* update profile_completed count*/
							$user = User::find(Auth::user()->id);
							if($user->profile_completed==0)
							$user->selected_profile = $category_type;
							$user->profile_completed = 	$user->profile_completed+1;
							$user->save();
						/* End update profile_completed count*/
					 return redirect('profiles/');
				else:
					Session::put('cat_data',$category_data);
					Session::put('cat_type',$category_type);
				 return redirect('profile/step2');
				endif; 	
			endif;
		}
                
		/*$individual = Categories::where('type','=','T')->where('ref_cat_id','=','0')->get();
		$organization = Categories::where('type','=','O')->where('ref_cat_id','=','0')->get();*/
		$individual = $organization ='';
		$user_selected_profile = Auth::user()->selected_profile;

		if(!$user_selected_profile || $user_selected_profile=='T')
		$individual = Categories::getListofCategories();

		if(!$user_selected_profile || $user_selected_profile=='O')
		$organization = Categories::getListofCategories('O');

		return view('profile.step1')->with(['validation_errors'=>$validation_errors,'individual'=>$individual,'organization'=>$organization]);
	}

	public function step2(Request $request)
	{  
		$req_parent_data = Session::get('cat_data');
		if(!$req_parent_data)
			return redirect('profile/step1');

		$parent_data = Categories::getListofCategoriesLikeArray();
		$child_data = Categories::getListofCategoriesLikeArray(true);
		$industry_data = Industry::getList();
		$roles_data = Roles::getList();

		$input = $request->all();
                 //print_r($input); exit;
		if($request->input('profile_save_type'))
		{
			$data['name'] = Auth::user()->name;
			$data['user_id'] = Auth::user()->id;
			$data['city'] = Auth::user()->city;
			$data['profile_type'] = Session::get('cat_type');
                        $cmp = '';
                        
                       if($data['profile_type']=='O') {
                            if(in_array(252,$req_parent_data)){
                                            $cmp = "Finance";
                                            $funding = 2;
                                        }
                                        else {
                                            $cmp = "Business";
                                            $funding = 1;
                                        }
                       }
                       else
                       {
                           $cmp = "";
                           $funding = 0;
                       }
                                        
                                        //print_r($data); 
					$result = Profile::create($data);
                                        $update = Profile::find($result->id);
                                        $update->status_business = $cmp;
                                        $update->funding = $funding;
                                        $update->update();
			//$result = Profile::create($data);	

			$this->save_update_profileCategories($req_parent_data,$input,$result,'Save');		
			/* update profile_completed count*/
				$user = User::find(Auth::user()->id);
				if($user->profile_completed==0)
				$user->selected_profile = Session::get('cat_type');
				$user->profile_completed = 	$user->profile_completed+1;
				$user->save();
			/* End update profile_completed count*/
			Session::forget('cat_data');
			Session::forget('cat_type');

			return redirect('profiles/');
		}
                
		return view('profile.step2')->with(['req_parent_data'=>$req_parent_data,'parent_data'=>$parent_data,'child_data'=>$child_data,'industry_data'=>$industry_data,'roles_data'=>$roles_data]);
	}

	public function step3(Request $request)
	{
		
		$profile_id= Session::get('profile_id');
		$input = $request->all();
                 print_r($input); exit;
		if($request->input('profile_save_type'))
		{
			$user = Profile::find($input['profile_id']);

			//$save_array = $request->only('site_use', 'emp_contact', 'video', 'photo', 'resumes_uploading');
			if(isset($input['site_use']))
			$user->site_use=$input['site_use'];
			if(isset($input['emp_contact']))
			$user->emp_contact=$input['emp_contact'];
			if(isset($input['video']))
			$user->video=$input['video'];
			if(isset($input['photo']))
			$user->photo=$input['photo'];
			if(isset($input['resumes_uploading']))
			$user->resumes_uploading=$input['resumes_uploading'];
		/*	echo "<pre>";
			print_r($user);
			print_r($input);
			exit;*/
			$user->save();
			return redirect('profile/talent');
		}	
		if(!$profile_id)
			return redirect('profile/step2');
		return view('profile.step3')->with(['profile_id'=>$profile_id]);
	}

	public function editstep1($profile_id,Request $request)
	{

		if(is_numeric($profile_id)):
			$profile_det = Profile::where('id','=',$profile_id)->where("user_id",'=',Auth::user()->id)->get();
			if(isset($profile_det[0])):

				/* step1 request data */	
				$req_parent_data1 = Session::get('cat_data');

				$input = $request->all();
				if($request->input('profile_save_type'))
				{
					$validation = Validator::make($input, [
						//'indv[]'       => 'required',
					]);
					
					if($validation->fails()):
						$validation_errors = $validation->errors()->all() ;  
					else :

						if($request->input('indv')):
							$category_type = 'T';	
							$category_data = $request->input('indv');
						else:
							$category_type = 'O';	
							$category_data = $request->input('org');
						endif;
								
							Session::put('cat_data',$category_data);
							Session::put('cat_type',$category_type);
						 return redirect('profile/step2/'.$profile_id);
					endif;
				}	

				$selected_categories = ProfileCategories::getCategoriesByProfileID($profile_det[0]->id,true);
				$req_parent_data2 = $selected_categories['parent'];

				if($req_parent_data1):
//					$req_parent_data = array_unique(array_merge($req_parent_data1,$req_parent_data2));
					$req_parent_data = $req_parent_data1;
				else:
					$req_parent_data = $req_parent_data2;
				endif;
	
				$validation_errors ='';
				$individual = Categories::getListofCategories();
				$organization = Categories::getListofCategories('O');

				return view('profile.edit_step1')->with(['validation_errors'=>$validation_errors,'individual'=>$individual,'organization'=>$organization,'profile_det'=>$profile_det[0],'req_parent_data'=>$req_parent_data]);
			else:
				return redirect('myaccount')->with('error_msg',"Invalid Request");
			endif;
		else:
			return redirect('myaccount')->with('error_msg',"Invalid Request");
		endif;
	}

	public function editstep2($profile_id,Request $request)
	{

		if(is_numeric($profile_id)):
			$profile_det = Profile::where('id','=',$profile_id)->where("user_id",'=',Auth::user()->id)->get();
			if(isset($profile_det[0])):

				/* step1 request data */	
				$req_parent_data1 = Session::get('cat_data');


				$selected_categories = ProfileCategories::getCategoriesByProfileID($profile_det[0]->id,true);
				/* Previous user slected categories*/
				$req_parent_data2 = $selected_categories['parent'];

				if($req_parent_data1):
//					$req_parent_data = array_unique(array_merge($req_parent_data1,$req_parent_data2));
					$req_parent_data = $req_parent_data1;
				else:
					$req_parent_data = $req_parent_data2;
				endif;

				$input = $request->all();
				if($request->input('profile_save_type'))
				{
					$req_parent_data = $input['req_parent_data'];

					$this->save_update_profileCategories($req_parent_data,$input,$profile_det[0],'Update');		
					Session::forget('cat_data');
					Session::forget('cat_type');	

					return redirect('profiles/'.$profile_id);
				}

				$req_child_data = $selected_categories['child'];
				$req_industry_data = CategoryIndustry::getIndustryByProfileID($profile_det[0]->id);
				$req_roles_data = CategoryRoles::getRolesByProfileID($profile_det[0]->id);


				$parent_data = Categories::getListofCategoriesLikeArray();
				$child_data = Categories::getListofCategoriesLikeArray(true);
				$industry_data = Industry::getList();
				$roles_data = Roles::getList();
				
				/*echo "<pre>";
				print_r($req_roles_data);
				print_r($roles_data);
				exit;*/

				return view('profile.edit_step2')->with(['profile_id'=>$profile_id,'req_parent_data'=>$req_parent_data,'req_child_data'=>$req_child_data,'req_industry_data'=>$req_industry_data,'req_roles_data'=>$req_roles_data,'parent_data'=>$parent_data,'child_data'=>$child_data,'industry_data'=>$industry_data,'roles_data'=>$roles_data]);
			else:
				return redirect('myaccount')->with('error_msg',"Invalid Request");
			endif;
		else:
			return redirect('myaccount')->with('error_msg',"Invalid Request");
		endif;
	}

	protected function save_update_profileCategories($req_parent_data,$input,$result,$type='Save')
	{
		if($type=='Update')	
		{
			$categories_delete = ProfileCategories::where('profile_id','=',$result->id)->delete();
			$category_industry_delete = CategoryIndustry::where('profile_id','=',$result->id)->delete();
			$category_role_delete = CategoryRoles::where('profile_id','=',$result->id)->delete();
			$category_other_delete = CategoryOthers::where('profile_id','=',$result->id)->delete();
		}

			foreach($req_parent_data as $req)	
			{
				$req_category_data['profile_id'] = $result->id;	
				$req_category_data['category_id'] = $req;
				$insert_req_category = ProfileCategories::create($req_category_data);
			
				if(isset($input['sub_cat_'.$req])):
					foreach($input['sub_cat_'.$req] as $cat):
						if($cat):
							$category_data = array();
							$category_data['profile_id'] = $result->id;	
							$category_data['category_id'] = $cat;
							$insert_category = ProfileCategories::create($category_data);
						endif;			
					endforeach;	

					//print_r($input['sub_cat_'.$req]);	
				endif;

				if(isset($input['sub_cat_'.$req])):
					foreach ($input['sub_cat_'.$req] as $ind) {
						if($ind):	
							$ind_data = array();
							$ind_data['profile_id'] = $result->id;
							$ind_data['cat_id'] = $req;
							$ind_data['name'] = $ind;
							$ind_data['other_type'] = "S";
							$insert_industry = CategoryOthers::create($ind_data);		
						endif;
					}
				endif;

				if(isset($input['sub_role_'.$req])):
					foreach ($input['sub_role_'.$req] as $role) {
						if($role):	
							$roles_data = array();							
							$roles_data['profile_id'] = $result->id;
							$roles_data['cat_id'] = $req;
							$roles_data['name'] = $role;							
							$roles_data['other_type'] = "R";
							$insert_role = CategoryOthers::create($roles_data);		
						endif;
					//print_r($input['sub_role_'.$req]);
					}
				endif;

				if(isset($input['sub_industry_'.$req])):
					foreach ($input['sub_industry_'.$req] as $oind) {
						if($oind):	
							$oind_data = array();
							$oind_data['profile_id'] = $result->id;
							$oind_data['cat_id'] = $req;
							$oind_data['name'] = $oind;
							$roles_data['other_type'] = "I";
							$insert_other_industry = CategoryOthers::create($oind_data);		
						endif;
					}
				endif;
			}
	}
	/*Talent Profile Detials view, Save, Edit And Delete*/
	public function talent($id,Request $request)
	{
		if(is_numeric($id)):
//			$profile_det = Profile::where('id','=',$id)->where("user_id",'=',Auth::user()->id)->get();
			$profile_det = Profile::where('id','=',$id)->get();
			$countries = Countries::orderBy('name')->get();
			if(isset($profile_det[0])):

				Session::forget('cat_data');
				Session::forget('cat_type');	

				if($profile_det[0]->user_id==Auth::user()->id):

					$profile_det[0]->private = true;
					
					$input = $request->all();
					if($input):

						/* get user profil details */
						$profile_det = Profile::find($id);
						/*echo "<pre>";
						print_r($profile_det);
						exit;*/
						if($input['save_type'] =='skill'):	
							$profile_det->skills = $input['skills'];
							$profile_det->save();
						elseif($input['save_type'] == 'name'):
							$profile_det->name = $input['name'];
							$profile_det->save();
						elseif($input['save_type'] == 'city'):
							$profile_det->city = $input['city'];
							$profile_det->save();
						elseif($input['save_type'] == 'url'):
							$profile_det->url = $input['url'];
							$profile_det->save();
						elseif($input['save_type'] == 'whyus'):
							$profile_det->why_us = $input['whyus'];
							$profile_det->save();
						elseif($input['save_type'] == 'aboutus'):
							$profile_det->about_us = $input['aboutus'];
							$profile_det->save();
						elseif($input['save_type'] == 'contact_info'):
							$profile_det->contact_info = $input['contact_info'];
							$profile_det->save();
						elseif($input['save_type'] == 'products_services'):
							$profile_det->products_services = $input['products_services'];
							$profile_det->save();
						elseif($input['save_type'] == 'influence'):
							$profile_det->influence = $input['influence'];
							$profile_det->save();
						elseif($input['save_type'] == 'interests'):
							$profile_det->interests = $input['interests'];
							$profile_det->save();
						elseif($input['save_type'] == 'experience'):
                                                   // print_r($input); exit;
                                                    $data = array();
								$data['profile_id']	= $id;
								$data['location']=$input['exp_location'];
								$data['company_name'] = $input['exp_company'];                                                               
								//$data['partners'] = $input['exp_partners'];
                                                                $r = str_replace('\r\n',' ',json_encode($input['exp_description']));                                                                                                            
                                                                $data['description']= trim(str_replace('"',' ',$r));								

								//if($input['exp_from_mm'] && $input['exp_from_yy'])
								//$data['from_date']=$input['exp_from_mm'].'-'.$input['exp_from_yy'];
								$data['from_date']=$input['exp_from_yy'].'-'.$input['exp_from_mm'].'-01';		
								//if($input['exp_to_mm'] && $input['exp_to_yy'])
								//	$data['to_date']=$input['exp_to_mm'].'-'.$input['exp_to_yy'];
								if(isset($input['exp_tilldate']) && $input['exp_tilldate']==1):
                                                                $data['to_date']="".'-'."".'-01';
                                                                else:
                                                                $data['to_date']=$input['exp_to_yy'].'-'.$input['exp_to_mm'].'-01';
                                                                endif;
                                                               // $data['to_date']=$input['exp_to_yy'].'-'.$input['exp_to_mm'].'-01';
									/*echo "<pre>";
									print_r($data);
									exit;*/
							$insert_experience = Experience::create($data);					
						elseif($input['save_type'] == 'education'):
							
                                                    //print_r($input); exit;
                                                    $data = array();
							  $data['profile_id'] = $id;
                                                          $data['partners'] = $input['edu_partners'];
							  $data['location']=$input['edu_location'];
							  $data['company_name'] = $input['edu_company'];
                                                          $r = str_replace('\r\n',' ',json_encode($input['edu_description']));                                                                                                            
                                                          $data['description']= trim(str_replace('"',' ',$r));
							  $data['partners']=$input['edu_partners'];

							  //if($input['edu_from_mm'] && $input['edu_from_yy'])
					
                                                          
                                                               $data['from_date']=$input['edu_from_yy'].'-'.$input['edu_from_mm'].'-01';		
								//if($input['exp_to_mm'] && $input['exp_to_yy'])
								//	$data['to_date']=$input['exp_to_mm'].'-'.$input['exp_to_yy'];
								if(isset($input['edu_tilldate']) && $input['edu_tilldate']==1):
                                                                $data['to_date']="".'-'."".'-01';
                                                                else:
                                                                $data['to_date']=$input['edu_to_yy'].'-'.$input['edu_to_mm'].'-01';
                                                                endif;
							   // $data['to_date']=$input['edu_to_mm'].'-'.$input['edu_to_yy'];

							$insert_education = Education::create($data);  
						         elseif($input['save_type'] == 'location'):
							  $data['profile_id'] = $id;
							  $data['name']=$input['loc_name'];
							  $data['number'] = $input['loc_number'];
							  $data['street']=$input['loc_street'];
							  $data['city']=$input['loc_city'];
							  $data['country']=$input['loc_country'];
                                                         $r = str_replace('\r\n',' ',json_encode($input['loc_description']));
                                                        //echo trim(str_replace('"',' ',$r)); exit;                                                        
							  $data['description']= trim(str_replace('"',' ',$r));
                                                                  //preg_replace( "/\r|\n/", "", $input['loc_description']);
							  $data['state'] = $input['loc_state'];
							  $data['zip'] = $input['loc_zip'];
							$insert_location = Location::create($data);  
						elseif($input['save_type'] == 'awards'):
							$data = array();
							  $data['profile_id'] = $id;
							  $data['location']=$input['aw_location'];
							  $data['company_name'] = $input['aw_company'];
                                                          $r = str_replace('\r\n',' ',json_encode($input['aw_description']));                                                                                                            
                                                          $data['description']= trim(str_replace('"',' ',$r));
							 

							  $data['award_date']=$input['aw_from_mm'].'-'.$input['aw_from_yy'];
							  /*echo "<pre>";	
							  print_r($data);
							  exit;*/
							  $insert_education = Awards::create($data);  
						elseif($input['save_type'] == 'social_links'):

							$save_links = ProfileLinks::save_update($input,$id);
						elseif($input['save_type'] == 'profile_image' && $input['image_name']):	
							$profile_det->profile_image = $input['image_name'];
							$profile_det->save();
							ResizeImage::imageCrop($input['image_name'],$input['x'],$input['y'],$input['w'],$input['h']);
							ResizeImage::resizeimagefixed($input['image_name'],'uploads/profile_images',200,200,1);
							/*echo "connect";
							exit;*/
						endif;
						return redirect('profiles/'.$id);								

					endif;
				else:
					$profile_det[0]->private = false;

					/*--------------------------------------------------------
					| Increase view count if viewed for first time
					*/
					$profile_viewer = Profile::where('user_id','=',Auth::user()->id)->get();

					$data_views = array(
						'visitor_profile_id' 	=> $profile_viewer[0]->id,
						'visited_profile_id' 	=> $id,
						'ip_address' 			=> $request->ip()
					);
					ProfileViews::create($data_views);
					// *** END				
				endif;	

				/*echo "<pre>";
				print_r($profile_det[0]);
				exit;*/
				
				/* Categories by profile ID */
				$profile_categories = $profile_experience = $profile_education = $profile_location = $profile_links ='';

				/*echo strpos($profile_det[0]->private_permission,'B,');
				exit;*/

				$profile_categories = ProfileCategories::getCategoriesByProfileID($profile_det[0]->id); 
				$profile_experience = Experience::getExperienceByProfileID($profile_det[0]->id);
                                //print_r($profile_experience); exit;
				$profile_education =  Education::getExperienceByProfileID($profile_det[0]->id);
				$profile_location  =  Location::getExperienceByProfileID($profile_det[0]->id);
				$profile_links = ProfileLinks::getlistByProfile($profile_det[0]->id);
				$profile_awards = Awards::getAwardsByProfileID($profile_det[0]->id);
 				
				$business_years = BusinessYears::getAllYears();		
				$currency_all = Currency::getAllCurrency();		
				$currency_units = CurrencyUnits::getAllUnits();		
				$growth_per_year = GrowthPerYear::getAllPercents();
				$industries = Industry::getListAll(); 				

 				$arr_withs = array(
					'prof_det'=>$profile_det[0],
					'countries'=>$countries,
					'profile_links'=>$profile_links,
					'categories'=>$profile_categories,
					'profile_exp'=>$profile_experience,
					'profile_edu'=>$profile_education,
					'profile_loc'=>$profile_location,
					'profile_aw'=>$profile_awards,
					'error_msg'=>Session::get('error_msg'),
					'succ_msg'=>Session::get('succ_msg')
 				);

 				if($profile_det[0]->profile_type=='O')
 				{
 					$financial_services = FinancialServices::getAll();
					$funding_data = '';$funding_assets_data = ''; $funding_assets_video = '';
					$fb_data = ''; $fb_assets_data = ''; $fb_assets_video = '';
					
						$funding_year = User::find(Auth::user()->id);
                                                $funding_data = Funding::getByProfile($id);
                                                
						if($funding_data):
							$funding_assets_data = FundingAssets::get_by_funding_id($funding_data->id);
							$funding_assets_video = FundingAssets::getVideos_by_funding_id($funding_data->id);
						endif;

						$fb_data = Funding::getByProfile($id,'B');
						/*echo '<pre>';
						print_r($fb_data);
						exit;*/
						if($fb_data):
							$fb_assets_data = FundingAssets::get_by_funding_id($fb_data->id);
							$fb_assets_video = FundingAssets::getVideos_by_funding_id($fb_data->id);
						endif;

					$action_url = action('ProfileController@funding_save', array($id, $profile_det[0]->profile_type));

					// add more withs
					$arr_withs['business_years']		= $business_years;
					$arr_withs['currency_all'] 			= $currency_all;
					$arr_withs['currency_units'] 		= $currency_units;
					$arr_withs['growth_per_year'] 		= $growth_per_year; 
					$arr_withs['industries'] 			= $industries;
					$arr_withs['action_url']			= $action_url;
					$arr_withs['funding_data']			= $funding_data;
                                        $arr_withs['funding_year']                      =$funding_year;
					$arr_withs['funding_assets_data'] 	= $funding_assets_data;
					$arr_withs['funding_assets_video'] 	= $funding_assets_video;
					$arr_withs['fb_data']			= $fb_data;
					$arr_withs['fb_assets_data'] 	= $fb_assets_data;
					$arr_withs['fb_assets_video'] 	= $fb_assets_video;
					$arr_withs['financial_services'] = $financial_services;
 					$view = 'profile.organization';

 				} else {

 					$view = 'profile.talent';
 				} 					
                               
				//return view($view)->with(['prof_det'=>$profile_det[0],'countries'=>$countries,'profile_links'=>$profile_links,'categories'=>$profile_categories,'profile_exp'=>$profile_experience,'profile_edu'=>$profile_education,'profile_loc'=>$profile_location,'profile_aw'=>$profile_awards,'error_msg'=>Session::get('error_msg'),'succ_msg'=>Session::get('succ_msg')]);
				$video = History::Addview(Session::get('auth_selected_profile'),$id,'P');
                                 if($video): 
				       return view($view)->with($arr_withs);
                                 endif;
			else:
				return redirect('myaccount')->with('error_msg',"Invalid Request");
			endif;
		else:
			return redirect('myaccount')->with('error_msg',"Invalid Request");
		endif;
	}

	public function talent_about_edit($profile_id,$type,$type_id,Request $request)
	{
		//$type_array = array ('exp'=>'Experience','edu'=>'Education','loc'=>'Location');	
		if(is_numeric($profile_id)):
			$profile_det = Profile::where('id','=',$profile_id)->where("user_id",'=',Auth::user()->id)->get();
			if(isset($profile_det[0])):
				$input = $request->all();
				if($type=='loc'):
					$update = Location::find($type_id);
					  $update->name=$input['loc_name'];
					  $update->number = $input['loc_number'];
					  $update->street=$input['loc_street'];
					  $update->city=$input['loc_city'];
					  $update->country=$input['loc_country'];
                                          $r = str_replace('\r\n',' ',json_encode($input['loc_description']));
                                          //echo trim(str_replace('"',' ',$r)); exit;
                                          $update->description=  trim(str_replace('"',' ',$r));
					  $update->state = $input['loc_state'];
					  $update->zip = $input['loc_zip'];
					$msg = " Selected Location updated successfully";
				elseif($type=='edu'):
					$update = Education::find($type_id);

						$update->location=$input['edu_location'];
						$update->company_name = $input['edu_company'];
                                                $r = str_replace('\r\n',' ',json_encode($input['edu_description']));                                          
                                                $update->description=  trim(str_replace('"',' ',$r));
						$update->partners=$input['edu_partners'];
						
                                                $update->from_date =$input['edu_from_yy'].'-'.$input['edu_from_mm'].'-01';
                                                if(isset($input['edu_tilldate']) && $input['edu_tilldate']==1):
                                                $update->to_date="".'-'."".'-01';
                                                else:
                                                $update->to_date=$input['edu_to_yy'].'-'.$input['edu_to_mm'].'-01';
                                                endif;

					$msg = " Selected Education updated successfully";
				elseif($type=='exp'):
					$update = Experience::find($type_id);
						$update->location=$input['exp_location'];
						$update->company_name = $input['exp_company'];
                                                 $r = str_replace('\r\n',' ',json_encode($input['exp_description']));                                          
                                                $update->description=  trim(str_replace('"',' ',$r));
						//$update->partners=$input['exp_partners'];
						/*$update->from_date =$input['exp_from_mm'].'-'.$input['exp_from_yy'];
						$update->to_date=$input['exp_to_mm'].'-'.$input['exp_to_yy'];*/
						$update->from_date =$input['exp_from_yy'].'-'.$input['exp_from_mm'].'-01';
                                                if(isset($input['exp_tilldate']) && $input['exp_tilldate']==1):
                                                $update->to_date="".'-'."".'-01';
                                                else:
                                                $update->to_date=$input['exp_to_yy'].'-'.$input['exp_to_mm'].'-01';
                                                endif;
						
					$msg = " Selected Experience updated successfully";
				elseif($type=='aw'):
					$update = Awards::find($type_id);
						$update->location=$input['aw_location'];
						$update->company_name = $input['aw_company'];
                                                $r = str_replace('\r\n',' ',json_encode($input['aw_description']));                                                                                                            
                                                $data['description']= trim(str_replace('"',' ',$r));
						//$update->description=$input['aw_description'];
						$update->award_date =$input['aw_from_mm'].'-'.$input['aw_from_yy'];
					$msg = " Selected Awards updated successfully";
				else:
					return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
				endif;	

				if($update->id):
					$update->save();	
					/*echo "<pre>";
				print_r($update);
				exit;*/
					//$delete->delete();
	 				return redirect('profiles/'.$profile_id)->with('succ_msg',$msg);					
				else:
	 				return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
				endif;		
			else:
 				return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
			endif;		
		else:
				return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
		endif;		
	}

	public function talent_about_delete($profile_id,$type,$type_id)
	{
		//$type_array = array ('exp'=>'Experience','edu'=>'Education','loc'=>'Location');	
		if(is_numeric($profile_id)):
			$profile_det = Profile::where('id','=',$profile_id)->where("user_id",'=',Auth::user()->id)->get();
			if(isset($profile_det[0])):
				if($type=='loc'):
					$delete = Location::find($type_id);
					$msg = " Selected Location deleted successfully";
				elseif($type=='edu'):
					$delete = Education::find($type_id);
					$msg = " Selected Education deleted successfully";
				elseif($type=='exp'):
					$delete = Experience::find($type_id);
					$msg = " Selected Experience deleted successfully";
				elseif($type=='aw'):
					$delete = Awards::find($type_id);
					$msg = " Selected Award deleted successfully";
				else:
					return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
				endif;	

				if($delete->id):
					$delete->delete();
	 				return redirect('profiles/'.$profile_id)->with('succ_msg',$msg);					
				else:
	 				return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
				endif;		
			else:
 				return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
			endif;		
		else:
				return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
		endif;		
	}

	/* End Talent Profile Save, Edit, Delete*/

	public function do_ajaxupload(Request $request)
	{

		$file = $request->file('profile_pic');
		$storage_path ='uploads/profile_images';
		$image_location = $storage_path."/".$file->getClientOriginalName();
		list($width, $height)= getimagesize($file);
		$file_type = strtolower($file->getClientOriginalExtension());
		$allow_type = array('png','gif','jpg','jpeg');
		if(!in_array($file_type,$allow_type)):
			echo json_encode(array("files"=>array('error'=>'Profile Image Allow PNG,JPEG,GIf types only')));
		elseif($width<200 || $height<200):
			echo json_encode(array("files"=>array('error'=>'The ideal pixel size for your photo is between 200 x 200')));
		else:	
			$file->move($storage_path,$file->getClientOriginalName());

			$w=200;
			$h=200;
			if ($height > $h){
				$scale = $h/$height;
				$uploaded = ResizeImage::resizeImage($image_location,$width,$height,$scale);
			} else {
				$scale = 1;
				$uploaded = ResizeImage::resizeImage($image_location,$w,$h,$scale);
			}
			//$image = Image::make(sprintf($storage_path.'/%s', $file->getClientOriginalName()))->resize(200, 200)->save();
			echo json_encode(array("files"=>array('error'=>'','name'=>$file->getClientOriginalName(),'path'=>$storage_path."/".$file->getClientOriginalName())));
		endif;
	}

	public function permission($profile_id,Request $request)
	{
		if(is_numeric($profile_id)):
			$profile_det = Profile::where('id','=',$profile_id)->where("user_id",'=',Auth::user()->id)->get();
			
			$input = $request->all();
			
			if(isset($profile_det[0]) && (isset($input['lock']) || isset($input['unlock']))):
				$sel_profile = Profile::find($profile_id);
				/* Permission Key Type*/

				$private_type = array(  'B'=>'Basic Information',
										'L'=>'location',
										'EXP'=>'Experience',
										'EDU'=>'Education',
										'S'=>'Skills',
										'In'=>'Influence',
										'Int'=>'Interests',
										'A'=>'About us',
										'W'=>'Why us',
										'Cont'=>'Contact information',
										'P'=>'Products / services',
										'AW'=>'Awards');

				/* End Permission Key Type*/
				foreach($input as $key=>$value)
				{
					if($key=='lock'):
						$sel_profile->private_permission=$sel_profile->private_permission.$value.",";
					elseif($key=='unlock'):
						$sel_profile->private_permission=str_replace($value.",",'',$sel_profile->private_permission);
					endif;

					$msg = $private_type[$value]." ".$key."ed Successfully"; // updated type like lock or unlock;
				}

				$sel_profile->save();

 				return redirect('profiles/'.$profile_id)->with('succ_msg',$msg);					

			else:
 				return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
			endif;		
		else:
				return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
		endif;		
	}


	/*-------------------------------------
	| Funding related methos
	*/	
	public function funding_save($profile_id, $type_id, Request $request, FileuploaderController $fileUploader)
	{
		/*echo "<pre>";
		print_r($request->all()); 
		exit;*/
		$prof_det = Profile::find($profile_id);
		$error_msg='';$msg='';$funding_type = 'R';
		if($request->input('sel_funding_type')==0):
		/*No Funding Save */
			//$prof_det->funding = '0';
			$prof_det->save();
			$msg = 'No funding Saved Successfully';
		/*End No funding Save*/	
		/*Raise funding save*/
		elseif($request->input('sel_funding_type')!=0):

			if($request->input('sel_funding_type') == 2)
				$funding_type = 'B';	
			
			$funding_data = Funding::getByProfile($profile_id,$funding_type);
			$opt = ($funding_data)?'update':'add';
			// pre-requisites
			$upload_path = 'uploads/funding_business/'; // single file upload path

			if($opt == 'update')
			{
				// the exact record & key ?
				$funding_business_id = $request->input('_fb_id');
				$fb_row = Funding::find($funding_business_id);

				// prepare update data
				   if (strpos($request->input('revenue_det'),',') == false) 
				    {
					$number=number_format($request->input('revenue_det')); 
					}
					else
					{
					$number=$request->input('revenue_det');	
					}
				 $fb_min_row = CurrencyUnits::find($request->input('min_investment_currency_units'));
				 $fb_max_row = CurrencyUnits::find($request->input('max_investment_currency_units'));
				 //echo $request->input('max_investment_amt');exit;
				 $min_invest_amt=$request->input('min_investment_amt')*$fb_min_row['amount'];
				 $max_invest_amt=$request->input('max_investment_amt')*$fb_max_row['amount'];
                 $tot_fun_val=$request->input('investment_amt')*$fb_min_row['amount'];
				$fund_data = array(
					'years_in_business' 			=> $request->input('years_in_business'),
					'assets_currency' 				=> $request->input('assets_currency'),
					'assets_currency_units' 		=> $request->input('assets_currency_units'),
					'nature_business' 				=> $request->input('nature_business'),
					'industry_focus' 				=> $request->input('industry_focus'),
					'emp_strength' 					=> $request->input('emp_strength'),
					'min_investment_currency' 		=> $request->input('min_investment_currency'),
					'min_investment_currency_units'	=> $request->input('min_investment_currency_units'),
					'investment_amt' 		        => $request->input('investment_amt'),
                    'max_investment_usd_val'        => $tot_fun_val,
                    'min_investment_amt'            => $request->input('min_investment_amt'),
                    'min_investment_fin_amt'        => $min_invest_amt,
                    'max_investment_amt'            => $request->input('max_investment_amt'),
                    'max_investment_fin_amt'        => $max_invest_amt,
					'revenue_det'	=> $number,
                    'growth' => $request->input('growth'),
				);


				if($request->input('sel_funding_type') == 2)
				{
					$fund_data['max_investment_currency'] = $request->input('max_investment_currency');
					$fund_data['max_investment_currency_units'] = $request->input('max_investment_currency_units');
					
					$fund_data['financial_service'] = $request->input('financial_service');

					if($request->input('industry_focus'))
					$fund_data['industry_focus'] = implode('||',$request->input('industry_focus'));

					if($request->input('portfolio'))
					$fund_data['portfolio'] = implode('||',$request->input('portfolio'));
				}	

				/*echo "<pre>";
				print_r($fund_data);
				exit;*/

				if ($request->hasFile('prev_profit_loss'))
				{
					// REMOVE me first o_O
					if($fb_row->prev_profit_loss && Storage::disk('funding')->exists($fb_row->prev_profit_loss))
					{
						Storage::disk('funding')->delete($fb_row->prev_profit_loss);
					}

					// Upload
					$org_name = $request->file('prev_profit_loss')->getClientOriginalName();
//					$new_name = 'prev_profit_loss_'.$funding_business_id.'.'.$request->file('prev_profit_loss')->getClientOriginalExtension();
					$new_name = 'fb_'.time().'.'.$request->file('prev_profit_loss')->getClientOriginalExtension();
					$fileUploader->move($request->file('prev_profit_loss'), $upload_path, $new_name);
					$fund_data['prev_profit_loss'] = $new_name;
					$fund_data['prev_profit_loss_name'] = $org_name;
				}
				else if($request->final_ppl)
				{
					$file = explode('|',$request->input('final_ppl'));	
					/*$org_name = $file[0];
					$extenstion = explode('.',$org_name);
					$new_name = 'prev_profit_loss_'.$funding_business_id.'.'.$extenstion[count($extenstion)-1];*/
					$org_name = $file[3];
					$new_name = $file[0];
					$fund_data['prev_profit_loss'] = $new_name;
					$fund_data['prev_profit_loss_name'] = $org_name;
				}


				if ($request->hasFile('next_profit_loss'))
				{
					// REMOVE me first o_O
					if($fb_row->next_profit_loss && Storage::disk('funding')->exists($fb_row->next_profit_loss))
					{
						Storage::disk('funding')->delete($fb_row->next_profit_loss);
					}

					// Upload
					$org_name = $request->file('next_profit_loss')->getClientOriginalName();
//					$new_name = 'next_profit_loss_'.$funding_business_id.'.'.$request->file('next_profit_loss')->getClientOriginalExtension();
					$new_name = 'fb_'.time().'.'.$request->file('next_profit_loss')->getClientOriginalExtension();
					$fileUploader->move($request->file('next_profit_loss'), $upload_path, $new_name);
					$fund_data['next_profit_loss'] = $new_name;
					$fund_data['next_profit_loss_name'] = $org_name;
				}
				else if($request->final_npl)
				{
					$file = explode('|',$request->input('final_npl'));	
					/*$org_name = $file[0];
					$extenstion = explode('.',$org_name);
					$new_name = 'next_profit_loss_'.$funding_business_id.'.'.$extenstion[count($extenstion)-1];*/
					$org_name = $file[3];
					$new_name = $file[0];
					$fund_data['next_profit_loss'] = $new_name;
					$fund_data['next_profit_loss_name'] = $org_name;
				}

				if ($request->hasFile('lship_team_file'))
				{
					// REMOVE me first o_O
					if($fb_row->lship_team_file && Storage::disk('funding')->exists($fb_row->lship_team_file))
					{
						Storage::disk('funding')->delete($fb_row->lship_team_file);
					}

					// Upload
					$org_name = $request->file('lship_team_file')->getClientOriginalName();
//					$new_name = 'lship_team_file_'.$funding_business_id.'.'.$request->file('lship_team_file')->getClientOriginalExtension();
					$new_name = 'fb_'.time().'.'.$request->file('lship_team_file')->getClientOriginalExtension();
					$fileUploader->move($request->file('lship_team_file'), $upload_path, $new_name);
					$fund_data['lship_team_file'] = $new_name;
					$fund_data['lship_team_file_name'] = $org_name;
				}						
				else if($request->final_ltf)
				{
					$file = explode('|',$request->input('final_ltf'));	
					/*$org_name = $file[0];
					$extenstion = explode('.',$org_name);
					$new_name = 'lship_team_file_'.$funding_business_id.'.'.$extenstion[count($extenstion)-1];*/
					$org_name = $file[3];
					$new_name = $file[0];
					$fund_data['lship_team_file'] = $new_name;
					$fund_data['lship_team_file_name'] = $org_name;
				}

				// run update
				Funding::where('id', '=', $funding_business_id)->update($fund_data);
                                User::where('id', '=', Auth::user()->id)->update(['years_in_business'=>$request->input('years_in_business')]);
			}
			else
			{

				/*--------------------------------
				| Save Funding Details
				*/		
				$fund_data = array();
				if (strpos($request->input('revenue_det'),',') == false) 
				    {
					$number=number_format($request->input('revenue_det')); 
					}
					else
					{
					$number=$request->input('revenue_det');	
					}

				 $fb_min_row = CurrencyUnits::find($request->input('min_investment_currency_units'));
				
                
				
                 
               

				$fund_data['investment_amt'] = $request->input('investment_amt');
				$fund_data['profile_id'] 					= $profile_id;
				$fund_data['years_in_business'] 			= $request->input('years_in_business');
				$fund_data['assets_currency'] 				= $request->input('assets_currency');
				$fund_data['assets_currency_units'] 		= $request->input('assets_currency_units');
				$fund_data['nature_business'] 				= $request->input('nature_business');
				$fund_data['industry_focus'] 				= $request->input('industry_focus');
				$fund_data['emp_strength'] 					= $request->input('emp_strength');
				$fund_data['min_investment_currency'] 		= $request->input('min_investment_currency');
				$fund_data['min_investment_currency_units'] = $request->input('min_investment_currency_units');
				if(empty($fund_data['investment_amt'])){
					$fund_data['investment_amt']=1;
					$tot_fun_val=$fund_data['investment_amt']*$fb_min_row['amount'];
			        }
			    else{
			    	$fund_data['investment_amt'] = $request->input('investment_amt');
			        $tot_fun_val=$request->input('investment_amt')*$fb_min_row['amount'];
			       }
                   $fund_data['max_investment_usd_val']       = $tot_fun_val;
				
				    $fund_data['revenue_det']	= $number;
                    $fund_data['growth'] = $request->input('growth');
				if($request->input('sel_funding_type') == 2)
				{  
					
				    $fb_max_row = CurrencyUnits::find($request->input('max_investment_currency_units'));
                    $max_invest_amt=$request->input('max_investment_amt')*$fb_max_row['amount'];

					$fund_data['max_investment_currency'] = $request->input('max_investment_currency');
					$fund_data['max_investment_currency_units'] = $request->input('max_investment_currency_units');
					$fund_data['financial_service'] = $request->input('financial_service');
					if(empty($fund_data['min_investment_amt'])){
						$fund_data['min_investment_amt']=1;
						$min_invest_amt=$fund_data['min_investment_amt']*$fb_min_row['amount'];
						}else{$fund_data['min_investment_amt'] = $request->input('min_investment_amt');
						$min_invest_amt=$request->input('min_investment_amt')*$fb_min_row['amount'];}
                    $fund_data['min_investment_fin_amt'] = $min_invest_amt;

                    if(empty($fund_data['max_investment_amt'])){
						$fund_data['max_investment_amt']=1;
						$max_invest_amt=$fund_data['max_investment_amt']*$fb_max_row['amount'];
						}else{$fund_data['max_investment_amt'] = $request->input('max_investment_amt');
						$max_invest_amt=$request->input('max_investment_amt')*$fb_max_row['amount'];}
                   
                    $fund_data['max_investment_fin_amt'] = $max_invest_amt;

					if($request->input('industry_focus'))
					$fund_data['industry_focus'] = implode('||',$request->input('industry_focus'));

					if($request->input('portfolio'))
					$fund_data['portfolio'] = implode('||',$request->input('portfolio'));

					$fund_data['funding_type'] = 'B';
				}	


				/*echo "<pre>";
				print_r($fund_data);
				exit;*/

				$create_funding = Funding::create($fund_data);		
				$funding_business_id = $create_funding->id;

				/*--------------------------------
				| Save Funding Assets (Single files)
				*/				
				$fb_row = Funding::find($funding_business_id);
				if ($request->hasFile('prev_profit_loss'))
				{
					$org_name = $request->file('prev_profit_loss')->getClientOriginalName();
//					$new_name = 'prev_profit_loss_'.$funding_business_id.'.'.$request->file('prev_profit_loss')->getClientOriginalExtension();
					$new_name = 'fb_'.time().'.'.$request->file('prev_profit_loss')->getClientOriginalExtension();
					$fileUploader->move($request->file('prev_profit_loss'), $upload_path, $new_name);
					$fb_row->prev_profit_loss = $new_name;
					$fb_row->prev_profit_loss_name = $org_name;
				}	
				else if($request->final_ppl)
				{
					$file = explode('|',$request->input('final_ppl'));	
					/*$org_name = $file[0];
					$extenstion = explode('.',$org_name);
					$new_name = 'prev_profit_loss_'.$funding_business_id.'.'.$extenstion[count($extenstion)-1];*/
					$org_name = $file[3];
					$new_name = $file[0];
					$fund_data['prev_profit_loss'] = $new_name;
					$fund_data['prev_profit_loss_name'] = $org_name;
				}

				if ($request->hasFile('next_profit_loss'))
				{
					$org_name = $request->file('next_profit_loss')->getClientOriginalName();
//					$new_name = 'next_profit_loss_'.$funding_business_id.'.'.$request->file('next_profit_loss')->getClientOriginalExtension();
					$new_name = 'fb_'.time().'.'.$request->file('next_profit_loss')->getClientOriginalExtension();
					$fileUploader->move($request->file('next_profit_loss'), $upload_path, $new_name);
					$fb_row->next_profit_loss = $new_name;
					$fb_row->next_profit_loss_name = $org_name;
				}		
				else if($request->final_npl)
				{
					$file = explode('|',$request->input('final_npl'));	
					/*$org_name = $file[0];
					$extenstion = explode('.',$org_name);
					$new_name = 'next_profit_loss_'.$funding_business_id.'.'.$extenstion[count($extenstion)-1];*/
					$org_name = $file[3];
					$new_name = $file[0];
					$fund_data['next_profit_loss'] = $new_name;
					$fund_data['next_profit_loss_name'] = $org_name;
				}

				if ($request->hasFile('lship_team_file'))
				{
					$org_name = $request->file('lship_team_file')->getClientOriginalName();
//					$new_name = 'lship_team_file_'.$funding_business_id.'.'.$request->file('lship_team_file')->getClientOriginalExtension();
					$new_name = 'fb_'.time().'.'.$request->file('lship_team_file')->getClientOriginalExtension();
					$fileUploader->move($request->file('lship_team_file'), $upload_path, $new_name);
					$fb_row->lship_team_file = $new_name;
					$fb_row->lship_team_file_name = $org_name;
				}						
				else if($request->final_ltf)
				{
					$file = explode('|',$request->input('final_ltf'));	
					/*$org_name = $file[0];
					$extenstion = explode('.',$org_name);
					$new_name = 'lship_team_file_'.$funding_business_id.'.'.$extenstion[count($extenstion)-1];*/
					$org_name = $file[3];
					$new_name = $file[0];
					$fund_data['lship_team_file'] = $new_name;
					$fund_data['lship_team_file_name'] = $org_name;
				}

				$fb_row->save();		
			}

			/*--------------------------------
			| Save Funding Assets (Multiple Files)
			*/
			if(count($request->input('final_docs')))
			{
				foreach($request->input('final_docs') as $doc_item)
				{
					$doc_data = explode('|', $doc_item);

					$fund_assets = array();
					$fund_assets['funding_business_id'] 	= $funding_business_id;
					$fund_assets['filename']				= $doc_data[0];
					$fund_assets['name'] 					= $doc_data[3];
					$fund_assets['url'] 					= $doc_data[1];
					$fund_assets['delete_url'] 				= $doc_data[2];
					$fund_assets['type'] 					= 1;

					$create_funding = FundingAssets::create($fund_assets);		
				}			
			}
			
			if(count($request->input('final_images')))
			{
				foreach($request->input('final_images') as $image_item)
				{
					$image_data = explode('|', $image_item);
					$fund_assets = array();
					$fund_assets['funding_business_id'] 	= $funding_business_id;
					$fund_assets['filename'] 				= $image_data[0];
					$fund_assets['name'] 					= $image_data[3];
					$fund_assets['url'] 					= $image_data[1];
					$fund_assets['delete_url'] 				= $image_data[2];
					$fund_assets['type'] 					= 2;

					$create_funding = FundingAssets::create($fund_assets);		
				}			
			}		

			if(count($request->input('final_videos')))
			{
				foreach($request->input('final_videos') as $video_rec)
				{
					$video_data = explode('|', $video_rec);

					$fund_assets = array();
					$fund_assets['funding_business_id'] 	= $funding_business_id;
					$fund_assets['name'] 					= $video_data[0];
					$fund_assets['url'] 					= $video_data[1];
					$fund_assets['type'] 					= 3;

					$create_funding = FundingAssets::create($fund_assets);	
					$create_funding_assets_data = FundingAssetsData::create(array('path'=>$video_data[1],'funding_business_assets_id'=>$create_funding->id));	
				}			
			}		

			if(count($request->input('fb_final_docs')))
			{
				foreach($request->input('fb_final_docs') as $doc_item)
				{
					$doc_data = explode('|', $doc_item);

					$fund_assets = array();
					$fund_assets['funding_business_id'] 	= $funding_business_id;
					$fund_assets['filename']				= $doc_data[0];
					$fund_assets['name'] 					= $doc_data[3];
					$fund_assets['url'] 					= $doc_data[1];
					$fund_assets['delete_url'] 				= $doc_data[2];
					$fund_assets['type'] 					= 1;

					$create_funding = FundingAssets::create($fund_assets);		
				}			
			}
			
			if(count($request->input('fb_final_images')))
			{
				foreach($request->input('fb_final_images') as $image_item)
				{
					$image_data = explode('|', $image_item);
					$fund_assets = array();
					$fund_assets['funding_business_id'] 	= $funding_business_id;
					$fund_assets['filename'] 				= $image_data[0];
					$fund_assets['name'] 					= $image_data[3];
					$fund_assets['url'] 					= $image_data[1];
					$fund_assets['delete_url'] 				= $image_data[2];
					$fund_assets['type'] 					= 2;

					$create_funding = FundingAssets::create($fund_assets);		
				}			
			}		

			if(count($request->input('fb_final_videos')))
			{
				foreach($request->input('fb_final_videos') as $video_rec)
				{
					$video_data = explode('|', $video_rec);

					$fund_assets = array();
					$fund_assets['funding_business_id'] 	= $funding_business_id;
					$fund_assets['name'] 					= $video_data[0];
					$fund_assets['url'] 					= $video_data[1];
					$fund_assets['type'] 					= 3;

					$create_funding = FundingAssets::create($fund_assets);	
					$create_funding_assets_data = FundingAssetsData::create(array('path'=>$video_data[1],'funding_business_assets_id'=>$create_funding->id));	
				}			
			}		

			// All good! let's go back
			//echo $funding_data->id;
			$profile_det = Profile::find($profile_id);
			$profile_det->funding = $request->input('sel_funding_type');
			$profile_det->save();
			if($request->input('sel_funding_type')==1)
				$msg = "Raising Funding Saved Successfully ";
			else 
				$msg = "Funding Business Saved Successfully ";
		
		endif;
			if(!$error_msg)
				return redirect('profiles/'.$profile_id)->with('succ_msg',$msg);
			else
				return redirect('profiles/'.$profile_id)->with('error_msg',$error_msg);
		/* End Raise funding save*/	
	}	

    protected function jQ_get_full_url() {
        $https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0 ||
            !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
                strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0;
        return
            ($https ? 'https://' : 'http://').
            (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
            (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
            ($https && $_SERVER['SERVER_PORT'] === 443 ||
            $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
            substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
    }


	/*public function pplajaxupload(Request $request)
	{
		$options = array(
			'param_name' => 'prev_profit_loss',
			'script_url' => url('profile/pplajaxupload', $parameters = [], $secure = null),
			'upload_dir' => dirname(@$_SERVER['SCRIPT_FILENAME']).'/uploads/funding_business/',
			'upload_url' => $this->jQ_get_full_url().'/uploads/funding_business/',
		);
		$upload = new AjaxUploadHandler($options);
	}*/

	public function pplajaxupload($param_name, Request $request)
	{
		$arr_params = explode('_', $param_name);$nfname = '';
		if($arr_params[0] == 'assets')
		{
			$upload_dir = dirname(@$_SERVER['SCRIPT_FILENAME']).'/uploads/funding_assets/'.$arr_params[1].'/';
			$upload_url = $this->jQ_get_full_url().'/uploads/funding_assets/'.$arr_params[1].'/';
			$nfname = 'fa_';
		}
		else
		{
			$upload_dir = dirname(@$_SERVER['SCRIPT_FILENAME']).'/uploads/funding_business/';
			$upload_url = $this->jQ_get_full_url().'/uploads/funding_business/';	
			$nfname = 'fbu_';		
		}

		$options = array(
			'param_name' => $param_name,
			'script_url' => url('profile/pplajaxupload/'.$param_name, $parameters = [], $secure = null),
			'upload_dir' => $upload_dir,
			'upload_url' => $upload_url,
			'new_file_name' => $nfname,
		);
		$upload = new AjaxUploadHandler($options);
	}	


	public function funding_permision($profile_id,$funding_id,Request $request)
	{
		if(is_numeric($profile_id)):
			$profile_det = Profile::where('id','=',$profile_id)->where("user_id",'=',Auth::user()->id)->get();
			$funding_det = Funding::where('id','=',$funding_id);
			$input = $request->all();
			
			if(isset($profile_det[0]) && (isset($input['lock']) || isset($input['unlock']))):
				$sel_profile = Profile::find($profile_id);
				$fund_det = Funding::find($funding_id);
				foreach($input as $key=>$value)
				{
					if($key=='lock'):
						$fund_det->private_permission=$fund_det->private_permission.$value.",";
					elseif($key=='unlock'):
						$fund_det->private_permission=str_replace($value.",",'',$fund_det->private_permission);
					endif;

					$msg = " Selected Details ".$key."ed Successfully"; // updated type like lock or unlock;
				}

				$fund_det->save();

 				return redirect('profiles/'.$profile_id)->with('succ_msg',$msg);					

			else:
 				return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
			endif;		
		else:
				return redirect('profiles/'.$profile_id)->with('error_msg',"Invalid Request");					
		endif;		
	}

	public function typeahead(Request $request)
	{
		$input = $request->all();
		$result = Profile::typeaheadName($input['profile_name']);	
		/*echo "<pre>";
		print_r($result);
		exit;*/
		echo json_encode($result);
	}

	public function funding_download($driver, $filename)
	{
		return redirect(url('uploads/'.$driver.'/'.$filename));
	}

    
    public function funding_assets_access_update($access_id,Request $request)
    {
        if(is_numeric($access_id)):
           $assets_det = FundingAssets::where('id','=',$access_id)->get();
           $input = $request->all();
           if(isset($assets_det[0]) && $input['access']): 
               $asset = FundingAssets::find($assets_det[0]->id); 

              if($input['access']=='lock'):
                $asset->access = 'PVT'; 
              elseif($input['access']=='unlock'):
                $asset->access = 'PUB'; 
              else:
                return redirect(URL::previous())->with('error_msg',"Invalid Request");
              endif; 
              
              /* save access */
               $asset->save();
               return redirect(URL::previous())->with('succ_msg',"Selected details ".ucwords($input['access'])." Successfully");    
              /* End save access */               
            else:
                return redirect(URL::previous())->with('error_msg',"Invalid Request");                
            endif;
        else:
            return redirect(URL::previous())->with('error_msg',"Invalid Request");
        endif;
    }
       
    public function AjaxCreateVideo(Request $request)
    {
    	$input = $request->all();
        $client_id     = Config::get('constants.VIMEO_CLIENT_ID');
        $client_secret = Config::get('constants.VIMEO_SECRET_KEY');
        $access_token  = Config::get('constants.VIMEO_ACCESS_TOKEN');
        $lib           = new \Vimeo\Vimeo($client_id, $client_secret,$access_token);
        $file_path     = $request->file('assets_videos')->getRealPath();
        $uri           = $lib->upload($file_path,false);
        if($uri)
        {	
	        $video_data = explode('/',$uri);
	    }
        echo json_encode(array('assets_video'=>array(array('name'=>$request->file('assets_videos')->getClientOriginalName(),'path'=>$video_data[2]))));
    }

    public function funding_assets_delete($funding_business_id)
    {
    	$assets_det = FundingAssets::find($funding_business_id);
    	if(isset($assets_det->id)):
	    	
	    	if($assets_det->type!='VIDEOS')
	    	{	
		    	if($assets_det->type=='IMAGES')
		    		$disk = 'funding_pics';
		    	else if($assets_det->type=='DOCS')
		    		$disk = 'funding_docs';	

		    	if(Storage::disk($disk)->exists($assets_det->name))
		    	Storage::disk($disk)->delete($assets_det->name);
			}
			else if($assets_det->type=='VIDEOS')
			{
				$assets_data_det = FundingAssetsData::where('funding_business_assets_id','=',$assets_det->id)->get();
				if(isset($assets_data_det[0]->id))		
				{
	               $path_id = $assets_det->url;
	               $client_id      = Config::get('constants.VIMEO_CLIENT_ID');
	               $client_secret  = Config::get('constants.VIMEO_SECRET_KEY');
	               $access_token   = Config::get('constants.VIMEO_ACCESS_TOKEN');
	               $lib            = new \Vimeo\Vimeo($client_id, $client_secret,$access_token);
	               $uri            = $lib->request('/videos/'.$path_id, array(), 'DELETE');
	               $assets_data = FundingAssetsData::find($assets_data_det[0]->id);
	               $assets_data->delete();
	            }  
			}
	    	$assets_det->delete();
			return redirect(URL::previous())->with('succ_msg',"Selected Details Delete successfully");	    	
	    endif;
   }

	public function funding_docs_delete($funding_id,$doc_type)
	{
		$fund_det = Funding::find($funding_id);
		$file_name ='';
		if(isset($fund_det->id)):

			if($doc_type == 'prev_profit_loss')
			{
				$file_name = $fund_det->prev_profit_loss_name;
				$fund_det->prev_profit_loss = '';
				$fund_det->prev_profit_loss_name = '';
			}	
			else if($doc_type == 'next_profit_loss')
			{
				$file_name = $fund_det->next_profit_loss_name;
				$fund_det->next_profit_loss = '';
				$fund_det->next_profit_loss_name = '';
			}	
			else if($doc_type == 'lship_team_file')
			{
				$file_name = $fund_det->lship_team_file_name;
				$fund_det->lship_team_file = '';
				$fund_det->lship_team_file_name = '';
			}	

	    	if($file_name && Storage::disk('funding_single')->exists($file_name))
	    	Storage::disk('funding_single')->delete($file_name);

	    	$fund_det->update();
			return redirect(URL::previous())->with('succ_msg',"Selected Details Delete successfully");	    	
	    endif;
	}
         public function pro_likes(Request $request)
        { 
          $data_id = Input::get('like_id');
          if($data_id):
          $profiles = Profile::where("id",'=',$data_id)->get();
          $likes = Users_likes::where("like_user_id",'=',Auth::user()->id)->where("likes_id",'=',$data_id)->where("likes_type",'=','P')->get();
           if(isset($likes[0])):
                  $delete=Users_likes::where("like_user_id",'=',Auth::user()->id)->where("likes_id",'=',$data_id)->where("likes_type",'=','P')->delete(); 
                          if($delete):echo "Like"; endif;
                               else:
                           $object= Users_likes::create([
                                    'like_user_id' => trim(Auth::user()->id),
                                    'owner_id' => trim($profiles[0]->user_id),
                                    'likes_id' => trim($profiles[0]->id),
                                    'likes_type'=>'P',
                                   ]);  
                           if($object):echo "Unlike"; endif;
                               endif;
                       
          endif;
          
       
        }
         public function pro_check(Request $request)
        {  
             $pro_id = Input::get('pro_id');
             $result=Input::get('result');
             
             if(is_numeric($pro_id)):
             $pro_det = Profile::find($pro_id);
                if($pro_det):
                    $pro_det = Profile::where('id', '=', $pro_id)->update(['is_interest' => $result]);
                    if($pro_det):
                         return "Success";
                    else:
                         return "Fail";
                    endif;
                else:
                return Redirect::back()->with('error_msg',"Invalid Request");     
                endif;
                 
             else:
             return Redirect::back()->with('error_msg',"Invalid Request");         
             endif;
             
        }
}
