<?php

namespace App\Http\Controllers;

use App\Models\BoardingPass;
use App\Models\Cruise;
use Illuminate\Http\Request;

class CheckInController extends Controller
{
    public function  index(Cruise $cruise)
    {
        return view('check_in.index', compact('cruise'));
    }

    public function list(Cruise $cruise)
    {
        $query =  BoardingPass::whereNotNull('checked_at')->with(['ticket.segment' => function ($query) use ($cruise) {
            $query->where('cruise_id', $cruise->id);
        }]);
        return datatables()
            ->eloquent($query)
            ->addColumn('ticket_number', function ($item) {
                return $item->ticket?$item->ticket->ticket_number:'--';
            })
            ->addColumn('first_name', function ($item) {
                return $item->ticket?$item->ticket->firstName:'--';
            })
            ->addColumn('last_name', function ($item) {
                return $item->ticket?$item->ticket->lastName:'--';
            })
            ->addColumn('passport_number', function ($item) {
                return $item->ticket?$item->ticket->passport:'--';
            })
            ->addColumn('phone_number', function ($item) {
                return $item->ticket?$item->ticket->phone:'--';
            })
            ->addColumn('cruise', function ($item) use($cruise) {
                return $cruise->name.'-'.$cruise->cruise_number;
            })
            ->make();
    }

    public function checkIn(Request $request, Cruise $cruise)
    {
        $boardingPass  = BoardingPass::with(['ticket.segment' => function ($query) use ($cruise) {
            $query->where('cruise_id', $cruise->id);
        }])->where('code', $request->code)->firstOrFail();
        $boardingPass->checked_at = now();
        $boardingPass->save();
        return $boardingPass;
    }
}
