<?php namespace App\Http\Controllers;

use App\User;
use App\Assets;
use App\AssetsData;
use Validator;
use Session;
use Illuminate\Support\Facades\Input;
use Vimeo\Vimeo;
use Config;
use Illuminate\Http\Request;
use Redirect;
use URL;
use App\Users_likes;

use App\FundingAssets;
use App\FundingAssetsData;
use Auth;
use App\Profile;
use App\History;

class VideoController extends Controller {

    private $current_profile_id;
	/*
	|--------------------------------------------------------------------------
	| User Controller
	|--------------------------------------------------------------------------
	|
	| This controller renders your application's users functionality
	| like signup, login, forgot password.
	|
	*/

	/**
	 * Create a new 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(); 
                             }
    }

	/**
		 * Show the application login to the user.
		 *
		 * @return Response
		 */
		public function index(Request $request)
		{
            
            $this->middleware('auth');
            $this->current_profile_id = Session::get('auth_selected_profile');
            if($request->input('upload')=='push')
            {
                    $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     = Input::file('image')->getRealPath();
                    $uri           = $lib->upload($file_path,false);
                    if($uri)
                    {
                        $video_data = explode('/',$uri);

                        $data = array(
                                        'name'          => $request->Input('name'),
                                        'asset_type'    => 'V',
                                        'profile_id'    => $this->current_profile_id,
                                        'processed'     => '0',
                                        'access'        => $request->Input('vid_type'),
                                    );
                        $res = Assets::Create($data);
                        $assets_data = array('path'=>$video_data[2],'asset_id'=>$res->id);
                        AssetsData::Create($assets_data);
                        
               }
                
            }
            
            $maxlimit = Config::get('constants.VIDEO_LIMIT');

            $video_data = Assets::getVideos($this->current_profile_id,$maxlimit);
            $numrows = Assets::getRows($this->current_profile_id,'V');
			return view('profileAssets.videos')->with('data',$video_data)->with('numrows',$numrows)->with('maxlimit',$maxlimit);
		}
    
        public function add_view(Request $request)
           {
             $data_id = Input::get('atr_val');
             $video = History::Addview(Session::get('auth_selected_profile'),$data_id,'V');
             if($video):
                 return $video;
             endif;
           }
        public function videoProcessedStatus()
        {
            $list = Assets::getUnprocessedVideos();
            $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);
            foreach($list as $details)
            {
                
                $uri       = $lib->request('/videos/'.$details->path);
                if($uri['body']['status']=='available' && $uri['body']['pictures']['sizes']['1']['link'] !="")
                {
                    Assets::where('id', '=', $details->id)->update(['processed' => '1']);
                    AssetsData::where('id','=',$details->assets_data_id)->update(['thumb_img' => $uri['body']['pictures']['sizes']['1']['link']]);
                    $this->updateTitle($details->path,$details->name);
                    
                    
                }else if($uri['body']['status']=='uploading_error'){
                    Assets::where('id', '=', $details->id)->update(['processed' => '2']);  
                    
                }
            }
            
            $video_list = FundingAssets::getUnprocessedVideos();
            foreach($video_list as $details)
            {
                $uri       = $lib->request('/videos/'.$details->url);
                if($uri['body']['status']=='available' && $uri['body']['pictures']['sizes']['1']['link'] !="")
                {
                    FundingAssets::where('id', '=', $details->id)->update(['processed' => '1']);
                    FundingAssetsData::where('funding_business_assets_id','=',$details->id)->update(['thumb_img' => $uri['body']['pictures']['sizes']['1']['link']]);
                    
                }else if($uri['body']['status']=='uploading_error'){
                    FundingAssets::where('id', '=', $details->id)->update(['processed' => '2']);  
                    
                }
            }
        }
    
    public function updateTitle($id="128234977",$name="test1")
    {
        
        $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);
        $params         = array('name'=>$name);
        $uri            = $lib->request('/videos/'.$id, $params, 'PATCH');
       
    }
    
    public function test($id="128234977")
    {
        
         $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/'.$id, array(), 'DELETE');
        print_r($uri);
    }

    /* update video access type*/
        public function update_access($access_id,Request $request)
        {
            if(is_numeric($access_id)):
               $video_det = Assets::where('id','=',$access_id)->get();
               $input = $request->all();
               if(isset($video_det[0]) && (Session::get('auth_selected_profile')==$video_det[0]->profile_id) && $input['access']): 
                   $video = Assets::find($video_det[0]->id); 

                  if($input['access']=='lock'):
                    $video->access = 'PVT'; 
                  elseif($input['access']=='unlock'):
                    $video->access = 'PUB'; 
                  else:
                    return redirect(URL::previous())->with('error_msg',"Invalid Request");
                  endif; 
                  
                  /* save access */
                   $video->save();
                   return redirect(URL::previous())->with('succ_msg',"Video ".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;
        }
    /* end update video access type*/    

    /*load more videos ajax request*/
      public function loadmore(Request $request)
        {
            $input = $request->all();
            $video_data = array();
            $take = $input['take'];
            $skip = $input['skip'];
            $search_key = $input['sea_key'];
            $this->current_profile_id = Session::get('auth_selected_profile');
            
            $likes = Users_likes::where("like_user_id",'=',Auth::user()->id)->where("likes_type",'=','V')->get();
            
            $values=array(); 
            foreach($likes as $val)
            {
                  $values[]=$val['likes_id'];
            }
            
            $video_data['count'] = Assets::getVideosCount($this->current_profile_id,$search_key);
            $video_data['values'] = Assets::getVideos($this->current_profile_id,$take,$skip,$search_key);
            $video_data['likes']  = $values;
            echo json_encode($video_data);
        }

    /* end load more vidoes ajax request */

    /* Delete video*/
    public function delete($access_id,Request $request)
    {

        if(is_numeric($access_id)):
               $video_det = Assets::where('id','=',$access_id)->get();
               $input = $request->all();
               if(isset($video_det[0]) && (Session::get('auth_selected_profile')==$video_det[0]->profile_id)): 

                   $video_data_det = AssetsData::where('asset_id','=',$video_det[0]->id)->get();

                   $video = Assets::find($video_det[0]->id); 
                  
                  /* Delete video */
                   if(isset($video_data_det[0]->id)):
    
                       $video_data = AssetsData::find($video_data_det[0]->id); 
                       $path_id = $video_data_det[0]->path;
                       $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');
                      
                       $video_data->delete();
                   endif;

                   $video->delete();

                   return redirect(URL::previous())->with('succ_msg',"Video Deleted Successfully");    
                  /* End Delete video */               
                else:
                    return redirect(URL::previous())->with('error_msg',"Invalid Request");                
                endif;
            else:
                return redirect(URL::previous())->with('error_msg',"Invalid Request");
            endif;
        /*echo "connect";
        exit;
      */
    }
    /* end Delete Video*/
    /*video search*/
//    public function videosearch(Request $request)
//    {
//        $this->current_profile_id = Session::get('auth_selected_profile');
//        $output=array();
//        $input = $request->all();
//        $search_data = $input['searchdata'];
//        $videos = Assets::getVideoSearch($search_data);
//        if(count($videos)>0)
//        {
//           foreach($videos as $video)
//           {
//
//             $video_img = ''; $access = '';
//             $vid_likes='';$likes='';
//             if($video->processed == '0'):
//                $video_img = '<img src="/uploads/processing.jpg" class="img-responsive ">';        
//             else:
//                $video_img = '<img src="'.$video->thumb_img.'" iframe-src ="https://player.vimeo.com/video/'.$video->path.'" class="img-responsive popup">';
//             endif;
//             
//             if(Session::get('auth_selected_profile')==$video->profile_id):
//              $access = '<div class="col-md-4 mtop10"><span class="lock-icon"><a href="{{url(videos/'.$video->id.'?access=lock)}}"><i class="fa fa-unlock"></i></a></span><span class="delete-icon"><a href="javascript:void(0)" title="Delete" class="delete_video" data-id="{{$video->id}}"><i class="fa fa-trash-o fa-lg"></i></a></span></div>';
//             endif;
//             //return $video->profile_id;exit;
//              if(Session::get('auth_selected_profile')!=$video->profile_id):
//                  //return Auth::user()->id;exit;
//                $likes = Users_likes::where("like_user_id",'=',Auth::user()->id)->where("likes_type",'=','V')->get();
//             //print_r($likes);exit;
//		$values=array(); 
//                foreach($likes as $val)
//                  {
//                      $values[]=$val['likes_id'];
//                  }
//                  //print_r($values);exit;
//                 $vid_likes='<div class="update_likes'.$video->id.'">';
//                 if(in_array($video->id,$values)):
//                 $vid_likes.='<div class="">  
//                     <a href="javascript:void(0)" class="updt_pro like'.$video->id.'" data-id="'.$video->id.'" style="color:#15AE9E"><span class="glyphicon glyphicon-thumbs-down"></span> (Unlike)</a> 
//                 </div>';
//                 else:
//                 $vid_likes.='<div class="">   
//                     <a href="javascript:void(0)" class="updt_pro unlike'.$video->id.'" data-id="'.$video->id.'" ><span class="glyphicon glyphicon-thumbs-up"></span> (Like)</a>                 
//                 </div>';
//                 endif;
//                 $vid_likes.='</div>';
//                 //print_r($output);exit;
//                 endif;
//
//             $output[]=  '<div class="col-sm-4 mbot10 vidlen">
//                    <div class="row">
//                      <div class="col-md-7 ">
//                      <h4 class="heading_min_height" >'.str_limit($video->name, $limit = 30, $end = '.....').'</h4>
//                        
//                      </div>'.$access.'</div>'.$video_img.$vid_likes.'</div>';
//           }
//        }
//        else
//        {
//           $output=  '<div class="col-sm-12 vidlen">
//                         <h4>No Videos Found</h4>
//                      </div>'; 
//        
//        }
//         return $output;  
//    }
//    
    /*like pictures*/ 
                public function vid_likes(Request $request)
                { 
                  $data_id = Input::get('like_id');
                 
                  $pic_det = Assets::where('id','=',$data_id)->get();
                 // echo Auth::user()->id;
             //  print_r($pic_det[0]->profile_id);exit;
                    if(isset($pic_det[0]) && $pic_det[0]->profile_id!=''):   
                        $profiles = Profile::where("id",'=',$pic_det[0]->profile_id)->get();
$likes = Users_likes::where("like_user_id",'=',Auth::user()->id)->where("likes_id",'=',$data_id)->where("likes_type",'=','V')->get();
                      if(isset($likes[0])):
                          $delete=Users_likes::where("like_user_id",'=',Auth::user()->id)->where("likes_id",'=',$data_id)->where("likes_type",'=','V')->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($pic_det[0]->id),
                                    'likes_type'=>trim($pic_det[0]->asset_type),
                                   ]);  
                           if($object):echo "Unlike"; endif;
                               endif;
                    
                    endif;
                     
                }

    /*end video search*/
}
