<?php

namespace Modules\Appointment\Entities;

use App\Traits\Tenantable;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Modules\Appointment\Entities\Schedule;

class Booking extends Model
{
    use Tenantable;

    protected $guarded = ['id'];

    public function schedule()
    {
        return $this->belongsTo(Schedule::class, 'schedule_id', 'id')->withDefault();
    }
    public function userInfo()
    {
        return $this->belongsTo(User::class, 'user_id', 'id')->withDefault();
    }
    public function instructor()
    {
        return $this->belongsTo(User::class, 'instructor_id', 'id')->withDefault();
    }
    public function currentStudent()
    {
        $this->where('status', 1)->where('schedule_id', $this->schedule_id)->groupBy(['user_id', 'schedule_id']);
    }
    public function getCurrentStudentAttribute()
    {
        $this->where('status', 1)->where('schedule_id', $this->schedule_id)->groupBy(['user_id', 'schedule_id']);
    }
    public static function bookingList($date, $user)
    {
        $user_id = $user->id;
        return Booking::with('schedule')->whereHas('schedule', function ($query) use ($date) {
            $query->where('schedule_date', $date);
        })->when($user->role_id == 3, function ($query) {
            $query->where('status', 1);
        })->where('user_id', $user_id)->get()->map(function ($item, $key) {
            return  [
                'id'=>$item->id,
                'schedule_id' => $item->schedule_id,
                'share_link' => $item->share_link,
                'note' => $item->note,
                'start_time' => $item->schedule->slotInfo ? $item->schedule->slotInfo->start_time : '',
                'end_time' => $item->schedule->slotInfo ? $item->schedule->slotInfo->end_time : '',
                'category' => $item->schedule->category ? $item->schedule->category->name : '',
                'subCategory' => $item->schedule->subCategory ? $item->schedule->subCategory->name : '',
                'instructor' => $item->schedule->userInfo ? $item->schedule->userInfo->name : '',
            ];
        });
    }
}
