<?php

namespace App\Http\Middleware;

use Closure;
use Redirect;
use Illuminate\Http\Request;
use App\Models\Ticket;
use App\Models\Office;


class CanEditTicket
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $office=Office::find(auth()->user()->office->id);
        $path_parts=explode('/',url()->full());
        $ticket_number=$path_parts[4];
     
          $ticket=   Ticket::where('ticket_number',$ticket_number)->first();
        if($office->is_admin==0){
            $tickets=   Ticket::whereHas('segment.booking', function ($query) {
                            $query->where('office_id', auth()->user()->office->id);
                        })->pluck('ticket_number')->toarray();
       
        }
        else{
            $tickets= Ticket::pluck('ticket_number')->toarray();
        }

         if(in_array($ticket_number, array_values($tickets))  ){
               $date = $ticket->created_at;
              if ($date->endOfDay() < now() ){
                      $date2 = $ticket->segment->cruise->departure_date_time;
                    // dd($date2);
                      if($date2->modify('-1 hour') > now()){
                          return $next($request);
                      }
                      else{
                          return abort(404);
                      }
            
              }
              else{
                   return abort(404);
              }
                     
         }
                  
        
         else{
                 return abort(404);

         }
       
                    
    }
}
