<?php

namespace App\Models;

use App\Traits\HasTranslations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class PackageSection extends Model
{
    use HasTranslations;

    protected $fillable = ['package_id', 'name', 'name_translations', 'sort_order', 'test_category_id'];

    protected $casts = [
        'name_translations' => 'array',
    ];

    public $translatable = ['name'];

    /**
     * Ensure name is always stored as string (DB column is string).
     * Form or repeater may sometimes send array e.g. ['ar' => 'x', 'en' => 'y'].
     */
    public function setNameAttribute($value): void
    {
        if (is_array($value)) {
            $value = $value['ar'] ?? $value['en'] ?? reset($value);
        }
        $this->attributes['name'] = $value === null ? null : (string) $value;
    }

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

    public function package(): BelongsTo
    {
        return $this->belongsTo(Package::class);
    }

    public function tests(): BelongsToMany
    {
        return $this->belongsToMany(Test::class, 'package_section_test')
            ->withPivot('sort_order')
            ->orderByPivot('sort_order');
    }
}
