File size: 1,603 Bytes
5f32fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php

declare(strict_types=1);

namespace App\Models;

use App\Enums\AITokenType;
use App\Models\Finance\AiChatModelPlan;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class AiModel extends Model
{
    protected $fillable = [
        'title',
        'ai_engine',
        'key',
        'is_active',
        'is_selected',
        'selected_title',
    ];

    protected $casts = [
        'ai_engine' => \App\Enums\AIEngine::class,
        'is_active' => 'boolean',
    ];

    public function tokens(): HasMany
    {
        return $this->hasMany(Token::class);
    }

    public function wordToken(): ?Token
    {
        return $this->tokens->firstWhere('type', AITokenType::WORD);
    }

    public function imageToken(): ?Token
    {
        return $this->tokens->firstWhere('type', AITokenType::IMAGE);
    }

    public function aiFinance()
    {
        return $this->hasMany(AiChatModelPlan::class, 'ai_model_id', 'id');
    }

    public static function planModels(): Collection|array
    {
        $planId = getCurrentActiveSubscription()?->getAttribute('plan_id') ?? 0;

        $query = self::query();

        if ($planId == 0) {
            $query->where('is_selected', 1);
        } else {
            $query->whereHas('aiFinance', function ($query) use ($planId) {
                $query->where('plan_id', $planId);
            });
        }

        $query->whereHas('tokens', function ($query) {
            $query->where('type', 'word');
        });

        return $query->get();
    }
}