<?php

namespace App\Services\Payments;

class CodAdvanceNoticeService
{
    public const DEFAULT_AMOUNT = 300;
    public const DEFAULT_TEXT = 'ক্যাশ অন ডেলিভারিতে পণ্য গ্রহণ করতে আপনাকে {amount} অগ্রিম পেমেন্ট করতে হবে।';

    public static function build(array $config, string $currencySymbol, string $currencySymbolPosition = 'left'): array
    {
        $status = in_array(data_get($config, 'status'), [true, 1, '1'], true);
        $amount = max(0, (float) data_get($config, 'amount', self::DEFAULT_AMOUNT));
        $noticeText = trim((string) data_get($config, 'notice_text', self::DEFAULT_TEXT));

        if ($noticeText === '') {
            $noticeText = self::DEFAULT_TEXT;
        }

        $formattedAmount = self::formatAmount(
            amount: $amount,
            currencySymbol: $currencySymbol,
            currencySymbolPosition: $currencySymbolPosition,
            useBanglaDigits: (bool) preg_match('/\p{Bengali}/u', $noticeText)
        );

        return [
            'status' => $status,
            'amount' => $amount,
            'formatted_amount' => $formattedAmount,
            'notice_text' => $noticeText,
            'display_text' => strtr($noticeText, [
                '{amount}' => $formattedAmount,
                ':amount' => $formattedAmount,
                '[amount]' => $formattedAmount,
            ]),
        ];
    }

    private static function formatAmount(
        float $amount,
        string $currencySymbol,
        string $currencySymbolPosition,
        bool $useBanglaDigits
    ): string {
        $decimals = floor($amount) === $amount ? 0 : 2;
        $number = number_format($amount, $decimals, '.', ',');

        if ($useBanglaDigits) {
            $number = strtr($number, [
                '0' => '০', '1' => '১', '2' => '২', '3' => '৩', '4' => '৪',
                '5' => '৫', '6' => '৬', '7' => '৭', '8' => '৮', '9' => '৯',
            ]);
        }

        $symbol = trim($currencySymbol);

        return $currencySymbolPosition === 'right'
            ? $number . $symbol
            : $symbol . $number;
    }
}
