<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Survey extends BaseModel
{
    use HasFactory, SoftDeletes;

    protected function content(): Attribute
    {
        return Attribute::make(
            get: fn($value) => json_decode($value, true),
        );
    }

    public function scopeKeyword($query)
    {
        $keyword = request()->keyword;
        if ($keyword) {
            $keyword = trim($keyword);
            return $query->where('title', 'like', '%' . $keyword . '%');
        }
        return $query;
    }

    public function orderSurveys()
    {
        return $this->hasMany(OrderSurvey::class);
    }

    public function scopeOrders($query)
    {
        $chat_id = request()->chat_id;
        return $query->with([
            'orderSurveys' => function ($sql) use ($chat_id) {
                $sql->where('chat_id', $chat_id);
            },
            'orderSurveys:survey_id,order_id,chat_id'
        ]);
    }
}
