<?php

namespace Plugins\Sms\Drivers\Ippanel;

use Exception;
use Illuminate\Support\Facades\Http;
use IPPanel\Client;
use IPPanel\Errors\Error;
use IPPanel\Errors\HttpException;
use Plugins\Sms\Contracts\PatternSmsDriverInterface;
use Plugins\Sms\Contracts\Response;

class IppanelSmsDriver implements PatternSmsDriverInterface
{
    private array $data = [];
    private string $endpoint = "https://rest.ippanel.com";

    public function sendByPattern(string $to, string $patternName): Response
    {
        try {
            $smsSettings = json_decode(getConfig('sms_settings'), true);
            $smsDriverSettings = $smsSettings['drivers'][IPPANEL_SMS_DRIVER] ?? [];
            $apiKey = $smsDriverSettings['api_key'] ?? '';
            $res = new SunwaySmsDriverResponse();
            $patternData = $smsDriverSettings['patterns'][$patternName];
            $patternWithFilledVars = $this->fillPatternVarsWithData($patternData['text']);

            $response = Http::withToken($apiKey, 'AccessKey')->send(
                'POST',
                $this->getPatternEndpoint(),
                [
                    'json' => [
                        'pattern_code' => $patternData['code'],
                        'originator' => $smsDriverSettings['number'],
                        'recipient' => $to,
                        'values' => $patternWithFilledVars
                    ],
                ]
            );

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

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

    private function fillPatternVarsWithData(string $patternRawText): array
    {
        $vars = [];
        preg_match_all('/{:(\w+)}/', $patternRawText, $matches);
        $extractedVars = $matches[1];
        foreach ($extractedVars as $value) {
            $vars[$value] = (string)$this->data[$value];
        }
        return $vars;
    }

    public function getPatternEndpoint(): string
    {
        return $this->endpoint.'/v1/messages/patterns/send';
    }

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

            $response = Http::withHeaders(['Authorization' => "AccessKey $apiKey"])->send(
                'POST',
                $this->getEndpoint(),
                [
                    'json' => [
                        'originator' => $smsDriverSettings['number'],
                        'recipients' => $to,
                        'message' => $text
                    ],
                ]
            );

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

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

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

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

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