<?php

namespace App\Http\Controllers;

use App\DataTables\BookingDataTable;
use App\Jobs\PayementBooking;
use App\Jobs\RefundSegment;
use App\Jobs\RefundBooking;
use App\Jobs\Refund1Booking;
use App\Models\Booking;
use App\Models\Transaction;

use App\Models\SegmentService;
use App\Models\Service;
use App\Models\Ticket;
use App\Models\TravelSegment;
use App\Traits\Currencies;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class BookingController extends Controller
{
    use Currencies;

    private $booking;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(BookingDataTable $dataTable)
    {
        return $dataTable->render('booking.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $request->session()->put('card.passengers',[]);
        $price_child = $this->convertCurrency(config('booking.price_bed_child')*100);
         return view('booking.create',['price_child'=>$price_child]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
         if($request->has_retour==true){
            $is_two_way=1;/////حجز ذهاب واياب 
        }
        else{
            $is_two_way=0;

        }
        $booking = $request->booking;

        $user = Auth::user();
        $data = [
            'office_id' => $user->office_id,
            'status' => Booking::‫‪STATE_OPEN‬‬,
            'number' =>  Booking::uniqid("BN-"),
        ];

        DB::transaction(function () use ($data, $booking, $request,$is_two_way) {
            $created_booking = Booking::create($data);
            foreach ($booking['segments'] as $item) {
                $room_type = $item['room_type'];
                if (!$room_type) continue;
                $db_room_type = Service::findOrFail($room_type['service_id']);
                $price_bed = $request->has_retour? $db_room_type->price_two : $db_room_type->price; 
                $segment = TravelSegment::create([
                    'booking_id' => $created_booking->id,
                    'cruise_id' => $room_type['cruise_id'],
                    'room_type_id' => $db_room_type->room_type_id,
                ]);
                $tickets = [];
                foreach ($request->session()->get('card.passengers') as $passenger) {
                    if(empty($passenger['called']))unset($passenger['called']);
                    $data = array_merge($passenger, [
                        'segment_id'   => $segment->id,
                        'price' =>  $passenger['is_child']?config('booking.price_bed_child')*100: $price_bed,
                        'ticket_number' => Ticket::uniqid("ET-"),
                        'ticket_status_code' => Ticket::‫‪STATE_OPEN‬‬,
                        'is_two_way'=>$is_two_way
                    ]);
                    $tickets[$passenger['passport']] = Ticket::create($data);
                }
                // dd( $tickets[$passenger['passport']]);
                foreach ($item['services'] as $service) {
                    $db_service = Service::findOrFail($service['id']);
                    $service['segment_id'] = $segment->id;
                    $price_car = $request->has_retour? $db_service->price_two : $db_service->price; 

                    $service['price'] = $price_car;
                    $service['article_id'] = $db_service->article_id;
                    $service['car_id'] = $db_service->car_id;
                    $service['ticket_id'] = $service['passenger_passport'] ? $tickets[$service['passenger_passport']]->id: null;         
                    $service['details'] = $service['details'] ?? [];
                    $service['ticket_number'] = SegmentService::uniqid("EST-");
                    SegmentService::create($service);
                }

            }
            $request->session()->put('card.passengers',[]);
            $this->booking =  $created_booking;
        });

        try {
            $this->dispatch(new PayementBooking($this->booking));
        } catch (\Throwable $th) {
            $this->booking->delete();
            abort(500, $th);
        }

        return $this->booking;
    }

    public function print($id)
    {
       
        $booking = Booking::findOrFail($id);
        // dd( $booking);
        return view('booking.print', ['booking' => $booking]);

    }

    public function print_ticket($id)
    {
        $ticket = Ticket::findOrFail($id);
        $price_this_ticket = Transaction::where('ticket_id',$id)->first()->amount;
        $booking_id = $ticket->segment->booking_id;
        $booking = Booking::findOrFail($booking_id);
        // dd( $booking);
        return view('booking.print', ['booking' => $booking,'price_this_ticket'=>$price_this_ticket]);
    }

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


    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Booking  $booking
     * @return \Illuminate\Http\Response
     */
    public function destroy(Booking $booking)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Booking  $booking
     * @return \Illuminate\Http\Response
     */
    public function refund(Booking $booking)
    {

         $booking->status='V';
         $booking->save();
        foreach ($booking->tickets as $ticket) {
            if( $ticket ->hasRetour()){
                
               $this->dispatch(new RefundBooking($ticket));
                
            }
        }
        return $booking;
    }
    public function refund1(Booking $booking)
    {
        

         $booking->status='R';
         $booking->save();
        foreach ($booking->tickets as $ticket) {
            if( $ticket ->hasRetour() &&$ticket->ticket_status!='U'){
                
               $this->dispatch(new Refund1Booking($ticket));
                
            }
        }
        return $booking;
    }
}
