<?php

namespace App\Services;

class SmsMessageAnalyzer
{
    private const GSM_SINGLE_LIMIT = 160;

    private const GSM_MULTI_LIMIT = 153;

    private const UCS2_SINGLE_LIMIT = 70;

    private const UCS2_MULTI_LIMIT = 67;

    public function characterCount(string $message): int
    {
        return mb_strlen($message);
    }

    public function isGsm7(string $message): bool
    {
        if ($message === '') {
            return true;
        }

        return ! preg_match('/[^\x00-\x7F]/', $message);
    }

    public function estimatedParts(string $message): int
    {
        $length = $this->characterCount($message);

        if ($length === 0) {
            return 0;
        }

        if ($this->isGsm7($message)) {
            if ($length <= self::GSM_SINGLE_LIMIT) {
                return 1;
            }

            return (int) ceil($length / self::GSM_MULTI_LIMIT);
        }

        if ($length <= self::UCS2_SINGLE_LIMIT) {
            return 1;
        }

        return (int) ceil($length / self::UCS2_MULTI_LIMIT);
    }

    public function summary(string $message): string
    {
        $characters = $this->characterCount($message);
        $parts = $this->estimatedParts($message);

        if ($parts === 0) {
            return __('filament.sms_analyzer.zero_characters');
        }

        $smsLabel = $parts === 1
            ? __('filament.sms_analyzer.one_sms')
            : __('filament.sms_analyzer.multiple_sms', ['count' => $parts]);

        return __('filament.sms_analyzer.characters_sms', [
            'characters' => $characters,
            'sms' => $smsLabel,
        ]);
    }
}
