<?php

namespace App\Models;

use App\Traits\Archivable;
use App\Traits\CascadesArchivableRelations;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Form extends Model
{
    use HasFactory, SoftDeletes, Archivable, CascadesArchivableRelations;

    protected $table = 'forms';

    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'franchisee_id',
        'parent_form_id',
        'is_global',
        'form_setting',
        'is_required_for_translation',
        'order_no',
    ];

    protected $casts = [
        'form_setting' => 'array',
        'is_global' => 'boolean',
        'is_required_for_translation' => 'boolean',
    ];

    protected static function booted(): void
    {
        static::creating(function (self $model): void {
            if (empty($model->{$model->getKeyName()})) {
                $model->{$model->getKeyName()} = (string) Str::uuid();
            }
        });
    }

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

    public function translations(): HasMany
    {
        return $this->hasMany(FormTranslation::class, 'form_id');
    }

    public function notifications(): HasMany
    {
        return $this->hasMany(FormNotification::class, 'form_id', 'id');
    }

    public function parentForm(): BelongsTo
    {
        return $this->belongsTo(self::class, 'parent_form_id')->withTrashed();
    }

    public function franchiseOverrides(): HasMany
    {
        return $this->hasMany(self::class, 'parent_form_id');
    }
}
