<?php namespace App\Http\Controllers;
use App\Profile; // Profile Model
use Auth; // Auth model

use Response;
use Storage;
use Illuminate\Http\Request;
use App\Actions;
use Datatables;
use Session;
use Redirect;
use App\user;
use App\ProfileCategories;
use App\CategoryIndustry;
use App\CategoryRoles;
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 App\Countries;
use App\Awards;
// use Image;
use App\FundingAssetsData;
use App\FinancialServices;
use App\Assets;
use App\AssetsData;
use App\AssetsShared;

class ShareController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Share Controller
	|--------------------------------------------------------------------------
	|
	|
	*/

	/**
	 * Share controller instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		$this->middleware('auth');
                if(!Session::get('auth_selected_profile')) {
                                return Redirect::to('profile/step1')->with('succ_msg', 'Please Create atleast one profile')->send(); 
                             }
	}

	/**
	 * Share public files.
	 *
	 * @return Response
	 */

	public function index()
	{ //echo Session::get('auth_selected_profile'); exit;
		//$profiles = Actions::where('profile_id','=',Auth::user()->id)->where('folder','=','S')->get();
	    return view('share.index');
	}

	public function ajax_list(Request $request)
	{ 
		$input = $request->all();	
                    //print_r($input); exit;
		$results = Actions::where('profile_id','=',Session::get('auth_selected_profile'))
						->where('folder','=',$input['folder'])
						->where('status','=','1');

		return Datatables::of($results)

						->addColumn('sender', function($results) {
							$default_image = 'default-profile.png';

							$user_det = Profile::find($results['from_id']);	

							if($results['is_readed']=='N')
								$sender = '<strong>'.$user_det->name.'</strong>';
							else
								$sender =  $user_det->name;	
							if($user_det->profile_image && is_file('uploads/profile_images/'.$user_det->profile_image)){								
								$default_image = $user_det->profile_image;}

							return '<img src="'.url('uploads/profile_images/'.$default_image).'" class="img-circle menter-profil-pic"><p class="share-pg-p">'.ucwords($sender).'</p>';

							/* End Using Profile ID*/	


						})
						->addColumn('action',function($results){

							return '<a href="'.url("profiles/".$results['from_id']."/S/".$results["id"]).'" class="btn btn-primary share-pg-view-btn" >View Profile</a>';
						})
						->editColumn('created_at',function($results){

							if(date("Y-m-d")==date('Y-m-d', strtotime($results['created_at'])))
								$date= '<a href="javascript:void(0)" title="'.date('m/d/Y h:i a', strtotime($results['created_at'])).'">'.date('h:i a', strtotime($results['created_at'])).'</a>';
								else
								$date= '<a href="javascript:void(0)" title="'.date('m/d/Y h:i a', strtotime($results['created_at'])).'">'.date('M d', strtotime($results['created_at'])).'</a>';

							if($results['is_readed']=='N')
							$data="<strong>".$date."</strong>";	
							else
							$data=$date;

							return $data;
						})
						->make(true);
	}

	public function request(Request $request)
	{
           // return 'hi';exit;
		/* Private type keys with name */
		 /* $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');*/
		/* Private type keys*/
		 // $private_type_keys = array('B','L','EXP','EDU','S','In','Int','A','W','Cont','P','AW');
                $asst_pic = Assets::getRowsList(Session::get('auth_selected_profile'),'I');
                $asst_res = Assets::getRowsList(Session::get('auth_selected_profile'),'R');
                $asst_vid = Assets::getRowsList(Session::get('auth_selected_profile'),'V');
                
                $private_type = array('one'=>1,'two'=>2);
                //echo Session::get('auth_selected_profile'); exit;
		$input = $request->all();                
		if($input['profileList'])
		{
			if(isset($input['send_request'])) 
			{                            
                             $insert_data=array();
                               if(! empty($input['permission'])) {
                                for($i=0;$i<count($input['profileList']);$i++)
                                { 
                                    for($j=0;$j<count($input['permission']);$j++){
                                        
                                        $user_id = Profile::where('id','=',$input['profileList'][$i])->get()->first();
                                        $insert_data[] = array(
						'from_id' => Session::get('auth_selected_profile'),
						'to_id' => $user_id->user_id,
						'assets_id' =>$input['permission'][$j],
						'created_at' => date('Y-m-d h:i:s'),
						'updated_at' => date('Y-m-d h:i:s'),
					);
                                    }
                                }
                               }
                               else
                               {  
                                   for($i=0;$i<count($input['profileList']);$i++)
                                    { 
                                   
                                       $user_id = Profile::where('id','=',$input['profileList'][$i])->get()->first();
                                       $assets_inf = array(
                                           'name' => $user_id->name,
                                           'profile_id' => Session::get('auth_selected_profile'),
                                           'asset_type' => 'O'
                                       );                                       
                                       $asset_ins = Assets::create($assets_inf);                                       
                                       $action_data[] = array(
                                                    'profile_id' =>$input['profileList'][$i], 
                                                    'from_id' => Session::get('auth_selected_profile') ,
                                                    'to_id' => $user_id->user_id,
                                                    'folder' => 's',
                                                    'status' => '1',
                                                    'created_at' => date('Y-m-d h:i:s'),
                                                    'updated_at' => date('Y-m-d h:i:s'),
                                            );
                                      // print_r($insert_data); 
                                             
                                    }
                                    Actions::insert($action_data);
                               }
                               
                        if(!empty($insert_data)){
                            
                            $insert_share = AssetsShared::insert($insert_data);
                        
                        }
                        return redirect('/search')->with('succ_msg',"Selected Items has been shared successfully..");
                        //$profiles = Profile::whereRaw("id IN (".implode(',',$input['profileList']).")")->get();                        
		        //return view('share.request_list')->with(['share_request'=>$profiles,'asst_pic'=>$asst_pic,'asst_vid'=>$asst_vid,'asst_res'=>$asst_res,'succ_msg'=>'']);
                         
			}	

			$profiles = Profile::whereRaw("id IN (".implode(',',$input['profileList']).")")->get();                        
		    return view('share.request_list')->with(['share_request'=>$profiles,'asst_pic'=>$asst_pic,'asst_vid'=>$asst_vid,'asst_res'=>$asst_res]);
		}
		else
		{
			return redirect(URL::previous())->with('error_msg',"Invalid To address");
		}
	}

	public function share_view($id,$share_id,Request $request)
	{
        if(is_numeric($id)):
           $profile_det = Profile::where('id','=',$id)->get();
           if(isset($profile_det[0]) && is_numeric($share_id)): 

				if($profile_det[0]->user_id==Auth::user()->id):
					$profile_det[0]->private = true;
				else:
					$profile_det[0]->private = false;
				endif;	

               $share_det = Actions::find($share_id); 
           		if(isset($share_det->id) && $share_det->from_id == $profile_det[0]->id):

           			if($share_det->permission_type=='S')
           				$profile_det[0]->private_permission = $share_det->permission_list;
           				/*$profile_det[0]->full_profile = FALSE;
           			else
           				$profile_det[0]->full_profile = TRUE;	*/
           			
           			if($share_det->is_readed=='N'):
           				$share_det->is_readed = 'Y';
           				$share_det->save();
           			endif;
           			
           			/*Load view profile*/
						/* Categories by profile ID */
						$profile_categories = $profile_experience = $profile_education = $profile_location = $profile_links ='';

						/*echo strpos($profile_det[0]->private_permission,'B,');
						exit;*/
						$countries = Countries::orderBy('name')->get();
						$profile_categories = ProfileCategories::getCategoriesByProfileID($profile_det[0]->id); 
						$profile_experience = Experience::getExperienceByProfileID($profile_det[0]->id);
						$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_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_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')]);
						return view($view)->with($arr_withs);
	            else:
	                return redirect(URL::previous())->with('error_msg',"Invalid Request");                
	            endif;
            else:
                return redirect(URL::previous())->with('error_msg',"Invalid Request");                
            endif;
        else:
            return redirect(URL::previous())->with('error_msg',"Invalid Request");
        endif;
		//$this->talent($id,)
	}

	/*Talent Profile Detials view, Save, Edit And Delete*/
	public function talent($id)
	{
		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])):

				if($profile_det[0]->user_id==Auth::user()->id):
					$profile_det[0]->private = true;
				else:
					$profile_det[0]->private = false;
				endif;	

				
				/* 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);
				$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_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_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')]);
				return view($view)->with($arr_withs);
			else:
				return redirect('myaccount')->with('error_msg',"Invalid Request");
			endif;
		else:
			return redirect('myaccount')->with('error_msg',"Invalid Request");
		endif;
	}

	public function share_asset(Request $request)
	{
		$input = $request->all(); 
		if($input['assets_id'] && isset($input['to']))
		{
			$insert_data=array();
			foreach ($input['to'] as $key => $value) {
				$insert_data[] = array(
						'from_id' => Session::get('auth_selected_profile'),
						'to_id' => $value,
						'assets_id' =>$input['assets_id'],
						'created_at' => date('Y-m-d h:i:s'),
						'updated_at' => date('Y-m-d h:i:s'),
					);
			}
			$insert_share = AssetsShared::insert($insert_data);

			return redirect(URL::previous())->with('succ_msg',"Selected ".$input['asset_type']." shared successfully");
		}
		else
		{
			return redirect(URL::previous())->with('error_msg',"Invalid To address");
		}
	}

	public function assets_ajx_list(Request $request)
	{
		$input = $request->all();	
		$results = AssetsShared::where('to_id','=',Auth::user()->id)->orderBy('created_at', 'desc');

		return Datatables::of($results)
			->addColumn('sender', function($results) {
				$default_image = 'default-profile.png';
				$user_det = Profile::where('id', '=', $results['from_id'])->first();
				if($results['is_read']=='N')
					$sender = '<strong>'.$user_det->name.'</strong>';
				else
					$sender =  $user_det->name;	
				if($user_det->profile_image && is_file('uploads/profile_images/'.$user_det->profile_image)){								
								$default_image = $user_det->profile_image;}
				
				return '<a href="'.url("profiles/".$results['from_id']."/S/".$results["id"]).'"><img src="'.url('uploads/profile_images/'.$default_image).'"  class="img-circle menter-profil-pic"><p class="share-pg-p">'.ucwords($sender).'</p></a>';
			})
			->addColumn('file', function($results){

				$assets = Assets::where('id', '=', $results['assets_id'])->first();				
				return $assets['name'];
			})
			->addColumn('action',function($results){
				
				$assets = Assets::where('id', '=', $results['assets_id'])->first();
				$assets_data = AssetsData::where('asset_id', '=', $results['assets_id'])->first();				
				$return_context = '';
				switch ($assets['asset_type']) {
					case 'I':
						$return_context = '<a href="javascript:;" data-id="'.$results['id'].'" pic-src ="images/'.$assets_data['path'].'" class="btn btn-primary pic-popup share-pg-view-btn" target="_blank">View Picture</a>';
						break;
					case 'V':
						$return_context = '<a href="javascript:;" data-id="'.$results['id'].'" iframe-src ="https://player.vimeo.com/video/'.$assets_data['path'].'" class="btn btn-primary popup share-pg-view-btn" >View Video</a>';
						break;
					case 'R':
						$return_context = '<a href="javascript:;" data-id="'.$results['id'].'" download-url="'.URL::to('res_download', array($results['assets_id'])).'" class="btn btn-primary download-popup share-pg-view-btn" target="_blank">View Resume</a>';
						break;											
				}
				return $return_context;
			})
			->editColumn('created_at',function($results){
				if(date("Y-m-d")==date('Y-m-d', strtotime($results['created_at'])))
					$date= '<a href="javascript:void(0)" title="'.date('m/d/Y h:i a', strtotime($results['created_at'])).'">'.date('h:i a', strtotime($results['created_at'])).'</a>';
					else
					$date= '<a href="javascript:void(0)" title="'.date('m/d/Y h:i a', strtotime($results['created_at'])).'">'.date('M d', strtotime($results['created_at'])).'</a>';

				if($results['is_readed']=='N')
				$data="<strong>".$date."</strong>";	
				else
				$data=$date;

				return $data;
			})
			->make(true);		
	}

	public function update_count($asset_id)
	{
		// make it read
		$asset = AssetsShared::find($asset_id);
		$asset->is_read = 'Y';
		$asset->save();
	}
}
