<?php namespace App\Http\Controllers;

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

class PicturesController 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(); 
                             }
                        $this->current_profile_id = Session::get('auth_selected_profile');
                        
                }

	/**
		 * Show the application login to the user.
		 *
		 * @return Response
		 */
		public function index(Request $request)
		{
                    
                 if($request->input('upload')=='push')
                {  
                    $rule  =  array(
                    'name' => 'required',
                    'image' => 'required|image|max:2000',
                     );
                    $validator = Validator::make(Input::all(),$rule);
                    if ($validator->fails())
                     {
                        return Redirect::to('pictures')
                            ->withErrors($validator->messages());
                     }
                    else
                     {
                       $object= Assets::create([
                                    'name' => trim(Input::get('name')),
                                    'profile_id' => $this->current_profile_id,
                                    'asset_type' => 'I',
                                   ]);
                        $id = $object->id;
                        
                        $image = Input::file('image');       
                        $img_name  = $image->getClientOriginalName();
                        $info = pathinfo($img_name);
                        $org_name =  basename($img_name,'.'.$info['extension']);
                        $tmp = explode('.', $img_name);
                        $ext = end($tmp);
                        $filename=$org_name.'_'.$id.'.'.$ext;
                        
                        $destination = 'images/';      
                        $image->move($destination, $filename);

                        AssetsData::create([
                                    'asset_id' => $id, 
                                    'path' => $filename,
                                   ]);
                     }
                }       $maxlimit = Config::get('constants.PIC_LIMIT');
                        $pictures = Assets::getPictures($this->current_profile_id,$maxlimit);
                        $numrows = Assets::getRows($this->current_profile_id);
    
			return View('profileAssets.pictures')->with('data',$pictures)->with('numrows',$numrows)->with('maxlimit',$maxlimit)->withMessage('Data inserted');
                     
                    
                }
           public function add_view(Request $request)
           {
             $data_id = Input::get('atr_val');
             $pictures = History::Addview($this->current_profile_id,$data_id,'I');
             if($pictures):
                 return $pictures;
             endif;
           }
           public function findlimit(Request $request)
           {
            $input = $request->all();
            $take = $input['take'];
            $skip = $input['skip'];
            $search_key = $input['sea_key'];
           // return $take;exit;
            $this->current_profile_id = Session::get('auth_selected_profile');
            
            $likes = Users_likes::where("like_user_id",'=',Auth::user()->id)->where("likes_type",'=','I')->get();
            
            $values=array(); 
            foreach($likes as $val)
            {
                  $values[]=$val['likes_id'];
            }
            
            $output['count'] = Assets::getPiccount($this->current_profile_id,$search_key);
            $output['values'] = Assets::getPictures($this->current_profile_id,$take,$skip,$search_key);
            $output['likes']  = $values;
            echo json_encode($output);
                }
               /*searching pictures*/ 
//                public function picturesearch()
//                {
//                $likes = Users_likes::where("like_user_id",'=',Auth::user()->id)->where("likes_type",'=','I')->get();
//		$values=array(); 
//                foreach($likes as $val)
//                  {
//                      $values[]=$val['likes_id'];
//                  }
//                 //echo '<pre>';print_r($values);exit;
//                $search_data = Input::get('searchdata');
//                $take = Input::get('take');
//                $skip = Input::get('skip');
//                $searchrows = Assets::getsearchRows('I',$search_data);
//                $pictures = Assets::getSearch($search_data,$take,$skip);
//                return View('profileAssets.dum_pictures')->with('likes',$values)->with('searchrows',$searchrows)->with('data',$pictures);  
//                  
//                }
//                
                public function pic_likes(Request $request)
                { 
                  $data_id = Input::get('like_id');
                  $pic_det = Assets::where('id','=',$data_id)->get();
                 // echo Auth::user()->id;
                 // print_r($likes_det);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",'=','I')->get();
                      if(isset($likes[0])):
                          $delete=Users_likes::where("like_user_id",'=',Auth::user()->id)->where("likes_id",'=',$data_id)->where("likes_type",'=','I')->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;
                      //return Redirect::back()->with('succ_msg',"Like Updated Successfully");   
                       // $likes = Users_likes::where("like_user_id",'=',Auth::user()->id)->where("likes_type",'=','I')->get();
		      /*  $values=array(); 
                        foreach($likes as $val)
                          {
                              $values[]=$val['likes_id'];
                          }*/
                  //  return $pictures;exit;
                         //return View('profileAssets.ajax_likes')->with('likes',$values)->with('data',$pictures);  
                  
                }
                
              /*Update user Access*/   
               public function update_access($access_id,Request $request)
             {
              if(is_numeric($access_id)):
               $pic_det = Assets::where('id','=',$access_id)->get();
               $input = $request->all();
               if(isset($pic_det[0]) && ($this->current_profile_id==$pic_det[0]->profile_id) && $input['access']): 
                   $picture = Assets::find($pic_det[0]->id); 

                  if($input['access']=='lock'):
                    $picture->access = 'PVT'; 
                  elseif($input['access']=='unlock'):
                    $picture->access = 'PUB'; 
                  else:
                    return Redirect::back()->with('error_msg',"Invalid Request");
                  endif; 
                  
                  /* save access */
                   $picture->save();
                   return Redirect::back()->with('succ_msg',"Picture ".ucwords($input['access'])." Successfully");    
                  /* End save access */               
                else:
                    return Redirect::back()->with('error_msg',"Invalid Request");                
                endif;
            else:
                return Redirect::back()->with('error_msg',"Invalid Request");
            endif;
           }
           public function pic_delete($del_id,Request $request)
           {
              if(is_numeric($del_id)):
              $pic_id=Assets::find($del_id)->where("profile_id",'=',$this->current_profile_id)->where("asset_type",'=','I')->get();
              $pic_data=AssetsData::where('asset_id','=',$del_id)->get()->first();
              
                 $dd = $pic_data->path;
          
              if(isset($pic_id[0])):
                  
                    $m_img_path='images/'.$dd;
                  if (file_exists($m_img_path))
                    {
                        unlink($m_img_path);     
                    }
               $delete = AssetsData::where('asset_id', '=', $del_id)->delete();
              if($delete):
                  $delete1 = Assets::where('id', '=', $del_id)->delete();
                 if($delete1):
                     return Redirect::back()->with('succ_msg',"Picture Deleted Successfully");   
                 else:
                    return Redirect::back()->with('error_msg',"Invalid Request");    
                 endif;
              else:
                 return Redirect::back()->with('error_msg',"Invalid Request");    
              endif;

                else:
                  return Redirect::back()->with('error_msg',"Invalid Request");   
              endif;
              else:
                return Redirect::back()->with('error_msg',"Invalid Request");   
              endif;
           }
}
