<?php

namespace app\common\sms;

use GuzzleHttp\Client;

use app\common\sms\Isms;

use think\facade\Db;

//實作物流串接介面
class SmskingSms implements Isms
{
    private $username;
    private $password;

    public function __construct(string $username, string $password)
    {
        $this->username = $username;
        $this->password = $password;
    }

    public function sendSms(array $data)
    {
        // 將$message 轉為 Big5 編碼
        $message = mb_convert_encoding($data['message'], 'BIG5', 'UTF-8');

        $url = 'https://api.kotsms.com.tw/kotsmsapi-1.php';

        $query = http_build_query([
            'username' => $this->username,
            'password' => $this->password,
            'dstaddr' => $data['recipient'],
            'smbody' => $message,
        ]);

        $url .= '?' . $query;
        // 使用 Guzzle 發送 API 請求
        $client = new Client();
        $response = $client->request('GET', $url);

        // 處理 API 回應
        $body = $response->getBody()->getContents();
        $result =explode('=',$body);
        // $result = json_decode($body, true);
        if (is_numeric(intval($result[1])) && intval($result[1])>=0) {
            return true;
        } else {
            return false;
        }
        return true;
    }
}
