<?php
namespace EasyChat\Library\Support;

use EasyChat\Model\Message;








final class OfficialSupportGreetingPolicy {
    private const SESSION_GAP_SECONDS = 8 * 60 * 60;

    private $registry;

    public function __construct($registry) {
        $this->registry = $registry;
    }

    public function shouldGreet(array $profile, string $question): bool {
        if ($this->isGreeting($question)) {
            return true;
        }
        $chat_id = (int)($profile['chat_id'] ?? 0);
        $message_id = (int)($profile['message_id'] ?? 0);
        $current_date = trim((string)($profile['message_date'] ?? ''));
        if ($chat_id <= 0 || $message_id <= 0 || $current_date === '') {
            return false;
        }
        $previous = (new Message($this->registry))->getLastMessageBefore($chat_id, $message_id);
        if (!$previous) {
            return true;
        }
        $previous_date = trim((string)($previous['date_added'] ?? ''));
        if ($previous_date === '') {
            return false;
        }
         
         
        if (substr($previous_date, 0, 10) !== substr($current_date, 0, 10)) {
            return true;
        }
        $previous_time = strtotime($previous_date);
        $current_time = strtotime($current_date);
        return $previous_time !== false
            && $current_time !== false
            && $current_time > $previous_time
            && ($current_time - $previous_time) >= self::SESSION_GAP_SECONDS;
    }

    public function prepend(string $answer, string $locale): string {
        $answer = trim($answer);
        if ($answer === '') {
            return $answer;
        }
        $greeting = $locale === 'en' ? 'Hello!' : 'Здравствуйте!';
        return $greeting . "\n\n" . $answer;
    }

    public function isGreeting(string $value): bool {
        $value = mb_strtolower(trim($value), 'UTF-8');
        if ($value === '') {
            return false;
        }
        return preg_match('/(?:^|[!,.\s])(?:привет|здравствуй(?:те)?|доб(?:рое|рый)\s+(?:утро|день|вечер)|hello|hi|good\s+(?:morning|afternoon|evening))(?:[!,.\s]|$)/u', $value) === 1;
    }

    public function isGreetingOnly(string $value): bool {
        $value = mb_strtolower(trim($value), 'UTF-8');
        return preg_match('/^(?:привет|здравствуй(?:те)?|доб(?:рое|рый)\s+(?:утро|день|вечер)|hello|hi|good\s+(?:morning|afternoon|evening))[!,.\s]*$/u', $value) === 1;
    }
}
