<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service;

use app\repository\channel\ChannelRepository;
use app\service\domain\notification\driver\SmsDriver;


/**
 * 短信服务
 * @package app\service
 */
class SmsService
{
     /**
     * 是否启用短信验证码
     * @return bool
     */
    public static function isEnabled(): bool
    {
        return ConfigService::getInt('sms_verify_enabled', 0) === 1;
    }

     /**
     * 是否需要注册短信验证码
     * @return bool
     */
    public static function isRegisterSmsRequired(): bool
    {
        return self::isEnabled();
    }

     /**
     * 是否需要密码重置短信验证码
     * @return bool
     */
    public static function isPasswordResetSmsPreferred(): bool
    {
        return self::isEnabled();
    }

     /**
     * 获取短信验证码过期时间（秒）
     * @return int
     */
    public static function getCodeTtlSeconds(): int
    {
        $v = ConfigService::getInt('sms_code_ttl_seconds', 300);
        if ($v < 60) $v = 60;
        if ($v > 1800) $v = 1800;
        return $v;
    }

     /**
     * 获取短信验证码模板ID
     * @return string
     */
    public static function getVerifyCodeTemplateId(): string
    {
        try {
            $repo = app()->make(ChannelRepository::class);
            $channels = ['weapp', 'wechat', 'aliapp', 'h5', 'app'];
            foreach ($channels as $channel) {
                foreach ($repo->listNotifyConfigs($channel) as $row) {
                    if ((string)($row['driver'] ?? '') === 'auth_notice.sms' && (int)($row['status'] ?? 0) === 1) {
                        $cfg = json_decode((string)($row['config_value'] ?? '{}'), true);
                        $tid = trim((string)(is_array($cfg) ? ($cfg['template_id'] ?? '') : ''));
                        if ($tid !== '') {
                            return $tid;
                        }
                    }
                }
            }
        } catch (\Throwable $e) {
        }
        return '';
    }

     /**
     * 发送短信验证码
     * @param string $phone
     * @param string $code
     * @param string $scene
     * @return array
     */
    public static function sendVerifyCode(string $phone, string $code, string $scene): array
    {
        $templateId = self::getVerifyCodeTemplateId();
        if ($templateId === '') {
            return ['ok' => false, 'msg' => ''];
        }

        try {
            $driver = app()->make(SmsDriver::class);
        } catch (\Throwable $e) {
            return ['ok' => false, 'msg' => '' . $e->getMessage()];
        }

        $result = $driver->send(
            ['phone' => $phone],
            $templateId,
            ['code' => $code, 'scene' => $scene],
            [],
        );

        if ($result['code'] === 0) {
            return ['ok' => true, 'msg' => $result['msg']];
        }
        return ['ok' => false, 'msg' => $result['msg']];
    }
}
