<?php

namespace App\Http\Controllers;

use App\DataTables\TicketDataTable;
use App\Jobs\PayementBooking;
use App\Jobs\ReissuedTicket;
use App\Jobs\VoidTicket;
use App\Jobs\RefundSegment;
use App\Jobs\RefundTicket;
use App\Models\Booking;
use App\Models\SegmentService;
use App\Models\Service;
use App\Models\Ticket;
use Carbon\Carbon;
use App\Models\TravelSegment;
use App\Traits\Currencies;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TicketController extends Controller
{
    use Currencies;
     public function __construct() {

       
    }
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(TicketDataTable $dataTable)
    {
            $office_id=auth()->user()->office_id;
            
            // $tikects=   Ticket::whereHas('segment.booking', function ($query) {
            //             $query->where('office_id', auth()->user()->office->id);
            //         })->pluck('id')->toarray();
                    
                    
            // return $tikects;
           

        return $dataTable->render('tickets.index');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    public function editPassenger(Ticket $ticket)
    {
       if(auth()->user()->can('pessanger_edit')){
            $nationalities = 'nationalities';
            $nationalities= explode(',',config('app.'.$nationalities));
            return view('tickets.edit_passenger',compact('ticket','nationalities'));
       }
        return abort(404);


    }
 
    public function updatePassenger(Request $request)
    { 
        $ticket=Ticket::find($request->ticket_id);
        $ticket->update($request->all());
        
        return back();

    }
 
    

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function refund($ticket_number)
    {
     $ticket=Ticket::where('ticket_number',$ticket_number)->first();
     

      return $this->dispatch(new RefundTicket($ticket));
    }
    
    
    public function void($ticket_number)
    {
     $ticket=Ticket::where('ticket_number',$ticket_number)->first();
     

      return $this->dispatch(new VoidTicket($ticket));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function show(Ticket $ticket)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function edit($ticket_number)
    {
        $ticket=Ticket::where('id',$ticket_number)->first();
        // dd($ticket);
        if($ticket){
            $segment= $ticket->segment;
            // "id" => 7795
            
            // "booking_id" => 4207 رقم الحجز
            // "cruise_id" => 41 رقم الرحلة 
            // "room_type_id" => 5 رقم الغرفة
            // "segment_status" => "O" حالة الرحلة
            // "created_at" => "2022-08-24 15:37:06"
            // "updated_at" => "2022-08-24 15:37:06"

            $price_child = $this->convertCurrency(config('booking.price_bed_child')*100);
 
            ////////////رجع الحجز لهذه التذكرة 
            $booking = $ticket->segment->booking;
            //// فحص هل هذه الرحلة ذهاب واياب - فحص عدد السيقمنت لهذا الحجز
            // $has_retour = $booking->segments->count()>1?true:false;
            $has_retour = $ticket->is_two_way == 1?true:false;

//            dd($has_retour->segment);


            return view('tickets.edit', ['ticket'=>$ticket,'segment' => $segment,'price_child' => $price_child,'has_retour'=>$has_retour]);
        }
        else{
            return redirect(route('tickets.index'));
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $ticket_number)
    {  
        $ticket=Ticket::where('id',13000)->first();
         $this->dispatch(new ReissuedTicket($ticket));

        
        /////////// جلب التيكت القديمة 
        $ticket=Ticket::where('ticket_number',$ticket_number)->first();

        /////////// جلب 
         $booking = $ticket->segment->booking;
 
        /////فحص الوجه هل لها اياب
        $has_retour = $ticket->is_two_way = 1?true:false;
        DB::transaction(function () use ($request, $booking,$ticket,$has_retour) {
            //

            // if($booking->tickets->count()>1){

                //// نسخ اخر حجز واضافة حجز جديد
                $booking = $booking->replicate()->fill([
                    'number' => Booking::uniqid("BN-"),
                    //'status' => Booking::‫‪STATE_OPEN‬‬,

                     'status' => Booking::STATE_‫‪EXCHANGED‬‬ ,
                    'office_id'=>auth()->user()->office_id
                ]);
                 $booking->save();
 
                 
    /////// نسخ 
                $new_segment= $ticket->segment->replicate(['laravel_through_key'])->fill([
                        'booking_id'   => $booking->id,
                        'segment_status' => Booking::STATE_‫‪EXCHANGED‬‬
                ]);
                $new_segment->save();
                foreach ($ticket->services as $service) {
                    
                    $new_service = $service->replicate(['laravel_through_key'])->fill([
                        'price' => $service->rate_price,
                        'segment_id' => $new_segment->id,
                        'ticket_number' => SegmentService::uniqid("ETS-")
                    ]);
                    $new_service->save();
                }
    
                $ticket->segment_id  =$new_segment->id;

            // }else{
 
                // $booking->status =  Booking::STATE_‫‪EXCHANGED‬‬;
                // $ticket->segment->segment_status = TravelSegment::STATE_‫‪EXCHANGED‬‬; 
                // $booking->office_id=auth()->user()->office_id;

                // $ticket->segment->save();
                
                // $booking->save();
            
            
            $ticket->ticket_status  =Ticket::STATE_‫‪EXCHANGED‬‬;
            $ticket->save();
            //
            $item = $request->booking['segments']['aller'];

            $room_type = $item['room_type'];
            if ($room_type) {
                $db_room_type = Service::findOrFail($room_type['service_id']);
                $price_bed =$has_retour ? $db_room_type->price_two : $db_room_type->price; 
            //    dd($price_bed);
                $segment = TravelSegment::create([
                    'booking_id' => $booking->id,
                    'cruise_id' => $room_type['cruise_id'],
                    'room_type_id' => $db_room_type->room_type_id,
                ]);
                $segment->save();
                //  dd($ticket->isChild()?config('booking.price_bed_child')*100: $price_bed);
                /////////اعد برمجة التيكت بدون البرايمري كي
                $new_ticket = $ticket->replicate(['laravel_through_key'])->fill([
                    'tax_office' => null,
                    'tax' => null,
                    'old_id' => $ticket->id,
                    'segment_id'   => $segment->id,
                    'price' =>   $ticket->isChild()?config('booking.price_bed_child')*100: $price_bed,
                    'ticket_number' => Ticket::uniqid("ET-"),
                    'ticket_status' => Ticket::‫‪STATE_OPEN‬‬,
                    'is_two_way'=>1
                ]);
                $new_ticket->save();


                foreach ($ticket->services as $service) {
                  //  $price_car =$has_retour?$service->car->price_two :$service->car->price;
                    $price_car =$has_retour?$service->car->service->price_two:$service->car->service->price_two;
                     $new_service = $service->replicate(['laravel_through_key'])->fill([  
                        'price' => $price_car,
                        'segment_id' => $segment->id,
                        'ticket_id' => $new_ticket ->id,
                        'ticket_number' => SegmentService::uniqid("EST-")
                    ]);
                    $new_service->save();
                }
    
            }
            $this->ticket = $new_ticket;
         });
 
        try {
            $this->dispatch(new ReissuedTicket($this->ticket));

         } catch (\Throwable $th) {
            abort(500, $th);
        }

        return  $this->ticket;
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Ticket  $ticket
     * @return \Illuminate\Http\Response
     */
    public function destroy(Ticket $ticket)
    {
        //
    }

    public function search(Request $request){
       
        return Ticket::with(['segment', 'segment.booking'])
                ->whereHas('segment' , function($query)use($request){
                    $query->where('cruise_id',$request->cruise_id);
            })
            ->where('ticket_number','like','%'.$request->q.'%')->orwhere('passport','like','%'.$request->q.'%')->paginate(10);
    }
    
   public function deleteImage(){
    $currentDate = Carbon::now()->format('Y-m-d');
    $tickets=Ticket::whereDate('created_at','<',$currentDate)->where('ticket_status','!=','O')->where('passport_file','!=','O')->get();
    

    foreach($tickets as $ticket){
        if(!$ticket->hasRetour()){
           
            $userPhoto = public_path('uploads/passport/').$ticket->passport_file; 
             if(file_exists($userPhoto)) { 
                @unlink($userPhoto);
          }
            
        }
    }
      return back();

    
  }
  public function searchPassport(Request $request){
       $ticket_number =Ticket::
                whereHas('segment' , function($query)use($request){
                    $query->where('cruise_id',$request->cruise);
            }) ->where('passport','like','%'.$request->passport.'%')->select('ticket_number')->first();
            if($ticket_number){
                
                return $ticket_number;
            }
            else{
                $ticket_number='fails';
                return $ticket_number;
            }
  }
}
