<?php

namespace App\Models;

use App\Traits\Uniqid;
use App\Models\Office;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Booking extends Model
{
    use HasFactory, Uniqid;

    const ‫‪STATE_OPEN‬‬ = 'O';
    const STATE_‫‪USED‬‬ = '‫‪U‬‬';
    const STATE_‫‪VOID‬‬ = 'V';
    const STATE_‫‪REFUNDED‬‬ = 'R';
    const STATE_‫‪EXCHANGED‬‬ = 'E';

    protected $fillable = [
        'office_id', 'status', 'number', 'old_id'
    ];

    public function office()
    {
        return $this->belongsTo(Office::class);
    }


    public function segments()
    {
        return $this->hasMany(TravelSegment::class);
    }

    public function tickets()
    {
        return $this->hasManyThrough(Ticket::class, TravelSegment::class, 'booking_id', 'segment_id');
    }

    public function services()
    {
        return $this->hasManyThrough(SegmentService::class, TravelSegment::class, 'booking_id', 'segment_id');
    }

    public function passengers()
    {
       return $this->tickets->groupBy('passport');
    }

    function getTotalServiceAttribute()
    {
        return $this->tickets->sum('total_service');
    }

    function getTotalAttribute()
    {
        return $this->tickets->sum('total');
    }

    function getOldTotalAttribute()
    {
        return $this->tickets->sum('old_total');
    }
    ///////////حساب جميع التذاكر 
    public function amountPaid(){
        $s = 0;
         foreach ($this->tickets as $ticket) {
            $s += $ticket->amountPaid();

        }
        return $s;
    }

    protected static function booted()
    {
        $office_id=auth()->user()->office_id;
        if($office_id!=null){
            $office=Office::find($office_id);
            if($office->is_admin	==0){
              static::addGlobalScope('officeUser', function ($builder) {
                if(auth()->check() && auth()->user()->office && !auth()->user()->isSuperAdmin()){
                    $builder->where('office_id',auth()->user()->office->id);
                }
            });
            }
        }
    }
}
