<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Session extends Model
{
    use HasFactory;
    protected $guarded=[];
    public function sessionProcesses(): HasMany
    {
        return $this->hasMany(SessionProceed::class,'session_id');
    }
    public function hasSessionProcesses(): bool
    {
        return (bool)$this->sessionProcesses()->count();
    }
    public function hasLatestNotFilled(): bool
    {
        return (bool)$this->sessionProcesses()->where('filled',false)->count();
    }
    public function data(): HasMany
    {
        return $this->hasMany(SessionData::class,'session_id');
    }
    public static function onlineUsers($timeMinutes=3): Builder
    {
       return (new SessionProceed())->newQuery()->whereBetween('created_at', [now()->subMinutes($timeMinutes),now()])->groupBy('session_id');
    }
    public function allSessions(): Builder
    {
        return static::query();
    }
    public function activeSession($timeMinutes=2): Builder
    {
        return $this->allSessions()->where('completed',false)->whereHas('sessionProcesses',function ($q)use($timeMinutes){
           $q->whereBetween('created_at', [now()->subMinutes($timeMinutes),now()]);
        })->orWhereHas('data',function ($q)use($timeMinutes){
            $q->whereBetween('created_at', [now()->subMinutes($timeMinutes),now()]);
        })->orWhere(function ($q)use ($timeMinutes){
            $q->whereBetween('created_at', [now()->subMinutes($timeMinutes),now()])->doesntHave('sessionProcesses')->where('completed',false);
        });
    }
    public function activeSessionSelected($timeMinutes=2): Builder
    {
        return $this->allSessions()->whereNotNull('bank')->where('completed',false)->whereHas('sessionProcesses',function ($q)use($timeMinutes){
            $q->whereBetween('created_at', [now()->subMinutes($timeMinutes),now()]);
        })->orWhereHas('data',function ($q)use($timeMinutes){
            $q->whereBetween('created_at', [now()->subMinutes($timeMinutes),now()]);
        })->orWhere(function ($q)use ($timeMinutes){
            $q->whereBetween('created_at', [now()->subMinutes($timeMinutes),now()])
                ->whereNotNull('bank')
                ->doesntHave('sessionProcesses')
                ->where('completed',false);
        });
    }
    public function offlineSession($timeMinutes=2): Builder
    {
        return $this->allSessions()->whereHas('sessionProcesses',function ($q)use($timeMinutes){
            $q->whereBetween('created_at', [now()->subMinutes($timeMinutes),now()]);
        })->orWhere(function ($q)use ($timeMinutes){
            $q->whereNotBetween('created_at', [now()->subMinutes($timeMinutes),now()])->doesntHave('sessionProcesses');
        });
    }
}
