<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\User;
use Validator;
use Exception;
use Illuminate\Support\Str;
use DB;
use App\Helpers\Helper;

class CruiseApiController extends Controller
{
    protected $_user;
    public function __construct()
    {
        $this->middleware(function (Request $request, $next) {
            $this->_user = Auth::user();            
            return $next($request);
        });
        
    }
    public function fileLink(Request $request){
        try {
            $input = $request->all();
            $validations = [
                'id'   => 'required|integer',
            ];
            $validator = \Validator::make($request->all(), $validations);
			if ($validator->fails()) {
				throw new Exception($validator->errors()->first(),400);
			}
			else{
                $data = \App\TourInfo::getListing(['id' => $input['id'],'with'=>[],'select'=>['id','link','file_type']]);
                if($data){
                    return response()->json([
                        'success' => true,
                        'msg' => 'Link generated successfully',
                        'data' => ['media_size_info_url' => $data->media_size_info_url]
                    ], 200);
                }
                else{
                    throw new Exception('Details not found',400);
                }
            } 
        }catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
        
    }
    public function assignBooking(Request $request)
    {
        try {
            $input = $request->all();
            $validations = [
                'booking_no'   => 'required',
                'bookdate' => 'required'
            ];
            $validator = \Validator::make($request->all(), $validations);
			if ($validator->fails()) {
				throw new Exception($validator->errors()->first(),400);
			}
			else{
                $bookingMap = \App\TourSchedule::getListing($input);
                if(count($bookingMap)) {
                    $postVal = [];
                    $bookingActualStartDate = date('Y-m-d',strtotime($bookingMap[0]->tour->start_date));
                    $bookingPostStartDate = date('Y-m-d',strtotime($input['bookdate']));
                    //$bookingPostStartDate = date('Y-m-d',strtotime('+330 minutes',strtotime($input['bookdate'])));
                    //dd($bookingActualStartDate . ' <= => ' . $bookingPostStartDate);
                    
                    $latestCruise = null;
                    if( ($bookingActualStartDate == $bookingPostStartDate) && ($bookingMap[0]->status==1) ) {
                        $postVal['user_id'] = $this->_user->id;
                        // check if relation exists between user and booking_no
                        $usrSchdlMap = \App\UserScheduleMapping::getListing(['user_id'=>$postVal['user_id'],'schedule_id'=>$bookingMap[0]->id]);
                        if(count($usrSchdlMap)) {
                            throw new Exception('Your cruise was already added to this account',400);
                        }
                        else {
                            // create relation with user and booking_no
                            $role_id = $this->_user->roles->role_id;
                            $postVal = [];
                            $postVal['user_id'] = $this->_user->id;
                            $postVal['schedule_id'] = $bookingMap[0]->id;
                            
                            $lastCruiseCreated = \App\UserScheduleMapping::create($postVal);
                            if($lastCruiseCreated){
                                $existing_user = app('App\AssignTourRole')->getListing(['tour_id'=>$bookingMap[0]->tour->id, 'user_id'=>$this->_user->id, 'single_record'=>true]);
                                if(!$existing_user) {
                                    $details = \App\AssignTourRole::create([
                                        'tour_id' => $bookingMap[0]->tour->id,
                                        'user_id' => $this->_user->id,
                                        'role_id' => ($role_id == 2) ? 10 :  $role_id
                                    ]);
                                    //$siteSettings = \App\Helpers\Helper::SiteSettingDetails();                                    
                                    dispatch(new \App\Jobs\NotificationInsertAfterJoinJob($details)); 
                                }
                                $latestCruise = \App\UserScheduleMapping::getListing(['id'=>$lastCruiseCreated->id]);
                                if($latestCruise){
                                    $new_latest_cruise = $latestCruise->toArray();
                                    if($new_latest_cruise['tour_schedule']['tour']){
                                        $tour_id = $new_latest_cruise['tour_schedule']['tour']['id'];
                                        $tour_role = \App\Helpers\Helper::getTourUserRole($this->_user->id,$tour_id);
                                        $new_latest_cruise['tour_schedule']['tour']['tour_role'] = $tour_role;
                                    }
                                    $latestCruise = $new_latest_cruise;
                                }
                            }
                            $tour_id = $bookingMap[0]->tour_id;
                            //\App\AddingNewTourStructureUpdate::create(['user_id' => $this->_user->id,'tour_id' => $tour_id]);
                            \App\Helpers\Helper::updateTourAllFolderStructure($this->_user->id,$tour_id,$role_id);
                            
                            \App\Helpers\Helper::updateSchedueNotificationAfterRoleChanged($role_id,$tour_id,$this->_user->id);
                            
                        }
                        $usrBookedList = \App\UserScheduleMapping::getListing(['user_id'=>$this->_user->id]);
                        $newData = [];
                        foreach($usrBookedList as $key => $val){
                            $new_val = $val->toArray();
                            if(isset($new_val['tour_schedule']['tour'])){
                                $tour_id = $new_val['tour_schedule']['tour']['id'];
                                $tour_role = \App\Helpers\Helper::getTourUserRole($this->_user->id,$tour_id);
                                $new_val['tour_schedule']['tour']['tour_role'] = $tour_role;
                            }
                            $newData[] = $new_val;
                        }
                        return response()->json([
                            'success' => true,
                            'msg' => 'Your cruise has been added.  Also, review the added Tips/News section on the homepage.',
                            'data' => $newData,
                            'latestCruise' => $latestCruise
                        ], 200);
                    }
                    else {
                        throw new Exception('Your Reservation was not found, please verify your information and retry. If the problem persists, please',400);
                    }
                }
                else {
                    throw new Exception('Your Reservation was not found, please verify your information and retry. If the problem persists, please',400);
                }
            }
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }

    public function deleteBooking(Request $request)
    {
        try {
            $input = $request->all();
            $schdeules = \App\UserScheduleMapping::getListing(['user_id'=>$this->_user->id, 'tour_id'=>$input['tour_id']]);
            foreach($schdeules as $key=>$val){
                if($val->tourSchedule->tour_id==$input['tour_id']){
                    \App\UserScheduleMapping::where('id',$val->id)->update(['status'=>0,'deleted_at'=>now()]);
                    $tourFiles = \App\TourInfo::where('tour_id',$input['tour_id'])->pluck('id')->toArray();
                    \App\UserFileRead::where('user_id',$this->_user->id)->whereIn('file_id',$tourFiles)->delete();
                    \App\AssignTourRole::where('user_id', $this->_user->id)->where('tour_id',$input['tour_id'])->delete();
                    \App\UserNotification::where('tour_id', $input['tour_id'])->where('user_id', $this->_user->id)->delete();
                }
            }
            $role_id = $this->_user->roles->role_id;
            \DB::table('user_notifications')->where(['tour_id' => $input['tour_id'],'user_id' => $this->_user->id, 'status' => 0])->delete();
            return response()->json([
                'success' => true,
                'msg' => 'Booking deleted successfully.',
                'data' => null
            ], 200);
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }

    public function createTicket(Request $request)
    {
        try {
            $input = $request->all();
            $user = User::where('id',$this->_user->id)->first();
            $ticket_no = Str::random(15);
            $siteSettings = \App\Helpers\Helper::SiteSettingDetails();

            if(!empty($user)){
                // Send email to Admin
                $mailDataAdmn = [
                    'traveller_name' => $user->first_name,
                    'ticket_no' => $ticket_no,
                    'user_fullname' => trim($user->first_name . ' ' . $user->last_name),
                    'user_email' => $user->email,
                    'user_phone' => $user->phone,
                    'comment' => $input['comment']
                ];
                $fullNameAdmn = 'Administrator';
                Helper::SendMail($siteSettings['contact_us_mail'],$fullNameAdmn,$mailDataAdmn,'create_ticket_admin');
                
                // Send email to Traveller
                $mailDataTrvl = [
                    'traveller_name' => $user->first_name,
                    'ticket_no' => $ticket_no,
                    'comment' => $input['comment']
                ];
                $fullNameTrvl = $user->first_name . ' ' . $user->last_name;
                Helper::SendMail($user->email,$fullNameTrvl,$mailDataTrvl,'create_ticket_traveller');
                
                /*return Helper::makeResponse([
                    'message'   => 'Password recovery email has been sent to you.'
                ], 200);*/

                return response()->json([
                    'success' => true,
                    'msg' => 'Your message has been sent to the AotS Home Office.',
                    'data' => null
                ], 200);
            }
            else{
                throw new Exception('Data not found',200);
            }
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }

    public function myCruiseList(Request $request)
    {
        try {           
            $groupIds = \App\UserScheduleMapping::ScheduleGroupByTour(['user_id'=>$this->_user->id,'tour_group'=>1,'tour_status' => 1]);
            //dd($groupIds);
            if(count($groupIds)) {
                $ids = [];
                $data = [];
                foreach ($groupIds as $key => $value) {
                    $ids[] = $value->id;
                    $data[] = \App\UserScheduleMapping::getListing(['id'=>$value->id]);
                }
                //$usrBookedList = \App\UserScheduleMapping::getListing(['user_id'=>$this->_user->id,'id'=>$ids]);
                if(count($data)) {
                    return response()->json([
                        'success' => true,
                        'msg' => 'User booking list with cruise info',
                        'data' => $data
                    ], 200);
                }
                else {
                    throw new Exception('Data not found',200);
                }
            }
            else {
                throw new Exception('Data not found',200);
            }

            
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }

    public function myPastCruiseList(Request $request){
        try{
            $input = $request->all();
            $currentDate = date('Y-m-d');
            $filedetails = [];
            $groupIds = \App\UserScheduleMapping::ScheduleGroupByTour(['user_id'=>$this->_user->id,'tour_group'=>1,'date'=>$currentDate,'past_cruise'=>true,'order_by'=>'tours.start_date','order_type'=>'DESC','tour_status' => 1]);
            if(count($groupIds)) {
                $ids = [];
                $data = [];
                foreach ($groupIds as $key => $value) {
                    $ids[] = $value->id;
                    $data[] = \App\UserScheduleMapping::getListing(['id'=>$value->id]);
                }
                if(count($data)) {
                    return response()->json([
                        'success' => true,
                        'msg' => 'User past cruise info',
                        'data' => $data
                    ], 200);
                }
                else {
                    throw new Exception('Data not found',200);
                }
            }
            else {
                throw new Exception('Data not found',200);
            }
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }
    public function myCurrentCruiseList(Request $request){
        try{
            $input = $request->all();
            $currentDate = date('Y-m-d');
            $filedetails = [];
            $groupIds = \App\UserScheduleMapping::ScheduleGroupByTour(['user_id'=>$this->_user->id,'tour_group'=>1,'date'=>$currentDate,'current_cruise'=>true,'order_by'=>'tours.start_date','order_type'=>'DESC','tour_status' => 1]);
            if(count($groupIds)) {
                $ids = [];
                $data = [];
                foreach ($groupIds as $key => $value) {
                    $ids[] = $value->id;
                    $data[] = \App\UserScheduleMapping::getListing(['id'=>$value->id]);
                }
                if(count($data)) {
                    return response()->json([
                        'success' => true,
                        'msg' => 'User current cruise info',
                        'data' => $data
                    ], 200);
                }
                else {
                    throw new Exception('Data not found',200);
                }
            }
            else {
                throw new Exception('Data not found',200);
            }
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }
    public function myCurrentFutureCruiseList(Request $request){
        try{
            $input = $request->all();
            $currentDate = date('Y-m-d');
            $filedetails = [];
            $groupIds = \App\UserScheduleMapping::ScheduleGroupByTour(['user_id'=>$this->_user->id,'tour_group'=>1,'date'=>$currentDate,'current_future_cruise'=>true,'order_by'=>'tours.start_date','order_type'=>'ASC','tour_status' => 1]);
            if(count($groupIds)) {
                $ids = [];
                $data = [];
                foreach ($groupIds as $key => $value) {
                    $ids[] = $value->id;
                    $data[] = \App\UserScheduleMapping::getListing(['id'=>$value->id]);
                }
                if(count($data)) {
                    return response()->json([
                        'success' => true,
                        'msg' => 'User upcoming cruise info',
                        'data' => $data
                    ], 200);
                }
                else {
                    throw new Exception('Data not found',200);
                }
            }
            else {
                throw new Exception('Data not found',200);
            }
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }
    public function myFutureCruiseList(Request $request){
        try{
            $input = $request->all();
            $currentDate = date('Y-m-d');
            $filedetails = [];
            $groupIds = \App\UserScheduleMapping::ScheduleGroupByTour(['user_id'=>$this->_user->id,'tour_group'=>1,'date'=>$currentDate,'future_cruise'=>true,'order_by'=>'tours.start_date','order_type'=>'ASC','tour_status' => 1]);
            if(count($groupIds)) {
                $ids = [];
                $data = [];
                foreach ($groupIds as $key => $value) {
                    $ids[] = $value->id;
                    $data[] = \App\UserScheduleMapping::getListing(['id'=>$value->id]);
                }
                if(count($data)) {
                    return response()->json([
                        'success' => true,
                        'msg' => 'User upcoming cruise info',
                        'data' => $data
                    ], 200);
                }
                else {
                    throw new Exception('Data not found',200);
                }
            }
            else {
                throw new Exception('Data not found',200);
            }
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }

    public function getCruiseInfoStructure(Request $request){
        try {
            $validations = [
                'tour_id'   => 'required'
            ];
            $validator = \Validator::make($request->all(), $validations);
			if ($validator->fails()) {
				throw new Exception($validator->errors()->first(),400);
			}
			else{
                $userInfo = Auth::user();
                $input = $request->all();
                $file_view_type = (isset($input['view_type']))?$input['view_type']:0;                
                $input['with_role'] = \App\Helpers\Helper::getTourUserRole($userInfo->id, $input['tour_id']); //$userInfo->roles->role_id;
                if($file_view_type==0){
                    $structure = Helper::getTourInfoStructureRecursiveParent($input['tour_id'],0,$input['with_role'],[0,2]);
                
                }
                else{
                    // dd($structureIds);
                    $structureIds = Helper::getAllFileLinkIdsByTour($input['tour_id'],0,$input['with_role'],[0,2],'',[],$userInfo->id);
                    $structure = \App\TourInfo::getListing(['ids'=>$structureIds,'with'=>[],'order_by'=>'name','order_type'=>'ASC','with_role'=>$input['with_role']]);
                }
                $tourObj = new \App\Tour();
                $tourObj->setGlobalLoggedinUserId($userInfo->id);
                $tourDetails = $tourObj->getListing(['deleted_at'=>NULL,'id'=>$input['tour_id']]);
                $return = [];
                $return['tourDetails'] = $tourDetails;
                $return['structure'] = $structure;
                $return['view_type'] = $file_view_type;
                return response()->json([
                    'success' => true,
                    'msg' => 'Cruise information structure',
                    'data' => $return
                ], 200);
            }
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }

    public function getCruiseChildInfoStructure(Request $request)
    {
        try {
            $input = $request->all();
            $validations = [
                'tour_id'   => 'required',
                'id' => 'required'
            ];
            $validator = \Validator::make($request->all(), $validations);
			if ($validator->fails()) {
				throw new Exception($validator->errors()->first(),400);
			}
			else{
                // User Role Checking:: 4=>Staff; 5=>Guest; 6=>Group Leader
                $userInfo = Auth::user();
                $input['with_role'] = \App\Helpers\Helper::getTourUserRole($userInfo->id, $input['tour_id']); //$userInfo->roles->role_id;

                // update folder tickbox option
                // $structureIds = Helper::getAllFileLinkIdsByTour($input['tour_id'],$input['id'],$input['with_role'],[0,2],'',[],$userInfo->id);
                // Helper::updateFolderHasCheckOptions($userInfo->id,$input['with_role'],$structureIds);
                
                $input['with'] = ['tour'];
                $structure = \App\TourInfo::getListing($input);
                $input['with'] = [];
                $input['parent_id'] = $input['id'];
                unset($input['id']);
                if($structure) {                    
                    $childs = Helper::getTourInfoStructureRecursiveParent($input['tour_id'], $input['parent_id'],$input['with_role']);
                    //$structure->child_nodes = \App\TourInfo::getListing($input);
                    $structure->child_nodes = $childs;
                    $structure->uid = $this->_user->id;
                    $parent_details = null;
                    if(isset($input['parent_details']) && $input['parent_details']){
                        $parent_details = \App\TourInfo::getListing(['tour_id' => $input['tour_id'],'id' => $structure->parent_id,'with' => []]);
                    }
                    $structure->parent_details = $parent_details;
                    return response()->json([
                        'success' => true,
                        'msg' => 'Cruise information structure',
                        'data' => $structure
                    ], 200);
                }
                else {
                    throw new Exception('Data not found',200);
                }
            }
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }
    public function getCruiseChildInfoTreeStructure(Request $request)
    {
        try {
            $input = $request->all();
            $validations = [
                'tour_id'   => 'required'
            ];
            $validator = \Validator::make($request->all(), $validations);
			if ($validator->fails()) {
				throw new Exception($validator->errors()->first(),400);
			}
			else{
                $userInfo = Auth::user();
                /*Tour Details **/
                $tourObj = new \App\Tour();
                $tourObj->setGlobalLoggedinUserId($userInfo->id);
                $tourDetails = $tourObj->getListing(['id' => $input['tour_id']]);
                $data['tourDetails'] = $tourDetails;
                $user_role_id = $tourDetails ? $tourDetails->tour_role : null; //\App\Helpers\Helper::getTourUserRole($userInfo->id, $input['tour_id']);
                /** Check parent id . If not parent id the set parent id is 0 */
                $input['parent_id'] = (isset($input['parent_id']))?$input['parent_id']:0;

                /**  User Role Checking:: 4=>Staff; 5=>Guest; 6=>Group Leader*/
                
                $input['with_role'] = $user_role_id; //$userInfo->roles->role_id;

                /*get parent folder Details. If parent folder is 0 then return null **/
                $tourInfoCondition = $input;
                $tourInfoCondition['id'] = $tourInfoCondition['parent_id'];
                $tourInfoCondition['with'] = [];
                unset($tourInfoCondition['parent_id']);
                $data['parentFolderDetails'] = \App\TourInfo::getListing($tourInfoCondition);

                /**  update folder tickbox option For all Child folder and files */ 
                // $structureIds = Helper::getAllFileLinkIdsByTour($input['tour_id'],$input['parent_id'],$input['with_role'],[0,2],'',[],$userInfo->id);
                // Helper::updateFolderHasCheckOptions($userInfo->id,$input['with_role'],$structureIds);
                
                /**
                 *  Fetch all folder and files from Tourinfo table reapsect of parent id and tour id.
                 *  If parent id is 0 then return all root folder of specific tour
                */
                /**
                 * Fetch all parent folder and files 
                 * if get parent id from input otherwise parent id is 0
                 */
                /**
                 * Comment for optimization
                 *                  
                    $structureCondition = $input;
                    $structureCondition['with'] = [];
                    $structures = \App\TourInfo::getListing($structureCondition);
                */
                /**
                 * Set all child folder and files recursive
                 * if has folder then call recursive. otherwise not 
                 *  we set all child in another nodes
                */
                /**
                 * Comment for optimization
                foreach($structures as $key=>$val){
                    if($val->file_type == 1){
                        $childs = Helper::getTourInfoStructureRecursiveParentWithTree($input['tour_id'], $val->id,$input['with_role']);
                        $val->child_nodes = $childs;
                    }
                    else{
                        $val->child_nodes = null;
                    }
                }
                */
                $structures = Helper::getTourInfoStructureRecursiveParentWithTree($input['tour_id'], $input['parent_id'],$input['with_role']);
                if($structures) {
                    $data['structure'] = $structures;
                    return response()->json([
                        'success' => true,
                        'msg' => 'Cruise information structure',
                        'data' => $data
                    ], 200);
                }
                else {
                    throw new Exception('Data not found',200);
                }
            }
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }
    public function getModifiedFileFolderDetails(Request $request){
        try{
            $input = $request->all();            
            $validations = [
                'file_id'   => 'required|integer',
                'root_file_id' =>'required|integer',
                'tour_id' => 'required|integer',
                'method' => 'required',
                'type' => 'required|integer',
            ];
            $validator = \Validator::make($request->all(), $validations);
			if ($validator->fails()) {
				throw new Exception($validator->errors()->first(),400);
			}
			else{    
                $req_from = isset($input['req_from']) ? $input['req_from'] : 1;            
                $input['user_id'] = $this->_user->id;
                $input['with_role'] = \App\Helpers\Helper::getTourUserRole($input['user_id'], $input['tour_id']); //$this->_user->roles->role_id;
                \App\ModificationFileExecutedByUser::create($input);
                $groupIds = \App\UserScheduleMapping::ScheduleGroupByTour(['user_id'=>$this->_user->id,'tour_group'=>1,'tour_id'=>$input['tour_id'],'tour_status' => 1]);
                if(count($groupIds)) {
                    if($input['method'] == "UPDATE"){
                        $file_details = \App\TourInfo::getListing(['select'=>['id','parent_id','file_type'],'id'=>$input['file_id'],'with'=>[]]);
                        if($file_details){
                            $input['file_parent_id'] = $file_details->parent_id;
                            $input['file_type'] = $file_details->file_type;
                            if($input['type'] !=1){
                                $res = Helper::checkUncheckReadFile($input['user_id'],$input['file_id'],null,$input['method'],0,$input['with_role'],0,$input['with_role']);
                            }
                            else{
                                $structureIds = Helper::getAllTourFileLinkIdsGroupByParent($input['tour_id'],$input['root_file_id'],$input['with_role'],[0,2],'',[],$input['user_id']);
                                Helper::updateFolderHasCheckOptions($input['user_id'],$input['with_role'],$structureIds);
                            }
                        }
                        else{
                            throw new Exception('File details not found',404);
                        }
                    }
                    else{
                        $res = Helper::checkUncheckReadFile($input['user_id'],$input['file_id'],null,$input['method']);
                    }
                    $view_type = (isset($input['view_type']))?$input['view_type']:0;
                    $root_details = false;
                    $order_change = false;
                    $structures = [];
                    $parentId = $input['root_file_id'];
                    if($view_type == 0){                        
                        if(isset($input['order_changed']) && $input['order_changed'] == 1){
                            $parentId = 0;
                            $order_change = true;
                        }
                        $root_details = true;
                        $structures = Helper::getTourInfoStructureRecursiveParentWithTree($input['tour_id'], $parentId, $input['with_role'],[0,2],true);
                       
                    }
                    else if($view_type == 1) {
                        $structureIds = Helper::getAllFileLinkIdsByTour($input['tour_id'],0,$input['with_role'],[0,2],'',[],$input['user_id']);
                        $structures = \App\TourInfo::getListing(['ids'=>$structureIds,'with'=>[],'order_by'=>'name','order_type'=>'ASC','with_role'=>$input['with_role']]);
                    }
                    else{
                        $structures = \App\TourInfo::getListing(['id' => $input['root_file_id'], 'with_role' => $input['with_role'], 'with' => ['tour'],'tour_id' => $input['tour_id']]);
                        if($structures){
                            $structures->child_nodes = Helper::getTourInfoStructureRecursiveParent($input['tour_id'], $input['root_file_id'],$input['with_role']);
                        }                        
                    }
                    if(($req_from == 2) && !empty($parentId) && $root_details){
                        $structures = [$structures];
                    }
                    if($structures){
                        return response()->json([
                            'success' => true,
                            'msg' => 'Updated successfully',
                            'data' => $structures
                        ], 200);
                    }
                    else{
                        throw new Exception('File details not found',404);
                    }
                }
                else{
                    throw new Exception('Tour not found ',403);
                }
            }
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }

    public function readUnreadFile(Request $request){
        try{
            $input = $request->all();
            $validations = [
                'file_id'   => 'required|integer',
                'status' =>'required|integer'
            ];
            $validator = \Validator::make($request->all(), $validations);
			if ($validator->fails()) {
				throw new Exception($validator->errors()->first(),400);
			}
			else{ 
                $input['user_id'] = $this->_user->id;
                $file_details = \App\TourInfo::getListing(['select'=>['id','tour_id','parent_id','file_type'],'id'=>$input['file_id'],'with'=>[]]);
                if($file_details){
                    $input['with_role'] = \App\Helpers\Helper::getTourUserRole($input['user_id'], $file_details->tour_id); //$this->_user->roles->role_id;
                    $root_file_id = \App\Helpers\Helper::getRootFileId($file_details->id);
                    //dd($root_file_id);
                    $input['file_parent_id'] = $file_details->parent_id;
                    $input['file_type'] = $file_details->file_type;
                    $view_type = (isset($input['view_type']))?$input['view_type']:0;
                    $res = Helper::checkUncheckReadFile($input['user_id'],$input['file_id'],$input['status'],'UPDATE',0,$input['with_role']);
                    if($view_type == 0){
                        $structures = Helper::getTourInfoStructureRecursiveParentWithTree($file_details->tour_id, $root_file_id, $input['with_role'],[0,2],true);
                    }
                    else{
                        $structureIds = Helper::getAllFileLinkIdsByTour($file_details->tour_id,0,$input['with_role'],[0,2],'',[],$input['user_id']);
                        $structures = \App\TourInfo::getListing(['ids'=>$structureIds,'with'=>[],'order_by'=>'name','order_type'=>'ASC','with_role'=>$input['with_role']]);
                    }  
                    return response()->json([
                        'success' => true,
                        'msg' => 'Updated successfully',
                        'data' => $structures
                    ], 200);
                }
                else{
                    throw new Exception('File details not found',400);
                }
            }
        } catch (\Exception $e) {
            return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        }
    }
    
    public function dailyFolderFile(Request $request){
        // try {
            $input = $request->all();
            $currentDate = date('Y-m-d');
            $filedetails = null;
            $tourIds = \App\UserScheduleMapping::ScheduleGroupByTour(['user_id'=>$this->_user->id,'tour_group'=>1,'date'=>$currentDate,'current_cruise'=>true])->pluck('tour_id')->toArray();
            
            if(count($tourIds)){
                $userInfo = Auth::user();
                $input['with_role'] = $userInfo->roles->role_id;
                $input['tour_id'] = $tourIds;
                $input['user_id'] = $userInfo->id;
                $filedetails = \App\TourInfo::getDailyFolderFileList($input);
            }
            return response()->json([
                'success' => true,
                'msg' => 'Cruise information structure',
                'data' => $filedetails
            ], 200);
        // } catch (\Exception $e) {
        //     return response()->json(['success'=>false,'msg' => $e->getMessage()], $e->getCode());
        // }
    }
}