<?php

namespace App\Services;

use App\Models\Setting;
use SoapClient;
use Throwable;

class PayamMatni
{
    private const WSDL = 'http://payammatni.com/webservice/send.php?wsdl';

    public static function send(string $mobile, string $content): void
    {
        if (!Setting::get('sms_enabled')) {
            return;
        }

        $username = Setting::get('sms_username', '');
        $password = Setting::get('sms_password', '');
        $fromNum  = Setting::get('sms_from_number', '');

        if (!$username || !$password || !$fromNum) {
            return;
        }

        try {
            ini_set('soap.wsdl_cache_enabled', '0');
            $soap = new SoapClient(self::WSDL);
            $soap->SendSMS($fromNum, [$mobile], $content, '0', $username, $password);
        } catch (Throwable) {
            // SMS failure is non-fatal; caller continues normally
        }
    }

    public static function sendOtp(string $mobile, string $code): void
    {
        $template = Setting::get('sms_otp_text', 'کد تأیید شما: {code}');
        $text     = str_replace('{code}', $code, $template);
        static::send($mobile, $text);
    }

    public static function sendIfEnabled(string $mobile, string $enabledKey, string $templateKey, array $vars = []): void
    {
        if (!Setting::get($enabledKey)) {
            return;
        }
        $template = Setting::get($templateKey, '');
        if (!$template) {
            return;
        }
        $text = $template;
        foreach ($vars as $var => $value) {
            $text = str_replace("{{$var}}", (string) $value, $text);
        }
        static::send($mobile, $text);
    }

    public static function getCredit(): ?string
    {
        $username = Setting::get('sms_username', '');
        $password = Setting::get('sms_password', '');

        if (!$username || !$password) {
            return null;
        }

        try {
            ini_set('soap.wsdl_cache_enabled', '0');
            $soap   = new SoapClient(self::WSDL);
            $result = $soap->GetCredit($username, $password);
            return is_numeric($result) ? number_format((float) $result) : (string) $result;
        } catch (Throwable) {
            return null;
        }
    }
}
