<?php

namespace App\Models;

use App\Traits\HasTranslations;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Test extends Model
{
    use HasFactory, SoftDeletes, HasTranslations;

    protected $fillable = [
        'name',
        'name_translations',
        'slug',
        'code',
        'description',
        'description_translations',
        'short_description',
        'short_description_translations',
        'normal_range',
        'unit',
        'price',
        'sample_type',
        'preparation_instructions',
        'estimated_time',
        'is_active',
        'test_category_id',
        'meta_title',
        'meta_description',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'is_active' => 'boolean',
        'name_translations' => 'array',
        'description_translations' => 'array',
        'short_description_translations' => 'array',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($test) {
            if (empty($test->slug)) {
                $base = Str::slug($test->name);
                $slug = $base;
                $n = 1;
                while (static::where('slug', $slug)->exists()) {
                    $slug = $base . '-' . $n;
                    $n++;
                }
                $test->slug = $slug;
            }
        });
    }

    public function category()
    {
        return $this->belongsTo(TestCategory::class, 'test_category_id');
    }

    public function packages()
    {
        return $this->belongsToMany(Package::class, 'package_tests')
            ->withPivot('sort_order');
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
