<?php

namespace App\Models;

use App\Traits\hasCommission;
use App\Traits\hasCurrency;
use App\Traits\Uniqid;
use App\Models\Office;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;
use Fol\Fees\Models\SubjectInterface;

class Ticket extends Model implements  SubjectInterface 
{
    use HasFactory, Uniqid, hasCurrency, hasCommission, LogsActivity;

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


    protected $fillable = [
        'segment_id',
        'old_id',
        'price',
        'commission',
        'tax',
        'tax_office',
        'firstName',
        'lastName',
        'nationality',
        'called',
        'passport',
        'email',
        'phone',
        'address',
        'birth_date',
        'expiry_date',
        'ticket_number',
        'ticket_status',
        'currency_code',
        'exchange_rate',
        'pcrneg',
        'vacc1n_name',
        'vacc1n_date' ,
        'vacc2n_name',
        'vacc2n_date',
        'place_of',
        'gender',
        'diff_price',
        'passport_file',
        'is_two_way'
    ];
    protected $table = 'tickets';

    protected $attributes = [
        'ticket_status' => self::‫‪STATE_OPEN‬‬,
    ];

    protected $currency_attributes = ['price'];

    public function segment()
    {
        return $this->belongsTo(TravelSegment::class, 'segment_id', 'id')->withoutGlobalScopes();
    }

    public function old()
    {
        return $this->belongsTo(Ticket::class, 'old_id', 'id')->withoutGlobalScopes();
    }


    public function refund()
    {
        return $this->hasOne(Refund::class, 'ticket_id', 'id');
    }

    public function boardingPass()
    {
        return $this->hasOne(BoardingPass::class, 'ticket_id', 'id');
    }

    public function transactions()
    {
        return $this->hasMany(Transaction::class, 'ticket_id', 'id');
    }

    public function refundTransaction()
    {
        return $this->hasOne(Transaction::class, 'ticket_id', 'id')->where('type', Transaction::TYPE_INCOME);
    }

    public function payementTransaction()
    {
        return $this->hasOne(Transaction::class, 'ticket_id', 'id')->where('type', Transaction::TYPE_EXPENSE);
    }

    public function services()
    {
        return $this->hasMany(SegmentService::class, 'ticket_id', 'id');
    }

    public function car()
    {
        return $this->hasOne(SegmentService::class, 'ticket_id', 'id')->whereNotNull('car_id');
    }

    public function getFullNameAttribute()
    {
        return $this->firstName . ' ' . $this->lastName;
    }

    function getTotalServiceAttribute()
    {
        return $this->services->sum('total');
    }


    function getTotalAttribute()
    {
        return $this->price + $this->total_service;
    }

    function getOldTotalAttribute()
    {
        return $this->old ? $this->old->total : 0;
    }


    public function gettotalNetAttribute()
    {
         return  $this->total *  (1 - $this->commission / 100);
    }

    public function isChild()
    {
        return $this->called == 'Inf';
    }

    public function price_reissued()
    {

    }

    public function amountPaid()
    {
        if ($this->old && $this->old->ticket_status == self::STATE_‫‪EXCHANGED‬‬) {
            //////////// اذا كان طفل اعطي القيمة صفر -  اذا لم يكن طفل 
            $total = $this->isChild() ? 0 : $this->old->tax_office+$this->old->tax;
            if ($this->old->total < $this->total) {
                $total += $this->total - $this->old->total;
            }
            return $total;
        }
        // dd($this->total);
        return $this->total;
    }

    public function amountRefunded($refund=null)
    {
        if ($this->ticket_status == self::STATE_‫‪VOID‬‬) {
            return   $this->total;
        } elseif ($this->ticket_status == self::STATE_‫‪REFUNDED‬‬) {
           $total= $this->total - ($this->isChild() ? 0 : $this->tax_office+$this->tax);
           return $total;
        }
         if($refund ='R'){
             $total= $this->total - ($this->isChild() ? 0 : $this->tax_office+$this->tax);
             return $total;

         }

        return 0;
    }

    public function amountNetPaid()
    {
         if ($this->old && $this->old->ticket_status == self::STATE_‫‪EXCHANGED‬‬) {
            $total_net = $this->isChild() ? 0 : $this->old->tax;
            if ($this->old->total < $this->total) {
                $total_net += $this->total_net - $this->old->total_net;
            }
            return $total_net;
        }
         return $this->total_net;
    }

    public function amountNetRefunded($refund=null)
    {
        if ($this->ticket_status == self::STATE_‫‪VOID‬‬) {
            return   $this->total_net;
        } elseif ($this->ticket_status == self::STATE_‫‪REFUNDED‬‬) {
            return $this->total_net - ( $this->isChild() ? 0 : $this->tax);
        }
      if($refund ='R'){
        return $this->total_net - ( $this->isChild() ? 0 : $this->tax);

     }
        

    }


    protected static function booted()
    {
        // $office_id=auth()->user()->office_id;
      
        // if($office_id!=null)
        // {
        //   $office=Office::find($office_id);
        // //   dd($office);
        //  if(auth()->user()->office->is_admin	 ==0){
             
        //     static::addGlobalScope('officeUser', function ($builder) {
        //         if (auth()->check() && auth()->user()->office ) {
        //             $builder->whereHas('segment.booking', function ($query) {
        //                 $query->where('office_id', auth()->user()->office->id);
        //             });
        //         }
        //     });
    
        //     static::addGlobalScope('status', function ($builder) {
        //         $builder->whereNotIn('ticket_status', [self::STATE_‫‪VOID‬‬, self::STATE_‫‪REFUNDED‬‬, self::STATE_‫‪EXCHANGED‬‬]);
        //     });
        //   }
        // }
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['ticket_status']);
    }
    
   public function getCheckerDate(): \DateTime{
      return $this->segment->cruise->departure_date_time;
   }
//   public function getPassportFileAttribute(){
//       return public_path('uploads/passport').$this->passport_file;
//   }
   
   public function getCheckerStatus(): string{
      return $this->ticket_status;
   }
   
    function hasRetour(){
        if($this->old)return $this->old->hasRetour();
        $booking = $this->segment->booking;
        return TravelSegment::withoutGlobalScopes()->where('booking_id','=',$booking->id)->count()>1?true:false;
    }
    public function oldtTicket()
    {
        return $this->belongsto(Ticket::class, 'old_id', 'id');
    }
    
    // function hasRetourStatus(){
    //     if($this->old){
    //         return $this->old;
        
    //     }
    // }
}
