<?php

namespace App\Models\Contact;

use App\Enum\Contact\MessageChannel;
use App\Models\Contact\Hub\ContactMessage;
use App\Models\Solicitor\SolicitorEmailSender;
use App\Models\Solicitor\SolicitorSmsSender;
use App\Trait\BelongsToSolicitor;
use App\Trait\HasSlug;
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;

class ContactTemplate extends Model
{
    use SoftDeletes, HasSlug, BelongsToSolicitor, HasFactory;

    protected $table = 'contact_templates';

    protected $fillable = [
        'solicitor_id',
        'category_id',
        'name',
        'slug',
        'key',
        'channel',
        'is_active',
        'allow_manual_send',
        'allow_automatic_send',
        'subject',
        'body_text_template',
        'body_html_template',
        'default_sender_email_id',
        'default_sms_sender_id',
        'applies_to_type',
        'description',
        'config',
    ];

    protected $casts = [
        'channel' => MessageChannel::class,
        'is_active' => 'boolean',
        'allow_manual_send' => 'boolean',
        'allow_automatic_send' => 'boolean',
        'config' => 'array',
    ];

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

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

    public function defaultSenderEmail(): BelongsTo
    {
        return $this->belongsTo(SolicitorEmailSender::class, 'default_sender_email_id');
    }

    public function defaultSmsSender(): BelongsTo
    {
        return $this->belongsTo(SolicitorSmsSender::class, 'default_sms_sender_id');
    }

    public function messages(): HasMany
    {
        return $this->hasMany(ContactMessage::class, 'template_id');
    }

    public function includeSignature(): bool
    {
        return (bool) ($this->config['include_signature'] ?? config('contact.signature.include_by_default', true));
    }

    public function isEmail(): bool
    {
        return $this->channel === MessageChannel::EMAIL;
    }

    public function isSms(): bool
    {
        return $this->channel === MessageChannel::SMS;
    }

    public function subjectTemplate(): ?string
    {
        return $this->subject;
    }

    public function bodyTemplate(): ?string
    {
        return $this->isEmail()
            ? ($this->body_html_template ?? $this->body_text_template)
            : $this->body_text_template;
    }

    public function bodyTextTemplate(): ?string
    {
        return $this->body_text_template;
    }

    public function bodyHtmlTemplate(): ?string
    {
        return $this->body_html_template;
    }

    /*
    |--------------------------------------------------------------------------
    | Legacy field compatibility
    |--------------------------------------------------------------------------
    | The old `templates` schema used `title`, `content`, `type`.  Existing
    | `App\Components\Template\*` components continue to use those names.
    | Accessor/mutator pairs below keep that surface alive while the real
    | columns are `name`, `body_html_template`, `channel`.
    */

    public function getTitleAttribute(): ?string
    {
        return $this->attributes['name'] ?? null;
    }

    public function setTitleAttribute($value): void
    {
        $this->attributes['name'] = $value;
    }

    public function getContentAttribute(): ?string
    {
        return $this->attributes['body_html_template']
            ?? $this->attributes['body_text_template']
            ?? null;
    }

    public function setContentAttribute($value): void
    {
        $this->attributes['body_html_template'] = $value;
        if (empty($this->attributes['body_text_template'])) {
            $this->attributes['body_text_template'] = strip_tags((string) $value);
        }
    }

    public function getTypeAttribute(): ?string
    {
        return $this->attributes['channel'] ?? null;
    }

    public function setTypeAttribute($value): void
    {
        $this->attributes['channel'] = $value;
    }
}
