<?php

namespace Modules\Appointment\Entities;

use App\Traits\Tenantable;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Modules\Appointment\Entities\TimeSlot;
use Modules\CourseSetting\Entities\Category;

class Schedule extends Model
{
    use Tenantable;

    protected $fillable = ['schedule_date', 'slot_id', 'user_id', 'category_id', 'sub_category_id',
     'created_by','updated_by'];

    public function userInfo()
    {
        return $this->belongsTo(User::class, 'user_id', 'id')->withDefault();
    }
    public function slotInfo()
    {
        return $this->belongsTo(TimeSlot::class, 'slot_id', 'id')->withDefault();
    }
    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id')->withDefault();
    }
    public function subCategory()
    {
        return $this->belongsTo(Category::class, 'sub_category_id', 'id')->whereNotNull('parent_id')->withDefault();
    }
    public static function teachingInfo($slot_id = null, $date = null, $user_id = null, $firstOrGet = null, $status = null)
    {
        $schedule = Schedule::when(is_int($slot_id), function ($query) use ($slot_id) {
            $query->where('slot_id', $slot_id);
        })->when($status, function ($query) use ($status) {
            $query->where('status', $status);
        })->when($user_id, function ($query) use ($user_id) {
            $query->where('user_id', $user_id);
        })->when($date, function ($query) use ($date) {
            $query->whereDate('schedule_date', $date);
        });
        if ($firstOrGet) {
            return $schedule->get();
        }
        return $schedule->first();
    }
    public function booked()
    {
        return $this->hasMany(Booking::class, 'schedule_id', 'id');
    }
    public function activeBooked()
    {
        return $this->hasMany(Booking::class, 'schedule_id', 'id')->where('status', 1);
    }
    public function instructorBookedUser()
    {
        return $this->activeBooked()->groupBy(['user_id']);
    }

}
