<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Cruise extends Model
{
    use HasFactory, LogsActivity;


    protected $fillable = [
        'name', 'cruise_number', 'ship_id', 'origin_port', 'destination_port', 'departure_date_time', 'arrival_date_time', 'weight', 'bags', 'status'
    ];

    protected $casts = [
        'departure_date_time' => 'datetime',
        'arrival_date_time' => 'datetime'
    ];

    public function ship()
    {
        return $this->belongsTo(Ship::class);
    }

    public function roomTypes()
    {
        return RoomType::with('service')->withCount(['rooms', 'tickets'=> function ( $query) {
        //   $query ->whereHas('tickets', function ($query) {
                $query->where('ticket_status', '=','O')
                   
            // })
                    ->whereHas('segment',function($query){
                        $query->where('cruise_id', '=',  $this->id);
                    });
                }])
            
            ->whereHas('service', function ($query) {
                $query->where('ship_id', $this->ship_id)
                    ->where('origin_port', $this->origin_port)
                    ->where('destination_port', $this->destination_port)
                    ->where('status',1);
            });
    }

    public function services()
    {
        return Service::with(['car', 'article'])->where('ship_id', $this->ship_id)
            ->where('origin_port', $this->origin_port)
            ->where('destination_port', $this->destination_port)
            ->whereNull('room_type_id')
            ->where('status',1);
    }

    public function originPort()
    {
        return $this->belongsTo(Port::class, 'origin_port', 'code');
    }

    public function destinationPort()
    {
        return $this->belongsTo(Port::class, 'destination_port', 'code');
    }


    public function getDepartureDateAttribute()
    {
        return  $this->departure_date_time->toDateString();
    }

    public function getDepartureTimeAttribute()
    {
        return  $this->departure_date_time->toTimeString();
    }

    public function getArrivalDateAttribute()
    {
        return  $this->arrival_date_time->toDateString();
    }

    public function getArrivalTimeAttribute()
    {
        return  $this->arrival_date_time->toTimeString();
    }

    public function getRouteAttribute()
    {
        return $this->origin_port . '-' . $this->destination_port;
    }

    
    public function getActivitylogOptions():LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['name', 'cruise_number']);
    }
}
