<?php

namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
require_once $_SERVER['DOCUMENT_ROOT'] . '/other/sms/aliyun/api_config.php';

if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php')) {
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
}

function BasicToken($aliyunsms_akid, $aliyunsms_akst, $aliyunsms_signname, $aliyunsms_notice1, $aliyunsms_notice2, $aliyunsms_notice3, $aliyunsms_notice4) {
    return "{$aliyunsms_akid},{$aliyunsms_akst},{$aliyunsms_signname},{$aliyunsms_notice1},{$aliyunsms_notice2},{$aliyunsms_notice3},{$aliyunsms_notice4}"; 
}

$web_apikey = $apiCredentials['web_apikey'] ?? '';
if (!isset($_GET['apikey']) || $_GET['apikey'] !== $web_apikey) {
    echo json_encode(['code' => 401, 'data' => 'Unauthorized access.']);
    exit;
}

class Index {

    /**
     * 使用AK&SK初始化账号Client
     * @return Dysmsapi Client
     */
    public static function createClient() {
        $config = new Config([
            "accessKeyId" => aliyunsms_akid,
            "accessKeySecret" => aliyunsms_akst
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args) {
        $data = json_decode(file_get_contents("php://input"), true);

        if (isset($data['mobile']) && isset($data['message'])) {
            $client = self::createClient();

            $templateCode = '';
            $templateParam = null;

            if (preg_match('/sendcode(\d+)/', $data['message'], $matches)) {
                $code = $matches[1]; // 获取验证码
                $templateCode = aliyunsms_notice4; // 确保对应的模板 ID
                $templateParam = json_encode(["code" => $code]); // 创建包含验证码的模板参数
            } else {
                // 处理其他消息类型
                switch ($data['message']) {
                    case 'newticket':
                        $templateCode = aliyunsms_notice1;
                        break;
                    case 'userreply':
                        $templateCode = aliyunsms_notice3;
                        break;
                    case 'adminreply':
                        $templateCode = aliyunsms_notice2;
                        break;
                    default:
                        error_log("未知的消息内容: " . $data['message']);
                        return;
                }
            }

            // 创建发送短信请求
            $sendSmsRequest = new SendSmsRequest([
                "signName" => aliyunsms_signname,
                "templateCode" => $templateCode,
                "phoneNumbers" => $data['mobile'],
                "templateParam" => isset($templateParam) ? $templateParam : null
            ]);
    
            $runtime = new RuntimeOptions([]);
            try {
    // 发送短信请求
    $response = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
    
    // 记录响应日志或其他处理
    error_log("SMS sent successfully: " . json_encode($response));
    
    // 返回成功的 JSON 数据
    echo json_encode([
        'code' => 200,
        'data' => '短信发送成功'
    ]);
} catch (Exception $error) {
    // 捕获异常并处理
    error_log("Error: " . $error->getMessage());
    if (!($error instanceof TeaError)) {
        $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
    }
    error_log("Error message: " . $error->message);
    error_log("Recommendation: " . ($error->data["Recommend"] ?? 'No recommendation available'));
    
    // 返回错误的 JSON 数据
    echo json_encode([
        'code' => 500,
        'data' => '发送短信时发生错误'
    ]);
}
        }
    }
}

$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}

if (isset($argv)) {
    Index::main(array_slice($argv, 1));
} else {
    $instance = new Index(); 
    $instance->main([]); 
}
