<?php

namespace Modules\WhatsApp\Entities;

use Illuminate\Database\Eloquent\Model;

class WaAutoReply extends Model
{
    protected $table = 'wa_auto_replies';

    protected $fillable = [
        'business_id', 'name', 'trigger', 'keyword', 'match',
        'template_id', 'body', 'stop_after', 'priority', 'active',
    ];

    protected $casts = [
        'stop_after' => 'boolean',
        'active'     => 'boolean',
        'priority'   => 'integer',
    ];

    /** Body to send: a linked template's body, else the inline body. */
    public function resolveBody(): string
    {
        if ($this->template_id) {
            $tpl = WaTemplate::find($this->template_id);
            if ($tpl) {
                return (string) $tpl->body;
            }
        }
        return (string) $this->body;
    }

    /** Does an inbound text trigger this keyword rule? */
    public function matches(string $text): bool
    {
        if ($this->trigger !== 'keyword' || empty($this->keyword)) {
            return false;
        }
        $text = mb_strtolower(trim($text));
        $keywords = array_filter(array_map('trim', explode(',', mb_strtolower($this->keyword))));

        foreach ($keywords as $kw) {
            if ($kw === '') {
                continue;
            }
            $hit = match ($this->match) {
                'exact'  => $text === $kw,
                'starts' => str_starts_with($text, $kw),
                default  => str_contains($text, $kw),
            };
            if ($hit) {
                return true;
            }
        }
        return false;
    }
}
