<?php

namespace Plugins\Sms\Drivers\SunwaySms;

use Exception;
use Illuminate\Support\Facades\Http;
use Plugins\Sms\Contracts\Response;
use Plugins\Sms\Contracts\SmsDriverInterface;

class SunwaySmsDriver implements SmsDriverInterface
{
    private array $data = [];
    private string $endpoint = "http://sms.sunwaysms.com/smsws/HttpService";

    public function send(string $text, array $to): Response
    {
        try {
            $smsSettings = json_decode(getConfig('sms_settings'), true);
            $smsDriverSettings = $smsSettings['drivers'][IPPANEL_SMS_DRIVER] ?? [];
            $username = $smsDriverSettings['username'] ?? '';
            $password = $smsDriverSettings['password'] ?? '';
            $res = new SunwaySmsDriverResponse();

            $response = Http::send(
                'GET',
                $this->getEndpoint(),
                [
                    'query' => [
                        'UserName' => $username,
                        'Password' => $password,
                        'To' => $to,
                        'Message' => $text,
                        'From' => $smsDriverSettings['number'],
                    ],
                ]
            );

            $res->setData($response->json());

            return $res;
        } catch (Exception $e) {
            return new SunwaySmsDriverResponse();
        }
    }

    public function getEndpoint(): string
    {
        return $this->endpoint . '?service=SendArray';
    }

    public function setData(array $data)
    {
        $this->data = $data;
    }

    public function shouldSendByPattern(array $settings): bool
    {
        return $settings['send_by_patterns'] == true;
    }
}