<?php

namespace Plugins\Sms\Drivers\KavehNegar;

use Exception;
use Illuminate\Support\Facades\Http;
use Plugins\Sms\Contracts\PatternSmsDriverInterface;
use Plugins\Sms\Contracts\Response;
use Plugins\Sms\Exceptions\SmsDriverApiException;

class KavehNegarSmsDriver implements PatternSmsDriverInterface
{
    private array $data = [];
    private string $endpoint = "https://api.kavenegar.com";
    private string $patternEndpoint = "https://api.kavenegar.com";

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

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

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

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

    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;
    }

    private function buildPatternTokens(string $patternRawText): array
    {
        preg_match_all('/{:(\w+)}/', $patternRawText, $matches);
        $extractedVars = $matches[1];
        $tokens = [];
        foreach ($extractedVars as $index => $value) {
            $tokenKey = 'token';
            if ($index > 0) {
                $tokenKey = 'token' . ($index + 1);
            }
            $tokens[$tokenKey] = str_replace(' ', "‌", $this->data[$value]);
        }
        return $tokens;
    }

    /**
     * @throws SmsDriverApiException
     */
    public function sendByPattern(string $to, string $patternName): Response
    {
        try {
            $smsSettings = json_decode(getConfig('sms_settings'), true);
            $smsDriverSettings = $smsSettings['drivers'][KAVEH_NEGAR_SMS_DRIVER] ?? [];
            $patternConfigs = $smsDriverSettings['patterns'][$patternName];
            $apiKey = $smsDriverSettings['api_key'] ?? '';
            $endpoint = str_replace('{{API_KEY}}', $apiKey, $this->getPatternEndpoint());
            $data = array_merge([
                'template' => $patternConfigs['code'],
                'receptor' => $to,
            ], $this->buildPatternTokens($patternConfigs['text']));

            $response = Http::send(
                'GET',
                $endpoint,
                [
                    'query' => $data
                ]
            );

            $res = new KavehNegarSmsDriverResponse();
            $res->setData($response->json());

            return $res;
        } catch (Exception $e) {
            throw new SmsDriverApiException($e->getMessage());
        }
    }

    public function getPatternEndpoint(): string
    {
        return $this->patternEndpoint . '/v1/{{API_KEY}}/verify/lookup.json';
    }
}