<?php

namespace Plugins\Sms\Drivers\FoodSms;

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

class FoodSmsDriver implements SmsDriverInterface
{
    private array $data = [];
    private string $endpoint = "http://api.foodsms.ir";

    public function send(string $text, array $to): Response
    {
        try {
            $smsSettings = json_decode(getConfig('sms_settings'), true);
            $smsDriverSettings = $smsSettings['drivers'][FOOD_SMS_DRIVER] ?? [];
            $apiKey = $smsDriverSettings['api_key'] ?? '';
            $res = new FoodSmsDriverResponse();
            $endpoint = str_replace('{{API_KEY}}', $apiKey, $this->getEndpoint());

            $response = Http::send(
                'GET',
                $endpoint,
                [
                    'query' => [
                        'to' => implode(',', $to),
                        'text' => $text,
                        'gateway' => $smsDriverSettings['number'],
                    ]
                ]
            );

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

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

    public function getEndpoint(): string
    {
        return $this->endpoint . '/v1/{{API_KEY}}/sms/send.json';
    }

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

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